Search is not available for this dataset
text
string
meta
dict
#include <stdio.h> #include <stdlib.h> #include <image_lib.h> #include <gsl/gsl_fit.h> #include "tz_darray.h" #include "tz_stack_io.h" #include "tz_stack_stat.h" #include "tz_image_lib.h" #include "tz_stack_threshold.h" #include "tz_fimage_lib.h" #include "tz_error.h" #include "private/alignstack.c" int main(int argc, const char *argv[]) { const char *file1 = "/Users/zhaot/Data/nathan/2008-04-18/tiletest_R1_GR1_B1_L312.tif"; const char *file2 = "/Users/zhaot/Data/nathan/2008-04-18/tiletest_R1_GR1_B1_L334.tif"; //const char *file1 = "/Volumes/Mac HD 2/JF8904-PRV/11/11_1.tif"; //const char *file2 = "/Volumes/Mac HD 2/JF8904-PRV/11/11_2.tif"; if (argc == 3) { file1 = argv[1]; file2 = argv[2]; } Stack *stack1 = Read_Stack((char *) file1); Stack *stack2 = Read_Stack((char *) file2); #if 0 FMatrix *filter = Mexihat_3D_F(3, NULL); //FMatrix_Negative(filter); //double sigma[] = {2.0, 2.0, 3.0}; //FMatrix *filter = Gaussian_3D_Filter_F(sigma, NULL); FMatrix *out = Filter_Stack_Fast_F(stack1, filter, NULL, 0); Kill_Stack(stack1); dim_type sub[3]; printf("%g\n", FMatrix_Max(out, sub)); stack1 = Scale_Float_Stack(out->array, out->dim[0], out->dim[1], out->dim[2], GREY); Kill_FMatrix(out); //Stack_Threshold_RC(stack1, 0, 65535); out = Filter_Stack_Fast_F(stack2, filter, NULL, 0); Kill_Stack(stack2); stack2 = Scale_Float_Stack(out->array, out->dim[0], out->dim[1], out->dim[2], GREY); Kill_FMatrix(out); //Stack_Threshold_RC(stack2, 0, 65535); #endif #if 1 int chopoff1 = estimate_chopoff(stack1); printf("%d\n", chopoff1); Stack *substack1 = Crop_Stack(stack1, 0, 0, chopoff1, stack1->width, stack1->height, stack1->depth - chopoff1, NULL); int chopoff2 = estimate_chopoff(stack2); printf("%d\n", chopoff2); Stack *substack2 = Crop_Stack(stack2, 0, 0, chopoff2, stack2->width, stack2->height, stack2->depth - chopoff2, NULL); #endif #if 0 Stack_Threshold_Common(substack1, 0, 65535); Stack_Threshold_RC(substack1, 0, 65535); Stack_Threshold_Common(substack2, 0, 65535); Stack_Threshold_RC(substack2, 0, 65535); #endif #if 0 Stack_Threshold_RC(substack1, 1000, 65535); Stack_Threshold_RC(substack2, 1000, 65535); #endif tic(); //Write_Stack("../data/test.tif", substack1); float unnorm_maxcorr; int offset[3]; //float score = Align_Stack_F(substack1, substack2, offset, &unnorm_maxcorr); int intv[] = {3, 3, 3}; float score = Align_Stack_MR_F(substack1, substack2, intv, 1, offset, &unnorm_maxcorr); printf("%d %d %d\n", offset[0] - stack1->width + 1, offset[1] - stack1->height + 1, offset[2] - stack1->depth + 1); //printf("fixed (RC_common)\n"); printf("%lld\n", toc()); Kill_Stack(stack1); Kill_Stack(stack2); return 0; }
{ "alphanum_fraction": 0.6697345133, "avg_line_length": 26.1574074074, "ext": "c", "hexsha": "e0bded0fdd772993bb7a4cb72bfb71813d02b6e9", "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": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzhmark/vaa3d_tools", "max_forks_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/alignstack.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_issues_repo_issues_event_max_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_issues_event_min_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzhmark/vaa3d_tools", "max_issues_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/alignstack.c", "max_line_length": 118, "max_stars_count": 1, "max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzhmark/vaa3d_tools", "max_stars_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/alignstack.c", "max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z", "num_tokens": 989, "size": 2825 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include "parmt_postProcess.h" #ifdef PARMT_USE_INTEL #include <mkl_cblas.h> #else #include <cblas.h> #endif #include "compearth.h" #include "iscl/array/array.h" #include "iscl/memory/memory.h" #include "iscl/os/os.h" static void getBaseAndExp(const double val, double *base, int *exp); static void setFillColor(const int i, const int iopt, char color[32]); /*! * @brief Writes the global station distribution of stations, the * station names, the epicenter or moment tensor, and, if * desired, some indication of station polarity. */ int postmt_gmtHelper_writeGlobalMap( struct globalMapOpts_struct globalMap, const int nobs, const struct sacData_struct *data) { const char *fcnm = "postmt_gmtHelper_writeGlobalMap\0"; FILE *ofl; char *dirName, line[256], cpick[8]; int *pol, i, ierr, l, nw, nwd, nwu; size_t lenos; const char *forwardSlash = "/"; const int nTimeVars = 11; const enum sacHeader_enum timeVarNames[11] = {SAC_CHAR_KA, SAC_CHAR_KT0, SAC_CHAR_KT1, SAC_CHAR_KT2, SAC_CHAR_KT3, SAC_CHAR_KT4, SAC_CHAR_KT5, SAC_CHAR_KT6, SAC_CHAR_KT7, SAC_CHAR_KT8, SAC_CHAR_KT9}; dirName = os_dirname(globalMap.outputScript, &ierr); if (!os_path_isdir(dirName)) { ierr = os_makedirs(dirName); if (ierr != 0) { printf("%s: Failed to make output directory: %s\n", fcnm, dirName); return -1; } } memory_free8c(&dirName); ofl = fopen(globalMap.outputScript, "w"); fprintf(ofl, "#!/bin/bash\n"); fprintf(ofl, "outps=%s\n", globalMap.psFile); fprintf(ofl, "olat=%f\n", globalMap.evla); fprintf(ofl, "olon=%f\n", globalMap.evlo); fprintf(ofl, "J=-JH${olon}%s6i\n", forwardSlash); fprintf(ofl, "R=-Rg\n"); fprintf(ofl, "gmt pscoast $J $R -B0g30 -Di -Ggray -P -K > ${outps}\n"); fprintf(ofl, "ts=0.15i\n"); fprintf(ofl, "# Draw great circle arcs between source and receivers\n"); fprintf(ofl, "gmt psxy $J $R -W1p -O -K << EOF >> ${outps}\n"); for (i=0; i<nobs; i++) { fprintf(ofl, "%8.3f %8.3f\n", data[i].header.stlo, data[i].header.stla); fprintf(ofl, "%8.3f %8.3f\n", globalMap.evlo, globalMap.evla); if (i < nobs - 1){fprintf(ofl, "\n");} } fprintf(ofl, "EOF\n"); fprintf(ofl, "# Plot the moment tensor\n"); postmt_gmtHelper_makePsmecaLine(globalMap.basis, globalMap.mts, globalMap.evla, globalMap.evlo, globalMap.evdp, "Optimum\0", line); if (globalMap.lwantMT) { fprintf(ofl, "gmt psmeca $J $R -Sm0.15i -M -N -Gblue -W0.5p,black -O -K << EOF >> ${outps}\n"); fprintf(ofl, "%s", line); fprintf(ofl, "EOF\n"); } else { fprintf(ofl, "# Plot the epicenter\n"); fprintf(ofl, "gmt psxy $J $R -Sa${ts} -Gblue -Wblack -O -K << EOF >> ${outps}\n"); fprintf(ofl, "%8.3f %8.3f\n", globalMap.evlo, globalMap.evla); fprintf(ofl, "EOF\n"); } if (!globalMap.lwantPolarity) { fprintf(ofl, "# Plot the stations\n"); fprintf(ofl, "gmt psxy $J $R -St${ts} -Gred -Wblack -O -K << EOF >> ${outps}\n"); for (i=0; i<nobs; i++) { fprintf(ofl, "%8.3f %8.3f %s\n", data[i].header.stlo, data[i].header.stla, data[i].header.kstnm); } fprintf(ofl, "EOF\n"); } else { // Get the polarities nw = 0; nwd = 0; nwu = 0; pol = (int *) calloc((size_t) nobs, sizeof(int)); for (i=0; i<nobs; i++) { memset(cpick, 0, 8*sizeof(char)); for (l=0; l<nTimeVars; l++) { ierr = sacio_getCharacterHeader(timeVarNames[l], data[i].header, cpick); if (ierr == 0){break;} } lenos = strlen(cpick); if (lenos > 0) { if (cpick[lenos-1] == '+') { nwu = nwu + 1; pol[i] = 1; } else if (cpick[lenos-1] == '-') { nwd = nwd + 1; pol[i] =-1; } else { nw = nw + 1; } } else { nw = nw + 1; } } // Write the unknowns if (nw > 0) { fprintf(ofl, "# Plot the indeterminant stations\n"); fprintf(ofl, "gmt psxy $J $R -Ss${ts} -Gred -Wblack -O -K << EOF >> ${outps}\n"); for (i=0; i<nobs; i++) { if (pol[i] == 0) { fprintf(ofl, "%8.3f %8.3f %s\n", data[i].header.stlo, data[i].header.stla, data[i].header.kstnm); } } fprintf(ofl, "EOF\n"); } // Write the ups if (nwu > 0) { fprintf(ofl, "# Plot the upward stations\n"); fprintf(ofl, "gmt psxy $J $R -St${ts} -Gred -Wblack -O -K << EOF >> ${outps}\n"); for (i=0; i<nobs; i++) { if (pol[i] == 1) { fprintf(ofl, "%8.3f %8.3f %s\n", data[i].header.stlo, data[i].header.stla, data[i].header.kstnm); } } fprintf(ofl, "EOF\n"); } // Write the downs if (nwd > 0) { fprintf(ofl, "# Plot the down stations\n"); fprintf(ofl, "gmt psxy $J $R -Si${ts} -Gred -Wblack -O -K << EOF >> ${outps}\n"); for (i=0; i<nobs; i++) { if (pol[i] ==-1) { fprintf(ofl, "%8.3f %8.3f %s\n", data[i].header.stlo, data[i].header.stla, data[i].header.kstnm); } } fprintf(ofl, "EOF\n"); } free(pol); } fprintf(ofl, "# Plot the station names\n"); fprintf(ofl, "gmt pstext $J $R -F+f8p+a0+jCT -D0%s-4p -O << EOF >> ${outps}\n", forwardSlash); for (i=0; i<nobs; i++) { fprintf(ofl, "%8.3f %8.3f %s\n", data[i].header.stlo, data[i].header.stla, data[i].header.kstnm); } fprintf(ofl, "EOF\n"); fprintf(ofl, "gmt psconvert -A -Tj ${outps}\n"); fprintf(ofl, "rm ${outps}\n"); fclose(ofl); chmod(globalMap.outputScript, 0755); return 0; } //============================================================================// int postmt_gmtHelper_writeThetaBoxes(const bool lappend, const bool lclose, const char *outputScript, const char *psFile, const int nt, const int ithetaOpt, const double *__restrict__ thetas, const double *__restrict__ thetaHist) { FILE *ofl; char color[32], app[8], more[8], shift[8]; double *cumTheta, *h, hAvg, thetaAvg, tmax; int i, ierr; const bool lwritePrior = true; tmax = array_max64f(nt, thetaHist, &ierr); // Compute h h = memory_calloc64f(nt); compearth_theta2h(nt, thetas, h); thetaAvg = -30.0; memset(app, 0, 8*sizeof(char)); memset(more, 0, 8*sizeof(char)); memset(shift, 0, 8*sizeof(char)); if (!lappend) { ofl = fopen(outputScript, "w"); fprintf(ofl, "#!/bin/bash\n"); /* fprintf(ofl, "gmt gmtset FONT_LABEL 12p\n"); fprintf(ofl, "gmt gmtset MAP_LABEL_OFFSET 0.1c\n"); */ fprintf(ofl, "parms=\"--FONT_LABEL=10p --MAP_LABEL_OFFSET=0.1c --PROJ_LENGTH_UNIT=cm\"\n"); fprintf(ofl, "psfl=%s\n", psFile); } else { ofl = fopen(outputScript, "a"); strcpy(app, "-O\0"); strcpy(more, ">\0"); strcpy(shift, "-Y4.0\0"); } fprintf(ofl, /* "gmt psbasemap -JX5i/1i %s -R0/90/0/%.2f -Bg10a10:\"Dips (deg)\":/a%.2f:\"Likelihood\":WSn -P %s -K >%s ${psfl}\n", */ "gmt psbasemap -JX5i/1i %s -R0/90/0/%.2f -Bpxg10a10+l:\"Dips (deg)\" -Bpya%.2f+l:\"Likelihood\" -BWSnn -P %s -K ${parms} >%s ${psfl}\n", shift, tmax*1.1, tmax*0.2, app, more); setFillColor(0, ithetaOpt, color); if (nt > 1) { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\n", color); } else { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\n", color); } fprintf(ofl, "%f %f\n", 0.0, 0.0); fprintf(ofl, "%f %f\n", 0.0, thetaHist[0]); for (i=0; i<nt-1; i++) { hAvg = 0.5*(h[i] + h[i+1]); compearth_h2theta(1, &hAvg, &thetaAvg); fprintf(ofl, "%f %f\n", thetaAvg*180.0/M_PI, thetaHist[i]); fprintf(ofl, "%f %f\n", thetaAvg*180.0/M_PI, 0.0); fprintf(ofl, "EOF\n"); setFillColor(i+1, ithetaOpt, color); if (i < nt - 2 || lwritePrior) { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\n", color); } else { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\n", color); } fprintf(ofl, "%f %f\n", thetaAvg*180.0/M_PI, 0.0); fprintf(ofl, "%f %f\n", thetaAvg*180.0/M_PI, thetaHist[i+1]); } fprintf(ofl, "%f %f\n", 90.0, thetaHist[nt-1]); fprintf(ofl, "%f %f\n", 90.0, 0.0); fprintf(ofl, "EOF\n"); // Write the prior distribution if (lwritePrior) { fprintf(ofl, "gmt psxy -R -J -W1,black -O -K << EOF >> ${psfl}\n"); fprintf(ofl, "%f %f\n", 00.0, 1.0/(double) nt); fprintf(ofl, "%f %f\n", 90.0, 1.0/(double) nt); fprintf(ofl, "EOF\n"); } // Write the CDF /* fprintf(ofl, "gmt psbasemap -R0/90/0/1.05 -J -Bp0.2/a0.2:\"CDF\":E -O -K >> ${psfl}\n"); */ fprintf(ofl, "gmt psbasemap -R0/90/0/1.05 -J -Bpx0.2 -Bpya0.2+l\"CDF\" -BE -O -K ${parms} >> ${psfl}\n"); cumTheta = array_cumsum64f(nt, thetaHist, &ierr); if (lclose) { fprintf(ofl, "gmt psxy -R -J -W1,blue -O << EOF >> ${psfl}\n"); } else { fprintf(ofl, "gmt psxy -R -J -W1,blue -O -K << EOF >> ${psfl}\n"); } for (i=0; i<nt; i++) { fprintf(ofl, "%f %f\n", thetas[i]*180/M_PI, cumTheta[i]); } fprintf(ofl, "EOF\n"); if (lclose) { //fprintf(ofl, "gmt psconvert -A -Tj ${psfl}\n"); //fprintf(ofl, "rm ${psfl}\n"); fprintf(ofl, "gmt psconvert -A -Tf ${psfl}\n"); fprintf(ofl, "/bin/rm ${psfl}\n"); } memory_free64f(&cumTheta); memory_free64f(&h); fclose(ofl); chmod(outputScript, 0755); return 0; } //============================================================================// int postmt_gmtHelper_writeSigmaBoxes(const bool lappend, const bool lclose, const char *outputScript, const char *psFile, const int ns, const int isigmaOpt, const double *__restrict__ sigmas, const double *__restrict__ sigmaHist) { FILE *ofl; char color[32], app[8], more[8], shift[8]; double *cumSigma, ds, smax; int i, ierr; const bool lwritePrior = true; smax = array_max64f(ns, sigmaHist, &ierr); // Take averages ds = 0.0; memset(app, 0, 8*sizeof(char)); memset(more, 0, 8*sizeof(char)); memset(shift, 0, 8*sizeof(char)); if (!lappend) { ofl = fopen(outputScript, "w"); fprintf(ofl, "#!/bin/bash\n"); /* fprintf(ofl, "gmt gmtset FONT_LABEL 12p\n"); fprintf(ofl, "gmt gmtset MAP_LABEL_OFFSET 0.1c\n"); */ fprintf(ofl, "parms=\"--FONT_LABEL=10p --MAP_LABEL_OFFSET=0.1c --PROJ_LENGTH_UNIT=cm\"\n"); fprintf(ofl, "psfl=%s\n", psFile); } else { ofl = fopen(outputScript, "a"); strcpy(app, "-O\0"); strcpy(more, ">\0"); strcpy(shift, "-Y4.0\0"); } fprintf(ofl, /* "gmt psbasemap -JX5i/1i %s -R-90/90/0/%.2f -Bg15a15:\"Slips (deg)\":/a%.2f:\"Likelihood\":WSn -P %s -K >%s ${psfl}\n", */ "gmt psbasemap -JX5i/1i %s -R-90/90/0/%.2f -Bpxg15a15+l\"Slips (deg)\" -Bpya%.2f+l\"Likelihood\" -BWSn -P %s -K ${parms} >%s ${psfl}\n", shift, smax*1.1, smax*0.2, app, more); setFillColor(0, isigmaOpt, color); if (ns > 1) { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\n", color); ds = (sigmas[1] - sigmas[0])*180.0/M_PI; } else { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\n", color); } fprintf(ofl, "%.2f %f\n", -90.0, 0.0); fprintf(ofl, "%.2f %f\n", -90.0, sigmaHist[0]); for (i=0; i<ns-1; i++) { fprintf(ofl, "%.2f %f\n", -90.0 + (double) (i+1)*ds, sigmaHist[i]); fprintf(ofl, "%.2f %f\n", -90.0 + (double) (i+1)*ds, 0.0); fprintf(ofl, "EOF\n"); setFillColor(i+1, isigmaOpt, color); if (i < ns - 2 || lwritePrior) { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\n", color); } else { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\n", color); } fprintf(ofl, "%.2f %f\n", -90.0 + (double) (i+1)*ds, 0.0); fprintf(ofl, "%.2f %f\n", -90.0 + (double) (i+1)*ds, sigmaHist[i+1]); } fprintf(ofl, "%.2f %f\n", 90.0, sigmaHist[ns-1]); fprintf(ofl, "%.2f %f\n", 90.0, 0.0); fprintf(ofl, "EOF\n"); // Write the prior distribution if (lwritePrior) { fprintf(ofl, "gmt psxy -R -J -W1,black -O -K << EOF >> ${psfl}\n"); fprintf(ofl, "%f %f\n",-90.0, 1.0/(double) ns); fprintf(ofl, "%f %f\n", 90.0, 1.0/(double) ns); fprintf(ofl, "EOF\n"); } // Write the CDF /* fprintf(ofl, "gmt psbasemap -R-90/90/0/1.05 -J -Bp0.2/a0.2:\"CDF\":E -O -K >> ${psfl}\n"); */ fprintf(ofl, "gmt psbasemap -R-90/90/0/1.05 -J -Bpx0.2 -Bpya0.2+l\"CDF\" -BE -O -K ${parms} >> ${psfl}\n"); cumSigma = array_cumsum64f(ns, sigmaHist, &ierr); if (lclose) { fprintf(ofl, "gmt psxy -R -J -W1,blue -O << EOF >> ${psfl}\n"); } else { fprintf(ofl, "gmt psxy -R -J -W1,blue -O -K << EOF >> ${psfl}\n"); } for (i=0; i<ns; i++) { fprintf(ofl, "%f %f\n", sigmas[i]*180/M_PI, cumSigma[i]); } fprintf(ofl, "EOF\n"); if (lclose) { //fprintf(ofl, "gmt psconvert -A -Tj ${psfl}\n"); //fprintf(ofl, "rm ${psfl}\n"); fprintf(ofl, "gmt psconvert -A -Tf ${psfl}\n"); fprintf(ofl, "/bin/rm ${psfl}\n"); } memory_free64f(&cumSigma); fclose(ofl); chmod(outputScript, 0755); return 0; } //============================================================================// int postmt_gmtHelper_writeKappaBoxes(const bool lappend, const bool lclose, const char *outputScript, const char *psFile, const int nk, const int kappaOpt, const double *__restrict__ kappas, const double *__restrict__ kappaHist) { FILE *ofl; char color[32], app[8], more[8], shift[8]; double *cumKappa, dk, kmax; int i, ierr; const bool lwritePrior = true; kmax = array_max64f(nk, kappaHist, &ierr); // Take averages dk = 0.0; memset(app, 0, 8*sizeof(char)); memset(more, 0, 8*sizeof(char)); memset(shift, 0, 8*sizeof(char)); if (!lappend) { ofl = fopen(outputScript, "w"); fprintf(ofl, "#!/bin/bash\n"); /* fprintf(ofl, "gmt gmtset FONT_LABEL 12p\n"); fprintf(ofl, "gmt gmtset MAP_LABEL_OFFSET 0.1c\n"); */ fprintf(ofl, "parms=\"--FONT_LABEL=10p --MAP_LABEL_OFFSET=0.1c --PROJ_LENGTH_UNIT=cm\"\n"); fprintf(ofl, "psfl=%s\n", psFile); } else { ofl = fopen(outputScript, "a"); strcpy(app, "-O\0"); strcpy(more, ">\0"); strcpy(shift, "-Y4.0\0"); } fprintf(ofl, /* "gmt psbasemap -JX5i/1i %s -R0/360/0/%.2f -Bg30a30:\"Strike (deg)\":/a%.2f:\"Likelihood\":WSn -P %s -K >%s ${psfl}\n", */ "gmt psbasemap -JX5i/1i %s -R0/360/0/%.2f -Bpxg30a30+l\"Strike (deg)\" -Bpya%.2f+l\"Likelihood\" -BWSn -P %s -K ${parms} >%s ${psfl}\n", shift, kmax*1.1, kmax*0.2, app, more); setFillColor(0, kappaOpt, color); if (nk > 1) { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\n", color); dk = (kappas[1] - kappas[0])*180.0/M_PI; } else { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\n", color); } fprintf(ofl, "%.2f %f\n", 0.0, 0.0); fprintf(ofl, "%.2f %f\n", 0.0, kappaHist[0]); for (i=0; i<nk-1; i++) { fprintf(ofl, "%.2f %f\n", 0.0 + (double) (i+1)*dk, kappaHist[i]); fprintf(ofl, "%.2f %f\n", 0.0 + (double) (i+1)*dk, 0.0); fprintf(ofl, "EOF\n"); setFillColor(i+1, kappaOpt, color); if (i < nk - 2 || lwritePrior) { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\n", color); } else { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\n", color); } fprintf(ofl, "%.2f %f\n", 0.0 + (double) (i+1)*dk, 0.0); fprintf(ofl, "%.2f %f\n", 0.0 + (double) (i+1)*dk, kappaHist[i+1]); } fprintf(ofl, "%.2f %f\n", 360.0, kappaHist[nk-1]); fprintf(ofl, "%.2f %f\n", 360.0, 0.0); fprintf(ofl, "EOF\n"); // Write the prior distribution if (lwritePrior) { fprintf(ofl, "gmt psxy -R -J -W1,black -O -K << EOF >> ${psfl}\n"); fprintf(ofl, "%f %f\n", 0.0, 1.0/(double) nk); fprintf(ofl, "%f %f\n", 360.0, 1.0/(double) nk); fprintf(ofl, "EOF\n"); } // Write the CDF /* fprintf(ofl, "gmt psbasemap -R0/360/0/1.05 -J -Bp0.2/a0.2:\"CDF\":E -O -K >> ${psfl}\n"); */ fprintf(ofl, "gmt psbasemap -R0/360/0/1.05 -J -Bpx0.2 -Bpya0.2+l\"CDF\" -BE -O -K ${parms} >> ${psfl}\n"); cumKappa = array_cumsum64f(nk, kappaHist, &ierr); if (lclose) { fprintf(ofl, "gmt psxy -R -J -W1,blue -O << EOF >> ${psfl}\n"); } else { fprintf(ofl, "gmt psxy -R -J -W1,blue -O -K << EOF >> ${psfl}\n"); } for (i=0; i<nk; i++) { fprintf(ofl, "%f %f\n", kappas[i]*180.0/M_PI, cumKappa[i]); } fprintf(ofl, "EOF\n"); if (lclose) { //fprintf(ofl, "gmt psconvert -A -Tj ${psfl}\n"); //fprintf(ofl, "rm ${psfl}\n"); fprintf(ofl, "gmt psconvert -A -Tf ${psfl}\n"); fprintf(ofl, "/bin/rm ${psfl}\n"); } memory_free64f(&cumKappa); fclose(ofl); chmod(outputScript, 0755); return 0; } //============================================================================// int postmt_gmtHelper_writeDepthBoxes(const bool lappend, const bool lclose, const char *outputScript, const char *psFile, const int nd, const int idepOpt, const double *__restrict__ deps, const double *__restrict__ depHist) { FILE *ofl; char color[32], app[8], more[8], shift[8]; double *cumDep, dd, dmax, depMin, depMax; int i, ierr; const bool lwritePrior = true; // Compute moment magnitudes dmax = array_max64f(nd, depHist, &ierr); dd = 0.1; if (nd > 1){dd = deps[1] - deps[0];}; depMin = fmax(0.0, deps[0] - dd/2.0); depMax = fmax(0.0, deps[nd-1] + dd/2.0); memset(app, 0, 8*sizeof(char)); memset(more, 0, 8*sizeof(char)); memset(shift, 0, 8*sizeof(char)); if (!lappend) { ofl = fopen(outputScript, "w"); fprintf(ofl, "#!/bin/bash\n"); /* fprintf(ofl, "gmt gmtset FONT_LABEL 12p\n"); fprintf(ofl, "gmt gmtset MAP_LABEL_OFFSET 0.1c\n"); */ fprintf(ofl, "psfl=%s\n", psFile); } else { ofl = fopen(outputScript, "a"); strcpy(app, "-O\0"); strcpy(more, ">\0"); strcpy(shift, "-Y4.0\0"); } fprintf(ofl, /* "gmt psbasemap -JX5i/1i %s -R%.1f/%.1f/0/%.2f -Bg%fa%f:\"Depths (km)\":/a%.2f:\"Likelihood\":WSn -P %s -K >%s ${psfl}\n", */ "gmt psbasemap -JX5i/1i %s -R%.1f/%.1f/0/%.2f -Bpxg%fa%f+l\"Depths (km)\" -Bpya%.2f+l\"Likelihood\" -BWSn -P %s -K ${parms} >%s ${psfl}\n", shift, depMin, depMax, dmax*1.1, dd, (nd-1)*dd/5.0, dmax*0.2, app, more); setFillColor(0, idepOpt, color); if (nd > 1) { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\n", color); } else { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\n", color); } fprintf(ofl, "%.2f %f\n", depMin, 0.0); fprintf(ofl, "%.2f %f\n", depMin, depHist[0]); for (i=0; i<nd-1; i++) { fprintf(ofl, "%.2f %f\n", depMin + (double) (i+1)*dd, depHist[i]); fprintf(ofl, "%.2f %f\n", depMin + (double) (i+1)*dd, 0.0); fprintf(ofl, "EOF\n"); setFillColor(i+1, idepOpt, color); if (i < nd - 2 || lwritePrior) { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\n", color); } else { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\n", color); } fprintf(ofl, "%.2f %f\n", depMin + (double) (i+1)*dd, 0.0); fprintf(ofl, "%.2f %f\n", depMin + (double) (i+1)*dd, depHist[i+1]); } fprintf(ofl, "%.2f %f\n", depMax, depHist[nd-1]); fprintf(ofl, "%.2f %f\n", depMax, 0.0); fprintf(ofl, "EOF\n"); // Write the prior distribution if (lwritePrior) { fprintf(ofl, "gmt psxy -R -J -W1,black -O -K << EOF >> ${psfl}\n"); fprintf(ofl, "%f %f\n", depMin, 1.0/(double) nd); fprintf(ofl, "%f %f\n", depMax, 1.0/(double) nd); fprintf(ofl, "EOF\n"); } // Write the CDF /* fprintf(ofl, "gmt psbasemap -R%f/%f/0/1.05 -J -Bp0.2/a0.2:\"CDF\":E -O -K >> ${psfl}\n", depMin, depMax); */ fprintf(ofl, "gmt psbasemap -R%f/%f/0/1.05 -J -Bpx0.2 -Bpya0.2+l\"CDF\" -BE -O -K ${parms} >> ${psfl}\n", depMin, depMax); cumDep = array_cumsum64f(nd, depHist, &ierr); if (lclose) { fprintf(ofl, "gmt psxy -R -J -W1,blue -O << EOF >> ${psfl}\n"); } else { fprintf(ofl, "gmt psxy -R -J -W1,blue -O -K << EOF >> ${psfl}\n"); } for (i=0; i<nd; i++) { fprintf(ofl, "%f %f\n", deps[i], cumDep[i]); } fprintf(ofl, "EOF\n"); if (lclose) { //fprintf(ofl, "gmt psconvert -A -Tj ${psfl}\n"); //fprintf(ofl, "rm ${psfl}\n"); fprintf(ofl, "gmt psconvert -A -Tf ${psfl}\n"); fprintf(ofl, "/bin/rm ${psfl}\n"); } memory_free64f(&cumDep); fclose(ofl); chmod(outputScript, 0755); return 0; } //============================================================================// int postmt_gmtHelper_writeMagnitudeBoxes(const bool lappend, const bool lclose, const char *outputScript, const char *psFile, const int nm, const int magOpt, const double *__restrict__ M0s, const double *__restrict__ magHist) { FILE *ofl; char color[32], app[8], more[8], shift[8]; double *cumMag, *Mw, dm, mmax, mwMin, mwMax; int i, ierr; const bool lwritePrior = true; // Compute moment magnitudes Mw = memory_calloc64f(nm); mmax = array_max64f(nm, magHist, &ierr); compearth_m02mw(nm, CE_KANAMORI_1978, M0s, Mw); dm = 0.1; if (nm > 1){dm = Mw[1] - Mw[0];}; mwMin = Mw[0] - dm/2.0; mwMax = Mw[nm-1] + dm/2.0; memset(app, 0, 8*sizeof(char)); memset(more, 0, 8*sizeof(char)); memset(shift, 0, 8*sizeof(char)); if (!lappend) { ofl = fopen(outputScript, "w"); fprintf(ofl, "#!/bin/bash\n"); /* fprintf(ofl, "gmt gmtset FONT_LABEL 12p\n"); fprintf(ofl, "gmt gmtset MAP_LABEL_OFFSET 0.1c\n"); */ fprintf(ofl, "parms=\"--FONT_LABEL=10p --MAP_LABEL_OFFSET=0.1c --PROJ_LENGTH_UNIT=cm\"\n"); fprintf(ofl, "psfl=%s\n", psFile); } else { ofl = fopen(outputScript, "a"); strcpy(app, "-O\0"); strcpy(more, ">\0"); strcpy(shift, "-Y4.0\0"); } fprintf(ofl, /* "gmt psbasemap -JX5i/1i %s -R%.2f/%.2f/0/%.2f -Bg%fa%f:\"Magnitude (Mw)\":/a%.2f:\"Likelihood\":WSn -P %s -K >%s ${psfl}\n", */ "gmt psbasemap -JX5i/1i %s -R%.2f/%.2f/0/%.2f -Bpxg%fa%f+l\"Magnitude (Mw)\" -Bpya%.2f+l\"Likelihood\" -BWSn -P %s -K ${parms} >%s ${psfl}\n", shift, mwMin, mwMax, mmax*1.1, dm, (nm-1)*dm/5.0, mmax*0.2, app, more); setFillColor(0, magOpt, color); if (nm > 1) { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\n", color); } else { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\n", color); } fprintf(ofl, "%.2f %f\n", mwMin, 0.0); fprintf(ofl, "%.2f %f\n", mwMin, magHist[0]); for (i=0; i<nm-1; i++) { fprintf(ofl, "%.2f %f\n", mwMin + (double) (i+1)*dm, magHist[i]); fprintf(ofl, "%.2f %f\n", mwMin + (double) (i+1)*dm, 0.0); fprintf(ofl, "EOF\n"); setFillColor(i+1, magOpt, color); if (i < nm - 2 || lwritePrior) { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\n", color); } else { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\n", color); } fprintf(ofl, "%.2f %f\n", mwMin + (double) (i+1)*dm, 0.0); fprintf(ofl, "%.2f %f\n", mwMin + (double) (i+1)*dm, magHist[i+1]); } fprintf(ofl, "%.2f %f\n", mwMax, magHist[nm-1]); fprintf(ofl, "%.2f %f\n", mwMax, 0.0); fprintf(ofl, "EOF\n"); // Write the prior distribution if (lwritePrior) { fprintf(ofl, "gmt psxy -R -J -W1,black -O -K << EOF >> ${psfl}\n"); fprintf(ofl, "%f %f\n", mwMin, 1.0/(double) nm); fprintf(ofl, "%f %f\n", mwMax, 1.0/(double) nm); fprintf(ofl, "EOF\n"); } // Write the CDF /* fprintf(ofl, "gmt psbasemap -R%f/%f/0/1.05 -J -Bp0.2/a0.2:\"CDF\":E -O -K >> ${psfl}\n", mwMin, mwMax); */ fprintf(ofl, "gmt psbasemap -R%f/%f/0/1.05 -J -Bpx0.2 -Bpya0.2+l\"CDF\" -BE -O -K ${parms} >> ${psfl}\n", mwMin, mwMax); cumMag = array_cumsum64f(nm, magHist, &ierr); if (lclose) { fprintf(ofl, "gmt psxy -R -J -W1,blue -O << EOF >> ${psfl}\n"); } else { fprintf(ofl, "gmt psxy -R -J -W1,blue -O -K << EOF >> ${psfl}\n"); } for (i=0; i<nm; i++) { fprintf(ofl, "%f %f\n", Mw[i], cumMag[i]); } fprintf(ofl, "EOF\n"); if (lclose) { //fprintf(ofl, "gmt psconvert -A -Tj ${psfl}\n"); //fprintf(ofl, "rm ${psfl}\n"); } fclose(ofl); memory_free64f(&cumMag); memory_free64f(&Mw); chmod(outputScript, 0755); return 0; } //============================================================================// int postmt_gmtHelper_writeGammaBoxes(const bool lappend, const bool lclose, const char *outputScript, const char *psFile, const int ng, const int igammaOpt, const double *__restrict__ gammas, const double *__restrict__ gammaHist) { FILE *ofl; char color[32], app[8], more[8], shift[8]; double *cumGamma, *v, gmax, gammaAvg, vAvg; int i, ierr; const bool lwritePrior = true; gmax = array_max64f(ng, gammaHist, &ierr); // Compute v v = memory_calloc64f(ng); compearth_gamma2v(ng, gammas, v); // Take averages gammaAvg = -30.0; memset(app, 0, 8*sizeof(char)); memset(shift, 0, 8*sizeof(char)); memset(more, 0, 8*sizeof(char)); if (!lappend) { ofl = fopen(outputScript, "w"); fprintf(ofl, "#!/bin/bash\n"); /* fprintf(ofl, "gmt gmtset FONT_LABEL 12p\n"); fprintf(ofl, "gmt gmtset MAP_LABEL_OFFSET 0.1c\n"); */ fprintf(ofl, "parms=\"--FONT_LABEL=10p --MAP_LABEL_OFFSET=0.1c --PROJ_LENGTH_UNIT=cm\"\n"); fprintf(ofl, "psfl=%s\n", psFile); } else { ofl = fopen(outputScript, "a"); strcpy(app, "-O\0"); strcpy(more, ">\0"); strcpy(shift, "-Y4.0\0"); } fprintf(ofl, /* "gmt psbasemap -JX5i/1i %s -R-30/30/0/%.2f -Bg5a5:\"Longitude (deg)\":/a%.2f:\"Likelihood\":WSn -P %s -K >%s ${psfl}\n", */ "gmt psbasemap -JX5i/1i %s -R-30/30/0/%.2f -Bpxg5a5+l\"Longitude (deg)\" -Bpya%.2f+l\"Likelihood\" -BWSn -P %s -K ${parms} >%s ${psfl}\n", shift, gmax*1.1, gmax*0.2, app, more); setFillColor(0, igammaOpt, color); if (ng > 1) { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\n", color); } else { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\n", color); } fprintf(ofl, "%f %f\n", -30.0, 0.0); fprintf(ofl, "%f %f\n", -30.0, gammaHist[0]); for (i=0; i<ng-1; i++) { vAvg = 0.5*(v[i] + v[i+1]); compearth_v2gamma(1, &vAvg, &gammaAvg); fprintf(ofl, "%f %f\n", gammaAvg*180.0/M_PI, gammaHist[i]); fprintf(ofl, "%f %f\n", gammaAvg*180.0/M_PI, 0.0); fprintf(ofl, "EOF\n"); setFillColor(i+1, igammaOpt, color); if (i < ng - 2 || lwritePrior) { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\n", color); } else { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\n", color); } fprintf(ofl, "%f %f\n", gammaAvg*180.0/M_PI, 0.0); fprintf(ofl, "%f %f\n", gammaAvg*180.0/M_PI, gammaHist[i+1]); } fprintf(ofl, "%f %f\n", 30.0, gammaHist[ng-1]); fprintf(ofl, "%f %f\n", 30.0, 0.0); fprintf(ofl, "EOF\n"); // Write the prior distribution if (lwritePrior) { fprintf(ofl, "gmt psxy -R -J -W1,black -O -K << EOF >> ${psfl}\n"); fprintf(ofl, "%f %f\n",-30.0, 1.0/(double) ng); fprintf(ofl, "%f %f\n", 30.0, 1.0/(double) ng); fprintf(ofl, "EOF\n"); } // Write the CDF /* fprintf(ofl, "gmt psbasemap -R-30/30/0/1.05 -J -Bp0.2/a0.2:\"CDF\":E -O -K >> ${psfl}\n"); */ fprintf(ofl, "gmt psbasemap -R-30/30/0/1.05 -J -Bpx0.2 -Bpya0.2+l\"CDF\" -BE -O -K ${parms} >> ${psfl}\n"); cumGamma = array_cumsum64f(ng, gammaHist, &ierr); if (lclose) { fprintf(ofl, "gmt psxy -R -J -W1,blue -O << EOF >> ${psfl}\n"); } else { fprintf(ofl, "gmt psxy -R -J -W1,blue -O -K << EOF >> ${psfl}\n"); } for (i=0; i<ng; i++) { fprintf(ofl, "%f %f\n", gammas[i]*180.0/M_PI, cumGamma[i]); } fprintf(ofl, "EOF\n"); if (lclose) { //fprintf(ofl, "gmt psconvert -A -Tj ${psfl}\n"); //fprintf(ofl, "rm ${psfl}\n"); fprintf(ofl, "gmt psconvert -A -Tf ${psfl}\n"); fprintf(ofl, "/bin/rm ${psfl}\n"); } memory_free64f(&cumGamma); memory_free64f(&v); fclose(ofl); chmod(outputScript, 0755); return 0; } //============================================================================// int postmt_gmtHelper_writeBetaBoxes(const bool lappend, const bool lclose, const char *outputScript, const char *psFile, const int nb, const int ibetaOpt, const double *__restrict__ betas, const double *__restrict__ betaHist) { FILE *ofl; char color[32], app[8], more[8], shift[8]; double *betaCum, *u, bmax, betaAvg, uAvg; int i, ierr; const bool lwritePrior = true; bmax = array_max64f(nb, betaHist, &ierr); // Compute u u = memory_calloc64f(nb); compearth_beta2u(nb, betas, u); // Take averages betaAvg = 0.0; memset(app, 0, 8*sizeof(char)); memset(more, 0, 8*sizeof(char)); memset(shift, 0, 8*sizeof(char)); if (!lappend) { ofl = fopen(outputScript, "w"); fprintf(ofl, "#!/bin/bash\n"); /* fprintf(ofl, "gmt gmtset FONT_LABEL 12p\n"); fprintf(ofl, "gmt gmtset MAP_LABEL_OFFSET 0.1c\n"); */ fprintf(ofl, "parms=\"--FONT_LABEL=10p --MAP_LABEL_OFFSET=0.1c --PROJ_LENGTH_UNIT=cm\"\n"); fprintf(ofl, "psfl=%s\n", psFile); } else { ofl = fopen(outputScript, "a"); strcpy(app, "-O\0"); strcpy(more, ">\0"); strcpy(shift, "-Y4.0\0"); } fprintf(ofl, /* "gmt psbasemap -JX5i/1i %s -R-90/90/0/%.3f -Bg15a15:\"Latitude (deg)\":/a%.2f:\"Likelihood\":WSn -P %s -K >%s ${psfl}\n", */ "gmt psbasemap -JX5i/1i %s -R-90/90/0/%.3f -Bpxg15a15+l\"Latitude (deg)\" -Bpya%.2f+l\"Likelihood\" -BWSn -P %s -K ${parms} >%s ${psfl}\n", shift, bmax*1.1, bmax*0.2, app, more); setFillColor(0, ibetaOpt, color); if (nb > 1) { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\n", color); } else { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\n", color); } fprintf(ofl, "%f %f\n", 90.0 - 0.0, 0.0); fprintf(ofl, "%f %f\n", 90.0 - 0.0, betaHist[0]); for (i=0; i<nb-1; i++) { uAvg = 0.5*(u[i] + u[i+1]); compearth_u2beta(1, &uAvg, &betaAvg); //compearth_u2beta(1, 20, 2, &uAvg, 1.e-7, &betaAvg); fprintf(ofl, "%f %f\n", 90.0 - betaAvg*180.0/M_PI, betaHist[i]); fprintf(ofl, "%f %f\n", 90.0 - betaAvg*180.0/M_PI, 0.0); fprintf(ofl, "EOF\n"); setFillColor(i+1, ibetaOpt, color); if (i < nb - 2 || lwritePrior) { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\n", color); } else { fprintf(ofl, "gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\n", color); } fprintf(ofl, "%f %f\n", 90.0 - betaAvg*180.0/M_PI, 0.0); fprintf(ofl, "%f %f\n", 90.0 - betaAvg*180.0/M_PI, betaHist[i+1]); } fprintf(ofl, "%f %f\n", 90.0 - M_PI*180.0/M_PI, betaHist[nb-1]); fprintf(ofl, "%f %f\n", 90.0 - M_PI*180.0/M_PI, 0.0); fprintf(ofl, "EOF\n"); // Write the prior distribution if (lwritePrior) { fprintf(ofl, "gmt psxy -R -J -W1,black -O -K << EOF >> ${psfl}\n"); fprintf(ofl, "%f %f\n",-90.0, 1.0/(double) nb); fprintf(ofl, "%f %f\n", 90.0, 1.0/(double) nb); fprintf(ofl, "EOF\n"); } // Write the CDF /* fprintf(ofl, "gmt psbasemap -R-90/90/0/1.05 -J -Bp0.2/a0.2:\"CDF\":E -O -K >> ${psfl}\n"); */ fprintf(ofl, "gmt psbasemap -R-90/90/0/1.05 -J -Bpx0.2 -Bpya0.2+l\"CDF\" -BE -O -K ${parms} >> ${psfl}\n"); betaCum = array_cumsum64f(nb, betaHist, &ierr); if (lclose) { fprintf(ofl, "gmt psxy -R -J -W1,blue -O << EOF >> ${psfl}\n"); } else { fprintf(ofl, "gmt psxy -R -J -W1,blue -O -K << EOF >> ${psfl}\n"); } for (i=0; i<nb; i++) { // the cdf is written backwards because i flip the axis to make it // increase left to right; this is opposite of what colatitude wants // to do fprintf(ofl, "%f %f\n", 90.0 - betas[i]*180.0/M_PI, betaCum[nb-1-i]); } fprintf(ofl, "EOF\n"); if (lclose) { //fprintf(ofl, "gmt psconvert -A -Tj ${psfl}\n"); //fprintf(ofl, "rm ${psfl}\n"); fprintf(ofl, "gmt psconvert -A -Tf ${psfl}\n"); fprintf(ofl, "/bin/rm ${psfl}\n"); } memory_free64f(&u); memory_free64f(&betaCum); fclose(ofl); chmod(outputScript, 0755); return 0; } //============================================================================// int postmt_gmtHelper_makeRegularHistograms( const int nlocs, const int nm, const int nb, const int ng, const int nk, const int ns, const int nt, const int nmt, const double *__restrict__ phi, double **__restrict__ locHist, double **__restrict__ magHist, double **__restrict__ betaHist, double **__restrict__ gammaHist, double **__restrict__ kappaHist, double **__restrict__ sigmaHist, double **__restrict__ thetaHist) { double *betaH, *gammaH, *kappaH, *locH, *magH, *sigmaH, *thetaH, xsum; int ib, ierr, ig, ik, il, im, imt, is, it; locH = memory_calloc64f(nlocs); magH = memory_calloc64f(nm); betaH = memory_calloc64f(nb); gammaH = memory_calloc64f(ng); kappaH = memory_calloc64f(nk); sigmaH = memory_calloc64f(ns); thetaH = memory_calloc64f(nt); for (il=0; il<nlocs; il++) { for (im=0; im<nm; im++) { for (ib=0; ib<nb; ib++) { for (ig=0; ig<ng; ig++) { for (ik=0; ik<nk; ik++) { for (is=0; is<ns; is++) { for (it=0; it<nt; it++) { imt = il*nm*nb*ng*nk*ns*nt + im*nb*ng*nk*ns*nt + ib*ng*nk*ns*nt + ig*nk*ns*nt + ik*ns*nt + is*nt + it; locH[il] = locH[il] + phi[imt]; magH[im] = magH[im] + phi[imt]; betaH[ib] = betaH[ib] + phi[imt]; gammaH[ig] = gammaH[ig] + phi[imt]; kappaH[ik] = kappaH[ik] + phi[imt]; sigmaH[is] = sigmaH[is] + phi[imt]; thetaH[it] = thetaH[it] + phi[imt]; } } } } } } } xsum = array_sum64f(nmt, phi, &ierr); cblas_dscal(nlocs, 1.0/xsum, locH, 1); cblas_dscal(nm, 1.0/xsum, magH, 1); cblas_dscal(nb, 1.0/xsum, betaH, 1); cblas_dscal(ng, 1.0/xsum, gammaH, 1); cblas_dscal(nk, 1.0/xsum, kappaH, 1); cblas_dscal(ns, 1.0/xsum, sigmaH, 1); cblas_dscal(nt, 1.0/xsum, thetaH, 1); *locHist = locH; *magHist = magH; *betaHist = betaH; *gammaHist = gammaH; *kappaHist = kappaH; *sigmaHist = sigmaH; *thetaHist = thetaH; return 0; } //============================================================================// static void getBaseAndExp(const double val, double *base, int *exp) { char cval[64], cexp[64], temp[64]; int i, k, l; bool lp1; memset(cval, 0, 64*sizeof(char)); memset(cexp, 0, 64*sizeof(char)); memset(temp, 0, 64*sizeof(char)); sprintf(temp, "%04.2e", val); lp1 = true; k = 0; l = 0; for (i=0; i<strlen(temp); i++) { if (temp[i] == 'e') { lp1 = false; continue; } else { if (lp1) { cval[k] = temp[i]; k = k + 1; } else { cexp[l] = temp[i]; l = l + 1; } } } *exp = atoi(cexp); *base = atof(cval); return; } static void getBaseAndExpMT(const double *mtIn, double *mtOut, int *expOut) { double xfact; int expWork, i; getBaseAndExp(mtIn[0], &mtOut[0], expOut); for (i=1; i<6; i++) { getBaseAndExp(mtIn[i], &mtOut[i], &expWork); if (expWork > *expOut){*expOut = expWork;} } // Rescale for (i=0; i<6; i++) { getBaseAndExp(mtIn[i], &mtOut[i], &expWork); xfact = pow(10.0, expWork - *expOut); mtOut[i] = mtOut[i]*xfact; } return; } int postmt_gmtHelper_makePsmecaLine(const enum compearthCoordSystem_enum basis, const double *mt, const double evla, const double evlo, const double evdp, const char *evid, char line[128]) { const char *fcnm = "postmt_gmtHelper_makePsmecaLine\0"; double mtUSE[6], mtGMT[6]; int exp, ierr; memset(line, 0, 128*sizeof(char)); ierr = compearth_convertMT(1, basis, CE_USE, mt, mtUSE); if (ierr != 0) { printf("%s: Error switching basis\n", fcnm); return -1; } getBaseAndExpMT(mtUSE, mtGMT, &exp); sprintf(line, "%f %f %f %f %f %f %f %f %f %d %s\n", evlo, evla, evdp, mtGMT[0], mtGMT[1], mtGMT[2], mtGMT[3], mtGMT[4], mtGMT[5], exp, evid); return 0; } static void setFillColor(const int i, const int iopt, char color[32]) { memset(color, 0, 32*sizeof(char)); if (i == iopt) { strcpy(color, "-Gyellow\0"); } else { strcpy(color, "-Gred\0"); } return; } //============================================================================// /* sprintf("%7.2f %5.2f %f \n"< evlo, evla, evdp, mrr, mtt, mpp, Columns: lon lat depth mrr mtt mpp mrt mrp mtp iexp name -176.96 -29.25 48 7.68 0.09 -7.77 1.39 4.52 -3.26 26 X Y 010176A */
{ "alphanum_fraction": 0.4724439108, "avg_line_length": 35.0181368508, "ext": "c", "hexsha": "3e399673441403d6030ec5a9474807aa08a5f5f4", "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": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_forks_repo_licenses": [ "Intel" ], "max_forks_repo_name": "bakerb845/parmt", "max_forks_repo_path": "postprocess/gmtHelper.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Intel" ], "max_issues_repo_name": "bakerb845/parmt", "max_issues_repo_path": "postprocess/gmtHelper.c", "max_line_length": 154, "max_stars_count": null, "max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_stars_repo_licenses": [ "Intel" ], "max_stars_repo_name": "bakerb845/parmt", "max_stars_repo_path": "postprocess/gmtHelper.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 14322, "size": 42477 }
/* Version 1.0 Correlation service; initial version will accept text input (optionally gzipped) where comments and any integer (ie containing no ".") in initial columns are skipped: [# comments] [int int int ] fl.oat fl.oat ... ([] means optional.) Each row is a node, each column a TR, separated by whitespace. This is the .1D surface fmri data format created by NIH AFNI/SUMA's 3dVol2Surf, which interpolates voxel rows data onto each node (vertex) in a MGH FreeSurfer surface. But the rows could be any rows data; no spatial information is used (nor is it supplied by any recognized input arguments). Normalizes each row by default. Saves correlationss as platform single-precision floats with .1D.gz output an option. Uses Cblas API so link with the Cblas implementation library of choice for your platform (Atlas, Gotoblas, MKL, vecLib, cuBLAS, OpenCL, etc). Tested with GotoBlas2 on 64-bit Linux and vecLib on 64-bit Mac OS X Most CBLAS implementations are multicore, so the parallelism (within-machine) should come from that. Ben Singer <bdsinger@princeton.edu> April 2013, revised October 2014 */ #define _GNU_SOURCE #include <libgen.h> #include <assert.h> #include <string.h> #include <limits.h> #include <stdlib.h> #ifdef __APPLE__ #include <malloc/malloc.h> #include <Accelerate/Accelerate.h> #else #include <cblas.h> #endif #include "pnicorr.h" // ******* Memory limits #define BYTES_PER_GB (1000000000LL) #define BYTES_PER_MB (1000000LL) #define MAX_FILENAME 256 #define CBLAS_ALPHA (1.0F) #define CBLAS_BETA (0.0F) #define PNICORR_ALIGNMENT 64 enum { PNICORR_CORRELATIONS_TAG = 1, PNICORR_NUMTAGS }; #define PNICORR_PROC_BODY_PARAMS \ (const float *restrict full_matrix, float *restrict submatrix, \ float *restrict correlations, const int *restrict offset_for_task, \ const int *restrict rows_for_task, const int nt, const int num_rows, \ const int num_columns, const char *restrict outfile, \ const pnicorr_iotype_t outtype, const int my_task_id) #define PNICORR_PROC_BODY_ARGS \ (full_matrix, submatrix, correlations, offset_for_task, rows_for_task, nt, \ num_rows, num_columns, outfile, outtype, my_task_id) #define PNICORR_PARAMSET_PARAMS \ (const int my_task_id, const int *num_rows, const int *num_columns, \ long long *ntasks, int *num_workers, float **restrict full_matrix) #define PNICORR_PARAMSET_ARGS \ (my_task_id, &num_rows, &num_columns, &ntasks, &num_workers, &full_matrix) #define PNICORR_TASK_PROCESSING_PARAMS \ (const float *restrict full_matrix, float *restrict submatrix, \ float *restrict correlations, const int offset_for_task, \ const int rows_for_task, const int num_rows, const int num_columns) #define PNICORR_TASK_PROCESSING_ARGS(id) \ (full_matrix, submatrix, correlations, offset_for_task[id], \ rows_for_task[id], num_rows, num_columns) #define COR_TASK_PROCESSING(id) \ pnicorr_task_processing PNICORR_TASK_PROCESSING_ARGS(id) #ifdef HAVE_MPI /* use MPI */ #include <mpi.h> void pnicorr_mpi_init(int *restrict my_task_id, int *restrict num_workers); void pnicorr_mpi_finalize(void); void pnicorr_mpi_paramset PNICORR_PARAMSET_PARAMS; void pnicorr_mpi_proc_body PNICORR_PROC_BODY_PARAMS; #define COR_MPI_INIT(my_task_id, num_workers) \ pnicorr_mpi_init(&my_task_id, &num_workers) #define COR_MPI_FINALIZE pnicorr_mpi_finalize() #define COR_MPI_PARAMSET pnicorr_mpi_paramset PNICORR_PARAMSET_ARGS #define COR_TASK_PROC_BODY pnicorr_mpi_proc_body PNICORR_PROC_BODY_ARGS #else /* no MPI */ #define NOP (void)0 #define COR_MPI_INIT(my_task_id, num_workers) NOP #define COR_MPI_FINALIZE NOP #define COR_MPI_PARAMSET NOP #define COR_TASK_PROC_BODY pnicorr_proc_body PNICORR_PROC_BODY_ARGS #endif // ******* Helper functions // ****************** normalize_fvec *************** static void normalize_fvec(float *restrict full_matrix, const int num_rows, const int N) { const int incX = 1; float *dptr = full_matrix; for (int i = 0; i < num_rows; ++i) { float norm2 = cblas_snrm2(N, dptr, incX); const float alpha = 1.0 / norm2; cblas_sscal(N, alpha, dptr, incX); dptr += N; } } void pnicorr_task_processing PNICORR_TASK_PROCESSING_PARAMS; void pnicorr_proc_body PNICORR_PROC_BODY_PARAMS; void pnicorr_savematrix_for_task(const int i, const int *restrict rows_for_task, const int num_rows, const char *outfile, const pnicorr_iotype_t outtype, const float *restrict correlations); // ****************** MAIN *************** int main(const int argc, const char *argv[]) { float *full_matrix = NULL; float *correlations = NULL; char outfile[MAX_FILENAME]; int num_rows = 0, num_columns = 0; int my_task_id = 0; long long ntasks = 1; int num_workers = 1; pnicorr_iotype_t outtype = pnicorr_iotype_numiotypes; COR_MPI_INIT(my_task_id, num_workers); struct opts2struct_t *ops2s = opts2struct_create(); if (0 == my_task_id) { // ***** parse input args ****** const char *ext; const char *comp; const int pre_args = 2; char *basec = strdup(argv[0]); char *bname = basename(basec); if (argc < pre_args) { fprintf(stderr, "\nusage: %s file.1D.dset[.gz] -[no]norm -mem=MB " "-iotype=1D|1Dgz|mat\n", bname); exit(EXIT_FAILURE); } const char *filename = argv[1]; opts2struct_parseopts(ops2s, argc, argv); int normalize = ops2s->i[norm]; long long maxmem = ops2s->i[mem]; if (!strncmp(ops2s->iotype, "1D", 2)) { outtype = pnicorr_iotype_1D; ext = "1D.dset"; comp = ""; } else if (!strncmp(ops2s->iotype, "1Dgz", 4)) { outtype = pnicorr_iotype_1Dgz; ext = "1D.dset"; comp = ".gz"; } else if (!strncmp(ops2s->iotype, "mat", 3)) { outtype = pnicorr_iotype_mat; ext = "mat"; comp = ""; } else { ext = ""; comp = ""; ERRIF(1, "unrecognized iotype %s", ops2s->iotype); } // ********** get full_matrix from file ************ full_matrix = pnicorr_load_1D(filename, &num_rows, &num_columns); // get outfile name pnicorr_genoutfile(bname, num_rows, ext, comp, outfile); free(basec); // ********** Normalize -- unless asked not to via "-nonorm" ************ if (normalize) { LOG("normalizing each row/rows independently ...\n"); TIC; normalize_fvec(full_matrix, num_rows, num_columns); TOC("normalize"); } // ************ do the matrix multiplication *************** // (results in correlation after normalization) long long corbytes = (long long)num_rows * (long long)num_rows * (long long)sizeof(float); // must split up the task s.t. each task uses MAX_MEM_PER_TASK bytes ntasks = (long long)((float)corbytes / (float)((long long)maxmem * BYTES_PER_MB) + 0.5); LOG("%lld task(s), since %d^2 floats is %.3f MB and the max MB per " "task is %lld MB\n", ntasks, num_rows, (float)corbytes / (float)BYTES_PER_MB, maxmem); if (ntasks <= 1) { // get time info immediately setbuf(stdout, NULL); // ********* all in one go; enough memory to do so ********* LOG("number of bytes needed for correlations is small enough for a " "single " "task\n"); LOG("allocating memory...\n"); int err = posix_memalign((void *)&correlations, PNICORR_ALIGNMENT, corbytes); ERRIF(err, "posix_memalign"); LOG("calling cblas_ssyrk to perform AA' ...\n"); TIC; cblas_ssyrk(CblasRowMajor, CblasUpper, CblasNoTrans, num_rows, num_columns, CBLAS_ALPHA, full_matrix, num_columns, CBLAS_BETA, correlations, num_rows); TOC("calculation"); // *** save *** LOG("saving %d x %d task correlations to %s\n", num_rows, num_rows, outfile); TIC; pnicorr_savematrix(correlations, num_rows, num_rows, "w", outtype, outfile); TOC("saving"); LOG("done\n"); } // ntasks > 1 } // my_task_id == 0 COR_MPI_PARAMSET; if (ntasks > 1) { float *submatrix = NULL; // **************** need to do it in blocks and append correlations // ********* int nt = (int)ntasks; int num_rows_per_task = num_rows / nt; if (num_rows_per_task < 1) { num_rows_per_task = 1; nt = num_rows; } int *rows_for_task = calloc(num_workers, sizeof(int)); int *offset_for_task = calloc(num_workers, sizeof(int)); // have task 0 (master in case of MPI) do the work for leftover rows // when total doesn't evenly divide ntasks rows_for_task[0] = num_rows - (num_rows_per_task * (nt - 1)); offset_for_task[0] = 0; int maxrows_for_tasks = (rows_for_task[0] > num_rows_per_task) ? rows_for_task[0] : num_rows_per_task; for (int i = 1; i < nt; ++i) { offset_for_task[i] = offset_for_task[i - 1] + rows_for_task[i - 1]; rows_for_task[i] = num_rows_per_task; } int err = posix_memalign((void *)&submatrix, PNICORR_ALIGNMENT, maxrows_for_tasks * num_columns * sizeof(float)); ERRIF(err, "posix_memalign submatrix"); err = posix_memalign((void *)&correlations, PNICORR_ALIGNMENT, maxrows_for_tasks * num_rows * sizeof(float)); ERRIF(err, "posix_memalign correlations"); COR_TASK_PROC_BODY; free(rows_for_task); free(offset_for_task); if (submatrix) { free(submatrix); submatrix = NULL; } } if (full_matrix) { free(full_matrix); full_matrix = NULL; } if (correlations) { free(correlations); correlations = NULL; } COR_MPI_FINALIZE; return EXIT_SUCCESS; } void pnicorr_task_processing PNICORR_TASK_PROCESSING_PARAMS { LOG("submatrix %p full_matrix %p\n", submatrix, full_matrix); memcpy(submatrix, full_matrix + offset_for_task, rows_for_task * num_columns * sizeof(float)); memset(correlations, 0, num_rows * rows_for_task * sizeof(float)); TIC; LOG("calling cblas_sgemm using %d num_rows (rows) at a time\n", rows_for_task); cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, rows_for_task, num_rows, num_columns, CBLAS_ALPHA, submatrix, num_columns, full_matrix, num_columns, CBLAS_BETA, correlations, num_rows); TOC("calculating"); } void pnicorr_savematrix_for_task(const int i, const int *restrict rows_for_task, const int num_rows, const char *outfile, const pnicorr_iotype_t outtype, const float *restrict correlations) { // ******** save/append ********* LOG("task %d: %s %d x %d task correlations to %s\n", i, (i == 0) ? "writing" : "appending", rows_for_task[i], num_rows, outfile); TIC; pnicorr_savematrix(correlations, rows_for_task[i], num_rows, (i == 0) ? "w" : "a", outtype, outfile); TOC("saving"); } #ifdef HAVE_MPI void pnicorr_mpi_init(int *my_task_id, int *num_workers) { int initialized; MPI_Initialized(&initialized); if (0 == initialized) { MPI_Init(NULL, NULL); } MPI_Comm_rank(MPI_COMM_WORLD, my_task_id); MPI_Comm_size(MPI_COMM_WORLD, num_workers); } void pnicorr_mpi_finalize(void) { int initialized; MPI_Initialized(&initialized); if (initialized) { int finalized; MPI_Finalized(&finalized); if (0 == finalized) { MPI_Finalize(); } } } void pnicorr_mpi_paramset PNICORR_PARAMSET_PARAMS { MPI_Bcast((void *)num_rows, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast((void *)num_columns, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast((void *)ntasks, 1, MPI_LONG_LONG, 0, MPI_COMM_WORLD); MPI_Bcast((void *)num_workers, 1, MPI_INT, 0, MPI_COMM_WORLD); long long fullmatrixbytes = *num_rows * *num_columns * sizeof(float); if (my_task_id > 0) { int err = posix_memalign((void *)full_matrix, PNICORR_ALIGNMENT, fullmatrixbytes); ERRIF(err, "posix_memalign"); } else { ALOGIF(*num_workers != *ntasks, "setting ntasks equal to num_workers: (%d " "workers, %d tasks -> %d tasks)\n", *num_workers, (int)*ntasks, *num_workers); } *ntasks = *num_workers; MPI_Bcast((void *)(*full_matrix), *num_rows * *num_columns, MPI_FLOAT, 0, MPI_COMM_WORLD); MPI_Barrier(MPI_COMM_WORLD); } void pnicorr_mpi_proc_body PNICORR_PROC_BODY_PARAMS { COR_TASK_PROCESSING(my_task_id); if (0 == my_task_id) { pnicorr_savematrix_for_task(0, rows_for_task, num_rows, outfile, outtype, correlations); for (int i = 1; i < nt; ++i) { MPI_Recv(correlations, num_rows * rows_for_task[i], MPI_FLOAT, i, PNICORR_CORRELATIONS_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE); pnicorr_savematrix_for_task(i, rows_for_task, num_rows, outfile, outtype, correlations); } } else { LOG("[%d] sending %d x %d correlations\n", my_task_id, rows_for_task[my_task_id], num_rows); MPI_Send(correlations, num_rows * rows_for_task[my_task_id], MPI_FLOAT, 0, PNICORR_CORRELATIONS_TAG, MPI_COMM_WORLD); } } #else void pnicorr_proc_body PNICORR_PROC_BODY_PARAMS { int num_rows_processed = 0; for (int i = 0; i < nt; ++i) { COR_TASK_PROCESSING(i); pnicorr_savematrix_for_task(i, rows_for_task, num_rows, outfile, outtype, correlations); num_rows_processed += rows_for_task[i]; ALOG("%d%% complete\n", (int)((float)num_rows_processed / (float)num_rows * 100.0f)); } } #endif
{ "alphanum_fraction": 0.6322594172, "avg_line_length": 33.8274231678, "ext": "c", "hexsha": "0e727a7e9b6b757385c177da9c74da2c3ed3116d", "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": "6865d0eacd24758a22383bda6f2ba71cad48332f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "bdsinger/pnicorr", "max_forks_repo_path": "pnicorr.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "6865d0eacd24758a22383bda6f2ba71cad48332f", "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": "bdsinger/pnicorr", "max_issues_repo_path": "pnicorr.c", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "6865d0eacd24758a22383bda6f2ba71cad48332f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "bdsinger/pnicorr", "max_stars_repo_path": "pnicorr.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3786, "size": 14309 }
#ifndef EMPHASIS_RINIT_H_INCLUDED #define EMPHASIS_RINIT_H_INCLUDED #include <nlopt.h> #if (defined(_WIN32) || defined(__WIN32__)) && !defined(__LCC__) # define REMP_EXPORT extern "C" __declspec(dllexport) #else # define REMP_EXPORT extern "C" #endif #ifdef __cplusplus extern "C" { #endif /* some function pointers into nlopt to be filled in by R */ REMP_EXPORT nlopt_opt(*remp_create)(nlopt_algorithm, unsigned); REMP_EXPORT void(*remp_destroy)(nlopt_opt); REMP_EXPORT nlopt_result(*remp_optimize)(nlopt_opt, double *, double *); REMP_EXPORT nlopt_result(*remp_set_min_objective)(nlopt_opt, nlopt_func, void *); REMP_EXPORT nlopt_result(*remp_set_max_objective)(nlopt_opt, nlopt_func, void *); REMP_EXPORT nlopt_result(*remp_set_lower_bounds)(nlopt_opt, const double *); REMP_EXPORT nlopt_result(*remp_set_lower_bounds1)(nlopt_opt, double); REMP_EXPORT nlopt_result(*remp_set_upper_bounds)(nlopt_opt, const double *); REMP_EXPORT nlopt_result(*remp_set_upper_bounds1)(nlopt_opt, double); REMP_EXPORT nlopt_result(*remp_set_xtol_rel)(nlopt_opt, double); REMP_EXPORT nlopt_result(*remp_set_xtol_abs)(nlopt_opt, double); #ifdef __cplusplus } #endif #endif
{ "alphanum_fraction": 0.7991452991, "avg_line_length": 28.5365853659, "ext": "h", "hexsha": "3dcf096a1b11a5a2df2e03e9d758823271fb54be", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-03-12T13:25:10.000Z", "max_forks_repo_forks_event_min_datetime": "2020-03-12T13:25:10.000Z", "max_forks_repo_head_hexsha": "c23a17ee903ca98c34126739561d97b32f631098", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "franciscorichter/emphasis", "max_forks_repo_path": "src/rinit.h", "max_issues_count": 6, "max_issues_repo_head_hexsha": "c23a17ee903ca98c34126739561d97b32f631098", "max_issues_repo_issues_event_max_datetime": "2020-05-24T16:53:03.000Z", "max_issues_repo_issues_event_min_datetime": "2018-07-16T13:55:17.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "franciscorichter/emphasis", "max_issues_repo_path": "src/rinit.h", "max_line_length": 81, "max_stars_count": null, "max_stars_repo_head_hexsha": "c23a17ee903ca98c34126739561d97b32f631098", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "franciscorichter/emphasis", "max_stars_repo_path": "src/rinit.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 349, "size": 1170 }
#ifndef DISTANCE_H_MUJPGVJL #define DISTANCE_H_MUJPGVJL #include <algorithm> #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics/mean.hpp> #include <boost/accumulators/statistics/median.hpp> #include <boost/accumulators/statistics/skewness.hpp> #include <boost/accumulators/statistics/stats.hpp> #include <boost/accumulators/statistics/variance.hpp> #include <boost/histogram.hpp> #include <cstddef> #include <gsl/gsl> #include <opencv2/core/persistence.hpp> namespace sens_loc { /// This namespace contains useful function for statistical analysis of /// keypoints, descriptors and other relevant quantities. namespace analysis { /// Wrapper-struct to hold the common set of statistical values. struct statistic { using accumulator_t = boost::accumulators::accumulator_set< float, boost::accumulators::stats<boost::accumulators::tag::count, boost::accumulators::tag::min, boost::accumulators::tag::max, boost::accumulators::tag::median, boost::accumulators::tag::mean, boost::accumulators::tag::variance( boost::accumulators::lazy), boost::accumulators::tag::skewness>>; std::size_t count = 0UL; float min = 0.0F; float max = 0.0F; float mean = 0.0F; float variance = 0.0F; float stddev = 0.0F; float skewness = 0.0F; float median = 0.0F; std::vector<float> decentils{0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F}; /// Extract the statistical values from the original data. /// \pre the data must be sorted! static statistic make(gsl::span<const float> data) { using namespace std; Expects(is_sorted(begin(data), end(data))); statistic s; if (data.empty()) return s; if (data.size() >= 10L) { const int number_quantils = 10; std::ptrdiff_t delta = data.size() / number_quantils; Expects(s.decentils.size() == 9UL); for (int i = 1; i < number_quantils; ++i) { s.decentils[i - 1] = data[i * delta]; } Ensures(s.decentils.size() == 9UL); } s.median = data[data.size() / 2]; accumulator_t accu; std::for_each(std::begin(data), std::end(data), [&accu](float e) { accu(e); }); using namespace boost::accumulators; s.count = boost::accumulators::count(accu); s.min = boost::accumulators::min(accu); s.max = boost::accumulators::max(accu); s.mean = boost::accumulators::mean(accu); s.variance = boost::accumulators::variance(accu); s.stddev = std::sqrt(s.variance); s.skewness = boost::accumulators::skewness(accu); return s; } void reset() noexcept { count = 0UL; min = 0.0F; max = 0.0F; mean = 0.0F; variance = 0.0F; stddev = 0.0F; skewness = 0.0F; median = 0.0F; decentils = {0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F}; } }; /// Write-Functionality for OpenCVs-Filestorage API. void write(cv::FileStorage& fs, const std::string& name, const statistic& stat); /// This class processes 'float' datapoints and calculates both histograms /// and basic statistical quantities, like the 'min', 'max', 'mean' and /// others. /// Its main use-case is to analyze distance information gathered while /// processing image and matching data. It can be used for any scalar /// quantity though. class distance { public: using axis_t = boost::histogram::axis::regular< // 'float' values are tracked with the histogram. float, // do no transformation before insertion boost::histogram::axis::transform::id, // a string is the metadata for the axis (=title) std::string, // no overflow/underflow by construction. boost::histogram::axis::option::none_t>; using histo_t = decltype(boost::histogram::make_histogram(axis_t{})); distance() = default; explicit distance(gsl::span<const float> distances, unsigned int bin_count = 50U, std::string title = "distance") noexcept : _bin_count{bin_count} , _axis_title{std::move(title)} { analyze(distances); } /// Analyses the provided distances. This will overwrite a previous /// analysis and dataset! Use this method to provide the data if the /// class was default constructed. /// \pre is_sorted(distances) void analyze(gsl::span<const float> distances, bool histo = true) noexcept; /// Return the reference to the potentially created histogram in \c analyze. /// If the histogram is not created, it will just be default constructed. /// \sa analyze [[nodiscard]] const histo_t& histogram() const noexcept { return _histo; } [[nodiscard]] std::size_t count() const noexcept { return _s.count; } [[nodiscard]] float min() const noexcept { return _s.min; } [[nodiscard]] float max() const noexcept { return _s.max; } [[nodiscard]] float median() const noexcept { return _s.median; } [[nodiscard]] float mean() const noexcept { return _s.mean; } [[nodiscard]] float variance() const noexcept { return _s.variance; } [[nodiscard]] float stddev() const noexcept { return _s.stddev; } [[nodiscard]] float skewness() const noexcept { return _s.skewness; } /// Read-Only access to underlying statistical data. [[nodiscard]] const statistic& get_statistic() const noexcept { return _s; } private: unsigned int _bin_count = 50UL; std::string _axis_title = "distance"; histo_t _histo; statistic _s; }; } // namespace analysis } // namespace sens_loc #endif /* end of include guard: DISTANCE_H_MUJPGVJL */
{ "alphanum_fraction": 0.5885433196, "avg_line_length": 39.1428571429, "ext": "h", "hexsha": "2f217464baa24db1de46bb7569ef34ee69d36ebe", "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/analysis/distance.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/analysis/distance.h", "max_line_length": 80, "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/analysis/distance.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": 1566, "size": 6302 }
#include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #include <sys/time.h> #include <sys/resource.h> #include <unistd.h> #include <signal.h> #include <gsl/gsl_rng.h> #include "allvars.h" #include "proto.h" #ifdef DEBUG #include <fenv.h> void enable_core_dumps_and_fpu_exceptions(void) { struct rlimit rlim; extern int feenableexcept(int __excepts); /* enable floating point exceptions */ /* feenableexcept(FE_DIVBYZERO | FE_INVALID); */ /* Note: FPU exceptions appear not to work properly * when the Intel C-Compiler for Linux is used */ /* set core-dump size to infinity */ getrlimit(RLIMIT_CORE, &rlim); rlim.rlim_cur = RLIM_INFINITY; setrlimit(RLIMIT_CORE, &rlim); /* MPICH catches the signales SIGSEGV, SIGBUS, and SIGFPE.... * The following statements reset things to the default handlers, * which will generate a core file. */ /* signal(SIGSEGV, catch_fatal); signal(SIGBUS, catch_fatal); signal(SIGFPE, catch_fatal); signal(SIGINT, catch_fatal); */ signal(SIGSEGV, SIG_DFL); signal(SIGBUS, SIG_DFL); signal(SIGFPE, SIG_DFL); signal(SIGINT, SIG_DFL); /* Establish a handler for SIGABRT signals. */ signal(SIGABRT, catch_abort); } void catch_abort(int sig) { MPI_Finalize(); exit(0); } void catch_fatal(int sig) { terminate_processes(); MPI_Finalize(); signal(sig, SIG_DFL); raise(sig); } void terminate_processes(void) { pid_t my_pid; char buf[500], hostname[500], *cp; char commandbuf[500]; FILE *fd; int i, pid; sprintf(buf, "%s%s", All.OutputDir, "PIDs.txt"); my_pid = getpid(); if((fd = fopen(buf, "r"))) { for(i = 0; i < NTask; i++) { int ret; ret = fscanf(fd, "%s %d", hostname, &pid); cp = hostname; while(*cp) { if(*cp == '.') *cp = 0; else cp++; } if(my_pid != pid) { sprintf(commandbuf, "ssh %s kill -ABRT %d", hostname, pid); printf("--> %s\n", commandbuf); fflush(stdout); #ifndef NOCALLSOFSYSTEM ret = system(commandbuf); #endif } } fclose(fd); } } void write_pid_file(void) { pid_t my_pid; char mode[8], buf[500]; FILE *fd; int i; my_pid = getpid(); sprintf(buf, "%s%s", All.OutputDir, "PIDs.txt"); if(RestartFlag == 0) strcpy(mode, "w"); else strcpy(mode, "a"); for(i = 0; i < NTask; i++) { if(ThisTask == i) { if(ThisTask == 0) sprintf(mode, "w"); else sprintf(mode, "a"); if((fd = fopen(buf, mode))) { fprintf(fd, "%s %d\n", getenv("HOST"), (int) my_pid); fclose(fd); } } MPI_Barrier(MPI_COMM_WORLD); } } #endif double get_random_number(unsigned int id) { return RndTable[(id % RNDTABLE)]; } void set_random_numbers(void) { int i; for(i = 0; i < RNDTABLE; i++) RndTable[i] = gsl_rng_uniform(random_generator); } /* returns the number of cpu-ticks in seconds that * have elapsed. (or the wall-clock time) */ double second(void) { #ifdef WALLCLOCK return MPI_Wtime(); #else return ((double) clock()) / CLOCKS_PER_SEC; #endif /* note: on AIX and presumably many other 32bit systems, * clock() has only a resolution of 10ms=0.01sec */ } double measure_time(void) /* strategy: call this at end of functions to account for time in this function, and before another (nontrivial) function is called */ { double t, dt; t = second(); dt = t - WallclockTime; WallclockTime = t; return dt; } /* returns the time difference between two measurements * obtained with second(). The routine takes care of the * possible overflow of the tick counter on 32bit systems. */ double timediff(double t0, double t1) { double dt; dt = t1 - t0; if(dt < 0) /* overflow has occured (for systems with 32bit tick counter) */ { #ifdef WALLCLOCK dt = 0; #else dt = t1 + pow(2, 32) / CLOCKS_PER_SEC - t0; #endif } return dt; } #ifdef X86FIX #define _FPU_SETCW(x) asm volatile ("fldcw %0": :"m" (x)); #define _FPU_GETCW(x) asm volatile ("fnstcw %0":"=m" (x)); #define _FPU_EXTENDED 0x0300 #define _FPU_DOUBLE 0x0200 void x86_fix(void) { unsigned short dummy, new_cw; unsigned short *old_cw; old_cw = &dummy; _FPU_GETCW(*old_cw); new_cw = (*old_cw & ~_FPU_EXTENDED) | _FPU_DOUBLE; _FPU_SETCW(new_cw); } #endif void sumup_large_ints(int n, int *src, long long *res) { int i, j, *numlist; numlist = (int *) mymalloc(NTask * n * sizeof(int)); MPI_Allgather(src, n, MPI_INT, numlist, n, MPI_INT, MPI_COMM_WORLD); for(j = 0; j < n; j++) res[j] = 0; for(i = 0; i < NTask; i++) for(j = 0; j < n; j++) res[j] += numlist[i * n + j]; myfree(numlist); } void sumup_longs(int n, long long *src, long long *res) { int i, j; long long *numlist; numlist = (long long *) mymalloc(NTask * n * sizeof(long long)); MPI_Allgather(src, n * sizeof(long long), MPI_BYTE, numlist, n * sizeof(long long), MPI_BYTE, MPI_COMM_WORLD); for(j = 0; j < n; j++) res[j] = 0; for(i = 0; i < NTask; i++) for(j = 0; j < n; j++) res[j] += numlist[i * n + j]; myfree(numlist); } size_t sizemax(size_t a, size_t b) { if(a < b) return b; else return a; } void report_VmRSS(void) { pid_t my_pid; FILE *fd; char buf[1024]; my_pid = getpid(); sprintf(buf, "/proc/%d/status", my_pid); if((fd = fopen(buf, "r"))) { while(1) { if(fgets(buf, 500, fd) != buf) break; if(strncmp(buf, "VmRSS", 5) == 0) { printf("ThisTask=%d: %s", ThisTask, buf); } if(strncmp(buf, "VmSize", 6) == 0) { printf("ThisTask=%d: %s", ThisTask, buf); } } fclose(fd); } }
{ "alphanum_fraction": 0.606634248, "avg_line_length": 17.826625387, "ext": "c", "hexsha": "ddd7966596c2c1c40fa3dfbdb74531ac7ffc42f0", "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": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "egpbos/egp", "max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/system.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "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": "egpbos/egp", "max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/system.c", "max_line_length": 160, "max_stars_count": null, "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "egpbos/egp", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/system.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1795, "size": 5758 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <time.h> #include <math.h> #include <float.h> #include "bingham/util.h" //#include <lapacke.h> //#undef I // fuck C99! const color_t colormap[256] = {{0, 0, 131}, {0, 0, 135}, {0, 0, 139}, {0, 0, 143}, {0, 0, 147}, {0, 0, 151}, {0, 0, 155}, {0, 0, 159}, {0, 0, 163}, {0, 0, 167}, {0, 0, 171}, {0, 0, 175}, {0, 0, 179}, {0, 0, 183}, {0, 0, 187}, {0, 0, 191}, {0, 0, 195}, {0, 0, 199}, {0, 0, 203}, {0, 0, 207}, {0, 0, 211}, {0, 0, 215}, {0, 0, 219}, {0, 0, 223}, {0, 0, 227}, {0, 0, 231}, {0, 0, 235}, {0, 0, 239}, {0, 0, 243}, {0, 0, 247}, {0, 0, 251}, {0, 0, 255}, {0, 4, 255}, {0, 8, 255}, {0, 12, 255}, {0, 16, 255}, {0, 20, 255}, {0, 24, 255}, {0, 28, 255}, {0, 32, 255}, {0, 36, 255}, {0, 40, 255}, {0, 44, 255}, {0, 48, 255}, {0, 52, 255}, {0, 56, 255}, {0, 60, 255}, {0, 64, 255}, {0, 68, 255}, {0, 72, 255}, {0, 76, 255}, {0, 80, 255}, {0, 84, 255}, {0, 88, 255}, {0, 92, 255}, {0, 96, 255}, {0, 100, 255}, {0, 104, 255}, {0, 108, 255}, {0, 112, 255}, {0, 116, 255}, {0, 120, 255}, {0, 124, 255}, {0, 128, 255}, {0, 131, 255}, {0, 135, 255}, {0, 139, 255}, {0, 143, 255}, {0, 147, 255}, {0, 151, 255}, {0, 155, 255}, {0, 159, 255}, {0, 163, 255}, {0, 167, 255}, {0, 171, 255}, {0, 175, 255}, {0, 179, 255}, {0, 183, 255}, {0, 187, 255}, {0, 191, 255}, {0, 195, 255}, {0, 199, 255}, {0, 203, 255}, {0, 207, 255}, {0, 211, 255}, {0, 215, 255}, {0, 219, 255}, {0, 223, 255}, {0, 227, 255}, {0, 231, 255}, {0, 235, 255}, {0, 239, 255}, {0, 243, 255}, {0, 247, 255}, {0, 251, 255}, {0, 255, 255}, {4, 255, 251}, {8, 255, 247}, {12, 255, 243}, {16, 255, 239}, {20, 255, 235}, {24, 255, 231}, {28, 255, 227}, {32, 255, 223}, {36, 255, 219}, {40, 255, 215}, {44, 255, 211}, {48, 255, 207}, {52, 255, 203}, {56, 255, 199}, {60, 255, 195}, {64, 255, 191}, {68, 255, 187}, {72, 255, 183}, {76, 255, 179}, {80, 255, 175}, {84, 255, 171}, {88, 255, 167}, {92, 255, 163}, {96, 255, 159}, {100, 255, 155}, {104, 255, 151}, {108, 255, 147}, {112, 255, 143}, {116, 255, 139}, {120, 255, 135}, {124, 255, 131}, {128, 255, 128}, {131, 255, 124}, {135, 255, 120}, {139, 255, 116}, {143, 255, 112}, {147, 255, 108}, {151, 255, 104}, {155, 255, 100}, {159, 255, 96}, {163, 255, 92}, {167, 255, 88}, {171, 255, 84}, {175, 255, 80}, {179, 255, 76}, {183, 255, 72}, {187, 255, 68}, {191, 255, 64}, {195, 255, 60}, {199, 255, 56}, {203, 255, 52}, {207, 255, 48}, {211, 255, 44}, {215, 255, 40}, {219, 255, 36}, {223, 255, 32}, {227, 255, 28}, {231, 255, 24}, {235, 255, 20}, {239, 255, 16}, {243, 255, 12}, {247, 255, 8}, {251, 255, 4}, {255, 255, 0}, {255, 251, 0}, {255, 247, 0}, {255, 243, 0}, {255, 239, 0}, {255, 235, 0}, {255, 231, 0}, {255, 227, 0}, {255, 223, 0}, {255, 219, 0}, {255, 215, 0}, {255, 211, 0}, {255, 207, 0}, {255, 203, 0}, {255, 199, 0}, {255, 195, 0}, {255, 191, 0}, {255, 187, 0}, {255, 183, 0}, {255, 179, 0}, {255, 175, 0}, {255, 171, 0}, {255, 167, 0}, {255, 163, 0}, {255, 159, 0}, {255, 155, 0}, {255, 151, 0}, {255, 147, 0}, {255, 143, 0}, {255, 139, 0}, {255, 135, 0}, {255, 131, 0}, {255, 128, 0}, {255, 124, 0}, {255, 120, 0}, {255, 116, 0}, {255, 112, 0}, {255, 108, 0}, {255, 104, 0}, {255, 100, 0}, {255, 96, 0}, {255, 92, 0}, {255, 88, 0}, {255, 84, 0}, {255, 80, 0}, {255, 76, 0}, {255, 72, 0}, {255, 68, 0}, {255, 64, 0}, {255, 60, 0}, {255, 56, 0}, {255, 52, 0}, {255, 48, 0}, {255, 44, 0}, {255, 40, 0}, {255, 36, 0}, {255, 32, 0}, {255, 28, 0}, {255, 24, 0}, {255, 20, 0}, {255, 16, 0}, {255, 12, 0}, {255, 8, 0}, {255, 4, 0}, {255, 0, 0}, {251, 0, 0}, {247, 0, 0}, {243, 0, 0}, {239, 0, 0}, {235, 0, 0}, {231, 0, 0}, {227, 0, 0}, {223, 0, 0}, {219, 0, 0}, {215, 0, 0}, {211, 0, 0}, {207, 0, 0}, {203, 0, 0}, {199, 0, 0}, {195, 0, 0}, {191, 0, 0}, {187, 0, 0}, {183, 0, 0}, {179, 0, 0}, {175, 0, 0}, {171, 0, 0}, {167, 0, 0}, {163, 0, 0}, {159, 0, 0}, {155, 0, 0}, {151, 0, 0}, {147, 0, 0}, {143, 0, 0}, {139, 0, 0}, {135, 0, 0}, {131, 0, 0}, {128, 0, 0}}; double get_time_ms() { struct timeval tv; struct timezone tz; gettimeofday(&tv, &tz); return 1000.*tv.tv_sec + tv.tv_usec/1000.; } // returns a pointer to the nth word (starting from 0) in string s char *sword(const char *s, const char *delim, int n) { if (s == NULL) return NULL; s += strspn(s, delim); // skip over initial delimeters int i; for (i = 0; i < n; i++) { s += strcspn(s, delim); // skip over word s += strspn(s, delim); // skip over delimeters } return (char *)s; } // splits a string into k words char **split(const char *s, const char *delim, int *k) { const char *sbuf = s + strspn(s, delim); // skip over initial whitespace s = sbuf; // determine the number of words int num_words = 0; while (*s != '\0') { s = sword(s, delim, 1); num_words++; } // fill in the words int i; s = sbuf; char **words; safe_calloc(words, num_words, char *); for (i = 0; i < num_words; i++) { int slen = strcspn(s, delim); // add "\n" ? safe_calloc(words[i], slen+1, char); // +1 to null-terminate the string strncpy(words[i], s, slen); s = sword(s, delim, 1); } *k = num_words; return words; } // compare the first word of s1 with the first word of s2 int wordcmp(const char *s1, const char *s2, const char *delim) { int n1 = strcspn(s1, delim); int n2 = strcspn(s2, delim); if (n1 < n2) return -1; else if (n1 > n2) return 1; return strncmp(s1, s2, n1); } // replace a word in a string array void replace_word(char **words, int num_words, const char *from, const char *to) { int i; for (i = 0; i < num_words; i++) { if (!strcmp(words[i], from)) { safe_realloc(words[i], strlen(to)+1, char); strcpy(words[i], to); } } } // computes the log factorial of x double lfact(int x) { static double logf[MAXFACT]; static int first = 1; int i; if (first) { first = 0; logf[0] = 0; for (i = 1; i < MAXFACT; i++) logf[i] = log(i) + logf[i-1]; } return logf[x]; } // computes the factorial of x double fact(int x) { return exp(lfact(x)); } // computes the surface area of a unit sphere with dimension d double surface_area_sphere(int d) { switch(d) { case 0: return 2; case 1: return 2*M_PI; case 2: return 4*M_PI; case 3: return 2*M_PI*M_PI; } return (2*M_PI/((double)d-1))*surface_area_sphere(d-2); } // logical not of a binary array void vnot(int y[], int x[], int n) { int i; for (i = 0; i < n; i++) y[i] = !x[i]; } // count the non-zero elements of x int count(int x[], int n) { int i; int cnt = 0; for (i = 0; i < n; i++) if (x[i] != 0) cnt++; return cnt; } // returns a dense array of the indices of x's non-zero elements int find(int *k, int x[], int n) { int i; int cnt = 0; for (i = 0; i < n; i++) if (x[i] != 0) k[cnt++] = i; return cnt; } // returns a sparse array of the indices of x's non-zero elements int findinv(int *k, int x[], int n) { int i; int cnt = 0; for (i = 0; i < n; i++) if (x[i] != 0) k[i] = cnt++; return cnt; } // computes a dense array of the indices of x==a int findeq(int *k, int x[], int a, int n) { int i; int cnt = 0; if (k != NULL) { for (i = 0; i < n; i++) { if (x[i] == a) k[cnt++] = i; } } else for (i = 0; i < n; i++) if (x[i] == a) cnt++; return cnt; } // computes the sum of x's elements double sum(double x[], int n) { int i; double y = 0; for (i = 0; i < n; i++) y += x[i]; return y; } // computes the product of x's elements double prod(double x[], int n) { int i; double y = 1; for (i = 0; i < n; i++) y *= x[i]; return y; } // computes the max of x double arr_max(double x[], int n) { int i; double y = x[0]; for (i = 1; i < n; i++) if (x[i] > y) y = x[i]; return y; } // computes the max of x int arr_max_i(int x[], int n) { int i; int y = x[0]; for (i = 1; i < n; i++) if (x[i] > y) y = x[i]; return y; } // computes the masked max of x double arr_max_masked(double x[], int mask[], int n) { int i; for (i = 0; i < n; i++) if (mask[i]) break; if (i==n) return NAN; double y = x[i++]; for (; i < n; i++) if (mask[i] && (x[i] > y)) y = x[i]; return y; } // computes the masked max of x float arr_maxf_masked(float x[], int mask[], int n) { int i; for (i = 0; i < n; i++) if (mask[i]) break; if (i==n) return NAN; float y = x[i++]; for (; i < n; i++) if (mask[i] && (x[i] > y)) y = x[i]; return y; } // computes the min of x double arr_min(double x[], int n) { int i; double y = x[0]; for (i = 1; i < n; i++) if (x[i] < y) y = x[i]; return y; } // computes the min of x int arr_min_i(int x[], int n) { int i; int y = x[0]; for (i = 1; i < n; i++) if (x[i] < y) y = x[i]; return y; } // computes the masked min of x double arr_min_masked(double x[], int mask[], int n) { int i; for (i = 0; i < n; i++) if (mask[i] != 0) break; if (i==n) return NAN; double y = x[i++]; for (; i < n; i++) if (mask[i] && (x[i] < y)) y = x[i]; return y; } // computes the masked min of x float arr_minf_masked(float x[], int mask[], int n) { int i; for (i = 0; i < n; i++) if (mask[i]) break; if (i==n) return NAN; float y = x[i++]; for (; i < n; i++) if (mask[i] && (x[i] < y)) y = x[i]; return y; } // returns the index of the max of x int find_max(double x[], int n) { int i; int idx = 0; for (i = 1; i < n; i++) if (x[i] > x[idx]) idx = i; return idx; } // returns the index of the min of x int find_min(double x[], int n) { int i; int idx = 0; for (i = 1; i < n; i++) if (x[i] < x[idx]) idx = i; return idx; } // returns the index of the max of x int find_imax(int x[], int n) { int i; int idx = 0; for (i = 1; i < n; i++) if (x[i] > x[idx]) idx = i; return idx; } // returns the index of the min of x int find_imin(int x[], int n) { int i; int idx = 0; for (i = 1; i < n; i++) if (x[i] < x[idx]) idx = i; return idx; } // computes the sum of x's elements int isum(int x[], int n) { int i; int y = 0; for (i = 0; i < n; i++) y += x[i]; return y; } // computes the max of x int imax(int x[], int n) { int i; int y = x[0]; for (i = 1; i < n; i++) if (x[i] > y) y = x[i]; return y; } // computes the min of x int imin(int x[], int n) { int i; int y = x[0]; for (i = 1; i < n; i++) if (x[i] < y) y = x[i]; return y; } // computes the norm of x double norm(double x[], int n) { double d = 0.0; int i; for (i = 0; i < n; i++) d += x[i]*x[i]; return sqrt(d); } // computes the norm of x-y double dist(double x[], double y[], int n) { double d = 0.0; int i; for (i = 0; i < n; i++) d += (x[i]-y[i])*(x[i]-y[i]); return sqrt(d); } // computes the norm^2 of x-y double dist2(double x[], double y[], int n) { double d = 0.0; int i; for (i = 0; i < n; i++) d += (x[i]-y[i])*(x[i]-y[i]); return d; } // computes the dot product of z and y double dot(double x[], double y[], int n) { int i; double z = 0.0; for (i = 0; i < n; i++) z += x[i]*y[i]; return z; } //computes the cross product of x and y void cross(double z[3], double x[3], double y[3]) { z[0] = x[1]*y[2] - x[2]*y[1]; z[1] = x[2]*y[0] - x[0]*y[2]; z[2] = x[0]*y[1] - x[1]*y[0]; } void cross4d(double w[4], double x[4], double y[4], double z[4]) { double **V = new_matrix2(4, 3); int i; for (i = 0; i < 4; ++i) { V[i][0] = x[i]; V[i][1] = y[1]; V[i][2] = z[i]; } double **W = new_matrix2(3, 3); int indices[4][3] = {{2, 3, 4}, {1, 3, 4}, {1, 2, 4}, {1, 2, 3}}; int cut_axis = 0; double dmax = 0; for (i = 0; i < 4; ++i) { reorder_rows(W, V, indices[i], 3, 3); double tmp = fabs(det(W, 3)); if (dmax < tmp) { dmax = tmp; cut_axis = i; } } double *c0 = V[cut_axis]; int uncut_axis[3]; for (i = 0; i < cut_axis; ++i) { uncut_axis[i] = i; w[i] = 0; } for (i = cut_axis + 1; i < 4; ++i) { uncut_axis[i-1] = i; w[i] = 0; } w[cut_axis] = 1; reorder_rows(W, V, uncut_axis, 3, 3); inv(W, W, 3); mult(c0, c0, -1, 3); double tmp[3]; matrix_vec_mult(tmp, W, c0, 3, 3); for (i = 0; i < 3; ++i) { w[uncut_axis[i]] = tmp[i]; } free_matrix2(V); free_matrix2(W); } // adds two vectors, z = x+y void add(double z[], double x[], double y[], int n) { int i; for (i = 0; i < n; i++) z[i] = x[i] + y[i]; } // subtracts two vectors, z = x-y void sub(double z[], double x[], double y[], int n) { int i; for (i = 0; i < n; i++) z[i] = x[i] - y[i]; } // multiplies a vector by a scalar, y = c*x void mult(double y[], double x[], double c, int n) { int i; for (i = 0; i < n; i++) y[i] = c*x[i]; } // computes the cumulative sum of x void cumsum(double y[], double x[], int n) { int i; double c = 0; for (i = 0; i < n; i++) { c += x[i]; y[i] = c; } } // takes absolute value element-wise void vec_func(double y[], double x[], double n, double (*f)(double)) { int i; for (i = 0; i < n; ++i) { y[i] = (*f)(x[i]); } } // sets y = x/norm(x) void normalize(double y[], double x[], int n) { double d = norm(x, n); int i; for (i = 0; i < n; i++) y[i] = x[i]/d; } // sets y = x/sum(x) void normalize_pmf(double y[], double x[], int n) { double d = sum(x, n); int i; for (i = 0; i < n; i++) y[i] = x[i]/d; } // multiplies two vectors, z = x.*y void vmult(double z[], double x[], double y[], int n) { int i; for (i = 0; i < n; i++) z[i] = x[i]*y[i]; } // averages two vectors, z = (x+y)/2 void avg(double z[], double x[], double y[], int n) { add(z, x, y, n); mult(z, z, .5, n); } // averages two vectors, z = w*x+(1-w)*y void wavg(double z[], double x[], double y[], double w, int n) { int i; for (i = 0; i < n; i++) z[i] = w*x[i] + (1-w)*y[i]; } // averages three vectors, y = (x1+x2+x3)/3 void avg3(double y[], double x1[], double x2[], double x3[], int n) { add(y, x1, x2, n); add(y, y, x3, n); mult(y, y, 1/3.0, n); } // calculate the projection of x onto y void proj(double z[], double x[], double y[], int n) { double u[n]; // y's unit vector double d = norm(y, n); mult(u, y, 1/d, n); mult(z, u, dot(x,u,n), n); } // binary search to find i s.t. A[i-1] <= x < A[i] int binary_search(double x, double *A, int n) { int i0 = 0; int i1 = n-1; int i; while (i0 <= i1) { i = (i0 + i1) / 2; if (x > A[i]) i0 = i + 1; else if (i > 0 && x < A[i-1]) i1 = i-1; else break; } if (i0 <= i1) return i; return n-1; } void plane_from_3points(double *coeffs, double *p0, double *p1, double *p2) { double diff1[3], diff2[3]; sub(diff1, p1, p0, 3); sub(diff2, p2, p0, 3); double normal[3]; cross(normal, diff1, diff2); normalize(normal, normal, 3); double flip = normal[2] > 0.0 ? -1.0 : 1.0; // flip normal towards camera coeffs[0] = normal[0] * flip; coeffs[1] = normal[1] * flip; coeffs[2] = normal[2] * flip; coeffs[3] = -dot(normal, p0, 3) * flip; } // quaternion multiplication: z = x*y void quaternion_mult(double z[4], double x[4], double y[4]) { double a = x[0]; double b = x[1]; double c = x[2]; double d = x[3]; double y0 = y[0]; double y1 = y[1]; double y2 = y[2]; double y3 = y[3]; z[0] = a*y0 - b*y1 - c*y2 - d*y3; z[1] = b*y0 + a*y1 - d*y2 + c*y3; z[2] = c*y0 + d*y1 + a*y2 - b*y3; z[3] = d*y0 - c*y1 + b*y2 + a*y3; } // invert a quaternion void quaternion_inverse(double q_inv[4], double q[4]) { q_inv[0] = q[0]; q_inv[1] = -q[1]; q_inv[2] = -q[2]; q_inv[3] = -q[3]; } // quaternion exponentiation (q2 = q^a) void quaternion_pow(double q2[4], double q[4], double a) { double u[3]; // axis of rotation normalize(u, &q[1], 3); double w = MIN(MAX(q[0], -1.0), 1.0); // for numerical stability double theta2 = acos(w); // theta / 2.0 double s = sin(a*theta2); q2[0] = cos(a*theta2); mult(&q2[1], u, s, 3); } // quaternion interpolation (slerp) void quaternion_interpolation(double q[4], double q0[4], double q1[4], double t) { double q0_inv[4], q01[4]; quaternion_inverse(q0_inv, q0); quaternion_mult(q01, q1, q0_inv); quaternion_pow(q01, q01, t); quaternion_mult(q, q01, q0); } // convert a rotation matrix to a unit quaternion void rotation_matrix_to_quaternion(double *q, double **R) { double S; double tr = R[0][0] + R[1][1] + R[2][2]; if (tr > 0) { S = sqrt(tr+1.0) * 2; // S=4*qw q[0] = 0.25 * S; q[1] = (R[2][1] - R[1][2]) / S; q[2] = (R[0][2] - R[2][0]) / S; q[3] = (R[1][0] - R[0][1]) / S; } else if ((R[0][0] > R[1][1]) && (R[0][0] > R[2][2])) { S = sqrt(1.0 + R[0][0] - R[1][1] - R[2][2]) * 2; // S=4*qx q[0] = (R[2][1] - R[1][2]) / S; q[1] = 0.25 * S; q[2] = (R[0][1] + R[1][0]) / S; q[3] = (R[0][2] + R[2][0]) / S; } else if (R[1][1] > R[2][2]) { S = sqrt(1.0 + R[1][1] - R[0][0] - R[2][2]) * 2; // S=4*qy q[0] = (R[0][2] - R[2][0]) / S; q[1] = (R[0][1] + R[1][0]) / S; q[2] = 0.25 * S; q[3] = (R[1][2] + R[2][1]) / S; } else { S = sqrt(1.0 + R[2][2] - R[0][0] - R[1][1]) * 2; // S=4*qz q[0] = (R[1][0] - R[0][1]) / S; q[1] = (R[0][2] + R[2][0]) / S; q[2] = (R[1][2] + R[2][1]) / S; q[3] = 0.25 * S; } normalize(q, q, 4); } // convert a unit quaternion to a rotation matrix void quaternion_to_rotation_matrix(double **R, double *q) { double a = q[0]; double b = q[1]; double c = q[2]; double d = q[3]; R[0][0] = a*a + b*b - c*c - d*d; R[0][1] = 2*b*c - 2*a*d; R[0][2] = 2*b*d + 2*a*c; R[1][0] = 2*b*c + 2*a*d; R[1][1] = a*a - b*b + c*c - d*d; R[1][2] = 2*c*d - 2*a*b; R[2][0] = 2*b*d - 2*a*c; R[2][1] = 2*c*d + 2*a*b; R[2][2] = a*a - b*b - c*c + d*d; } int find_first_non_zero(double *v, int n) { int i; for (i = 0; i < n; ++i) { if (v[i] != 0.) return i; } return -1; } int find_first_lt(double *x, double a, int n) { int i; for (i = 0; i < n; ++i) if (x[i] < a) break; return i; } int find_first_gt(double *x, double a, int n) { int i; for (i = 0; i < n; ++i) if (x[i] > a) break; return i; } /* short *ismember(double *A, double *B, int n, int m) { short *C; safe_calloc(C, n, short); int i, j; // NOTE(sanja): this can be done in O(n log n + m) if necessary. Also, SSE2-able :) for (i = 0; i < n; ++i) { for (j = 0; j < m; ++j) { if (double_is_equal(A[i], B[j])) { C[i] = 1; break; } } } return C; } short *ismemberi(int *A, int *B, int n, int m) { short *C; safe_calloc(C, n, short); int i, j; // NOTE(sanja): this can be done in O(n log n + m) if necessary. Also, SSE2-able :) for (i = 0; i < n; ++i) { for (j = 0; j < m; ++j) { if (A[i] == B[j]) { C[i] = 1; break; } } } return C; } */ // check if y contains x int ismemberi(int x, int *y, int n) { int i; for (i = 0; i < n; ++i) if (x == y[i]) return 1; return 0; } // reverses an array of doubles (safe for x==y) void reverse(double *y, double *x, int n) { int i; for (i = 0; i < n/2; i++) { double tmp = x[i]; y[i] = x[n-i-1]; y[n-i-1] = tmp; } } // reverses an array of ints (safe for x==y) void reversei(int *y, int *x, int n) { int i; for (i = 0; i < n/2; i++) { int tmp = x[i]; y[i] = x[n-i-1]; y[n-i-1] = tmp; } } // reorder an array of doubles (safe for x==y) void reorder(double *y, double *x, int *idx, int n) { int i; double *y2 = y; if (x==y) safe_calloc(y2, n, double); for (i = 0; i < n; i++) y2[i] = x[idx[i]]; if (x==y) { memcpy(y, y2, n*sizeof(double)); free(y2); } } // reorder an array of ints (safe for x==y) void reorderi(int *y, int *x, int *idx, int n) { int i; int *y2 = y; if (x==y) safe_calloc(y2, n, int); for (i = 0; i < n; i++) y2[i] = x[idx[i]]; if (x==y) { memcpy(y, y2, n*sizeof(int)); free(y2); } } // add an element to the front of a list ilist_t *ilist_add(ilist_t *x, int a) { ilist_t *head; safe_malloc(head, 1, ilist_t); head->x = a; head->next = x; head->len = (x ? 1 + x->len : 1); return head; } // check if a list contains an element int ilist_contains(ilist_t *x, int a) { if (!x) return 0; ilist_t *tmp; for (tmp = x; tmp; tmp = tmp->next) if (tmp->x == a) return 1; return 0; } // find the index of an element in a list (or -1 if not found) int ilist_find(ilist_t *x, int a) { int i = 0; ilist_t *tmp; for (tmp = x; tmp; tmp = tmp->next) { if (tmp->x == a) return i; i++; } return -1; } // free a list void ilist_free(ilist_t *x) { ilist_t *tmp, *tmp2; tmp = x; while (tmp) { tmp2 = tmp->next; free(tmp); tmp = tmp2; } } static void init_rand() { static int first = 1; if (first) { first = 0; int seed = time(NULL); // seed = 1371836140; //int seed = 1368560954; <-- Crashes straw bowl on 3/9 //1368457226; <--- Shows overlap on 5/3 printf("********* seed = %d\n", seed); srand (seed); } } // returns a random int between 0 and n-1 int irand(int n) { init_rand(); if (n < 0) printf("Negative n: %d\n", n); return rand() % n; } // returns a random double in [0,1] double frand() { init_rand(); return fabs(rand()) / (double)RAND_MAX; } // samples d integers from 0:n-1 uniformly without replacement void randperm(int *x, int n, int d) { init_rand(); int i; if (d > n) { fprintf(stderr, "Error: d > n in randperm()\n"); return; } // sample a random starting point int i0 = rand() % n; // use a random prime step to cycle through x static const int big_primes[100] = {996311, 163573, 481123, 187219, 963323, 103769, 786979, 826363, 874891, 168991, 442501, 318679, 810377, 471073, 914519, 251059, 321983, 220009, 211877, 875339, 605603, 578483, 219619, 860089, 644911, 398819, 544927, 444043, 161717, 301447, 201329, 252731, 301463, 458207, 140053, 906713, 946487, 524389, 522857, 387151, 904283, 415213, 191047, 791543, 433337, 302989, 445853, 178859, 208499, 943589, 957331, 601291, 148439, 296801, 400657, 829637, 112337, 134707, 240047, 669667, 746287, 668243, 488329, 575611, 350219, 758449, 257053, 704287, 252283, 414539, 647771, 791201, 166031, 931313, 787021, 520529, 474667, 484361, 358907, 540271, 542251, 825829, 804709, 664843, 423347, 820367, 562577, 398347, 940349, 880603, 578267, 644783, 611833, 273001, 354329, 506101, 292837, 851017, 262103, 288989}; int step = big_primes[rand() % 100]; int idx = i0; for (i = 0; i < d; i++) { x[i] = idx; idx = (idx + step) % n; } /* if (d > 2*sqrt(n*log(n))) { double r[n]; int idx[n]; for (i = 0; i < n; i++) r[i] = frand(); sort_indices(r, idx, n); memcpy(x, idx, d*sizeof(int)); } else { for (i = 0; i < d; i++) { while (1) { x[i] = rand() % n; for (j = 0; j < i; j++) if (x[j] == x[i]) break; if (j == i) // x[i] is unique break; } } } */ } // approximation to the inverse error function double erfinv(double x) { if (x < 0) return -erfinv(-x); double a = .147; double y1 = (2/(M_PI*a) + log(1-x*x)/2.0); double y2 = sqrt(y1*y1 - (1/a)*log(1-x*x)); double y3 = sqrt(y2 - y1); return y3; } // generate a random sample from a normal distribution double normrand(double mu, double sigma) { double u = frand(); return mu + sigma*sqrt(2.0)*erfinv(2*u-1); } // compute the pdf of a normal random variable double normpdf(double x, double mu, double sigma) { double dx = x - mu; return exp(-dx*dx / (2*sigma*sigma)) / (sqrt(2*M_PI) * sigma); } // samples from the probability mass function w with n elements int pmfrand(double *w, int n) { int i; double r = frand(); double wtot = 0; for (i = 0; i < n; i++) { wtot += w[i]; if (wtot >= r) return i; } return 0; } // samples from the cumulative mass function w with n elements (much faster than pmfrand) int cmfrand(double *w, int n) { double r = frand(); return binary_search(r, w, n); } // sample from a multivariate normal void mvnrand(double *x, double *mu, double **S, int d) { double z[d], **V = new_matrix2(d,d); eigen_symm(z,V,S,d); int i; for (i = 0; i < d; i++) z[i] = sqrt(z[i]); mvnrand_pcs(x,mu,z,V,d); free_matrix2(V); } double mvnpdf(double *x, double *mu, double **S, int d) { double **S_inv = new_matrix2(d,d); inv(S_inv, S, d); double dx[d]; sub(dx, x, mu, d); double S_inv_dx[d]; matrix_vec_mult(S_inv_dx, S_inv, dx, d, d); double dm = dot(dx, S_inv_dx, d); double p = exp(-.5*dm) / sqrt(pow(2*M_PI, d) * det(S,d)); free_matrix2(S_inv); return p; } /* compute a multivariate normal pdf double mvnpdf(double *x, double *mu, double **S, int d) { double z[d], **V = new_matrix2(d,d); eigen_symm(z,V,S,d); int i; for (i = 0; i < d; i++) z[i] = sqrt(z[i]); printf("S = [%f %f %f; %f %f %f; %f %f %f]\n", S[0][0], S[0][1], S[0][2], S[1][0], S[1][1], S[1][2], S[2][0], S[2][1], S[2][2]); //dbug printf("z = [%f, %f, %f]\n", z[0], z[1], z[2]); //dbug double p = mvnpdf_pcs(x,mu,z,V,d); free_matrix2(V); return p; } */ // sample from a multivariate normal in principal components form void mvnrand_pcs(double *x, double *mu, double *z, double **V, int d) { int i; double s, v[d]; memcpy(x, mu, d*sizeof(double)); for (i = 0; i < d; i++) { s = normrand(0, z[i]); mult(v, V[i], s, d); // v = s*V[i] add(x, x, v, d); // x += v } } // compute a multivariate normal pdf in principal components form double mvnpdf_pcs(double *x, double *mu, double *z, double **V, int d) { int i; double xv, dx[d]; sub(dx, x, mu, d); // dx = x - mu double logp = -(d/2)*log(2*M_PI) - log(prod(z,d)); for (i = 0; i < d; i++) { xv = dot(dx, V[i], d) / z[i]; logp -= 0.5*xv*xv; } return exp(logp); } // sample from an angular central gaussian in principal components form void acgrand_pcs(double *x, double *z, double **V, int d) { int i; double mu[d]; for (i = 0; i < d; i++) mu[i] = 0; mvnrand_pcs(x, mu, z, V, d); normalize(x, x, d); } // compute an angular central gaussian pdf in principal components form double acgpdf_pcs(double *x, double *z, double **V, int d) { int i; double p = 1 / (prod(z,d) * surface_area_sphere(d-1)); double xv, md = 0; // mahalanobis distance for (i = 0; i < d; i++) { xv = dot(x, V[i], d) / z[i]; md += xv*xv; } p *= pow(md, -d/2); return p; } // create a new n-by-m-by-p 3d matrix of doubles double ***new_matrix3(int n, int m, int p) { if (n*m*p == 0) return NULL; int i; double **X2 = new_matrix2(n*m, p); double ***X; safe_malloc(X, n, double**); for (i = 0; i < n; i++) X[i] = X2 + m*i; return X; } // free a 3d matrix void free_matrix3(double ***X) { free_matrix2(X[0]); free(X); } // create a new n-by-m-by-p 3d matrix of floats float ***new_matrix3f(int n, int m, int p) { if (n*m*p == 0) return NULL; int i; float **X2 = new_matrix2f(n*m, p); float ***X; safe_malloc(X, n, float**); for (i = 0; i < n; i++) X[i] = X2 + m*i; return X; } // free a 3d matrix void free_matrix3f(float ***X) { free_matrix2f(X[0]); free(X); } // copy a 3d matrix of doubles: Y = X void matrix3_copy(double ***Y, double ***X, int n, int m, int p) { memcpy(Y[0][0], X[0][0], n*m*p*sizeof(double)); } // clone a 3d matrix of doubles: Y = new(X) double ***matrix3_clone(double ***X, int n, int m, int p) { double ***Y = new_matrix3(n,m,p); matrix3_copy(Y, X, n, m, p); return Y; } // create a new n-by-m 2d matrix of doubles double **new_matrix2(int n, int m) { if (n*m == 0) return NULL; int i; double *raw, **X; safe_calloc(raw, n*m, double); safe_malloc(X, n, double*); for (i = 0; i < n; i++) X[i] = raw + m*i; return X; } void add_rows_matrix2(double ***X, int n, int m, int new_n) { int i; double *raw = (*X)[0]; safe_realloc(raw, m * new_n, double); safe_realloc(*X, new_n, double*); for (i = 0; i < new_n; i++) (*X)[i] = raw + m*i; } void add_rows_matrix2i(int ***X, int n, int m, int new_n) { int i; int *raw = (*X)[0]; safe_realloc(raw, m * new_n, int); safe_realloc(*X, new_n, int*); for (i = 0; i < new_n; i++) (*X)[i] = raw + m*i; } /* void resize_matrix2(double ***X, int n, int m, int n2, int m2) { if (m2 == m) add_rows_matrix2(X, n, m, n2); else { } } */ // create a new n-by-m 2d matrix of floats float **new_matrix2f(int n, int m) { if (n*m == 0) return NULL; int i; float *raw, **X; safe_calloc(raw, n*m, float); safe_malloc(X, n, float*); for (i = 0; i < n; i++) X[i] = raw + m*i; return X; } // create a new n-by-m 2d matrix of ints int **new_matrix2i(int n, int m) { if (n*m == 0) return NULL; int i, *raw, **X; safe_calloc(raw, n*m, int); safe_malloc(X, n, int*); for (i = 0; i < n; i++) X[i] = raw + m*i; return X; } // create a new n-by-m 2d matrix of chars char **new_matrix2c(int n, int m) { if (n*m == 0) return NULL; int i; char *raw, **X; safe_calloc(raw, n*m, char); safe_malloc(X, n, char*); for (i = 0; i < n; i++) X[i] = raw + m*i; return X; } // create a new n-by-m 2d matrix of doubles double **new_matrix2_data(int n, int m, double *data) { double **X = new_matrix2(n,m); memcpy(X[0], data, n*m*sizeof(double)); return X; } // create a new n-by-m 2d matrix of floats float **new_matrix2f_data(int n, int m, float *data) { float **X = new_matrix2f(n,m); memcpy(X[0], data, n*m*sizeof(float)); return X; } // create a new n-by-m 2d matrix of ints int **new_matrix2i_data(int n, int m, int *data) { int **X = new_matrix2i(n,m); memcpy(X[0], data, n*m*sizeof(int)); return X; } // create a new n-by-m 2d matrix of chars char **new_matrix2c_data(int n, int m, char *data) { char **X = new_matrix2c(n,m); memcpy(X[0], data, n*m*sizeof(char)); return X; } /* double **add_matrix_row(double **X, int n, int m) { //printf("DANGER! Reallocating matrix rows is not tested yet!\n"); double *raw = X[0]; safe_realloc(raw, (n + 1) * m, double); safe_realloc(X, n+1, double*); X[n] = raw + m * n; return X; } */ double **new_identity_matrix2(int n) { double **mat = new_matrix2(n, n); int i; for (i = 0; i < n; ++i) mat[i][i] = 1; return mat; } int **new_identity_matrix2i(int n) { int **mat = new_matrix2i(n, n); int i; for (i = 0; i < n; ++i) mat[i][i] = 1; return mat; } double **new_diag_matrix2(double *diag, int n) { double **mat = new_matrix2(n, n); int i; for (i = 0; i < n; ++i) { mat[i][i] = diag[i]; } return mat; } int **new_diag_matrix2i(int *diag, int n) { int **mat = new_matrix2i(n, n); int i; for (i = 0; i < n; ++i) { mat[i][i] = diag[i]; } return mat; } // free a 2d matrix of doubles void free_matrix2(double **X) { if (X == NULL) return; free(X[0]); free(X); } // free a 2d matrix of floats void free_matrix2f(float **X) { if (X == NULL) return; free(X[0]); free(X); } // free a 2d matrix of ints void free_matrix2i(int **X) { if (X == NULL) return; free(X[0]); free(X); } // free a 2d matrix of chars void free_matrix2c(char **X) { if (X == NULL) return; free(X[0]); free(X); } /* * Write a matrix in the following format. * * <nrows> <ncols> * <row 1> * <row 2> * ... */ void save_matrix(const char *fout, double **X, int n, int m) { //fprintf(stderr, "saving matrix to %s\n", fout); FILE *f = fopen(fout, "w"); int i, j; fprintf(f, "%d %d\n", n, m); for (i = 0; i < n; i++) { for (j = 0; j < m; j++) fprintf(f, "%f ", X[i][j]); fprintf(f, "\n"); } fclose(f); } void save_matrixi(const char *fout, int **X, int n, int m) { //fprintf(stderr, "saving matrix to %s\n", fout); FILE *f = fopen(fout, "w"); int i, j; fprintf(f, "%d %d\n", n, m); for (i = 0; i < n; i++) { for (j = 0; j < m; j++) fprintf(f, "%d ", X[i][j]); fprintf(f, "\n"); } fclose(f); } /* * Write a 3d matrix in the following format. * * <ntabs> <nrows> <ncols> * <tab 1 row 1> * <tab 1 row 2> * ... * <tab 2 row 1> * <tab 2 row 2> * ... */ void save_matrix3(const char *fout, double ***X, int n, int m, int p) { //fprintf(stderr, "saving matrix3 to %s\n", fout); FILE *f = fopen(fout, "w"); int i, j, k; fprintf(f, "%d %d %d\n", n, m, p); for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { for (k = 0; k < p; k++) fprintf(f, "%f ", X[i][j][k]); fprintf(f, "\n"); } } fclose(f); } /* * Load a matrix in the following format. * * <nrows> <ncols> * <row 1> * <row 2> * ... */ double **load_matrix(char *fin, int *n, int *m) { FILE *f = fopen(fin, "r"); if (f == NULL) { fprintf(stderr, "Invalid filename: %s\n", fin); return NULL; } char sbuf0[128], *s = sbuf0; if (fgets(s, 128, f) == NULL || sscanf(s, "%d %d", n, m) < 2) { fprintf(stderr, "Corrupt matrix header in file %s\n", fin); fclose(f); return NULL; } double **X = new_matrix2(*n, *m); const int CHARS_PER_FLOAT = 20; const int buflen = CHARS_PER_FLOAT * (*m); char sbuf[buflen]; int i, j; for (i = 0; i < *n; i++) { s = sbuf; if (fgets(s, buflen, f) == NULL) break; for (j = 0; j < *m; j++) { if (sscanf(s, "%lf", &X[i][j]) < 1) break; s = sword(s, " \t", 1); } if (j < *m) break; } if (i < *n) { fprintf(stderr, "Corrupt matrix file '%s' at line %d, element %d\n", fin, i+2, j+1); fclose(f); free_matrix2(X); return NULL; } fclose(f); return X; } /* * Load a 3d matrix in the following format. * * <ntabs> <nrows> <ncols> * <tab 1 row 1> * <tab 1 row 2> * ... * <tab 2 row 1> * <tab 2 row 2> * ... */ double ***load_matrix3(char *fin, int *n, int *m, int *p) { FILE *f = fopen(fin, "r"); if (f == NULL) { fprintf(stderr, "Invalid filename: %s\n", fin); return NULL; } char sbuf0[128], *s = sbuf0; if (fgets(s, 128, f) == NULL || sscanf(s, "%d %d %d", n, m, p) < 3) { fprintf(stderr, "Corrupt matrix header in file %s\n", fin); fclose(f); return NULL; } double ***X = new_matrix3(*n, *m, *p); const int CHARS_PER_FLOAT = 20; const int buflen = CHARS_PER_FLOAT * (*p); char sbuf[buflen]; int i, j, k; for (i = 0; i < *n; i++) { for (j = 0; j < *m; j++) { s = sbuf; if (fgets(s, buflen, f) == NULL) break; for (k = 0; k < *p; k++) { if (sscanf(s, "%lf", &X[i][j][k]) < 1) break; s = sword(s, " \t", 1); } if (k < *p) break; } if (j < *m) break; } if (i < *n) { fprintf(stderr, "Corrupt matrix file '%s' at line %d\n", fin, i*(*m)+j+2); fclose(f); free_matrix3(X); return NULL; } fclose(f); return X; } // calculate the area of a triangle double triangle_area(double x[], double y[], double z[], int n) { double a = dist(x, y, n); double b = dist(x, z, n); double c = dist(y, z, n); double s = .5*(a + b + c); return sqrt(s*(s-a)*(s-b)*(s-c)); } // calculate the volume of a tetrahedron double tetrahedron_volume(double x1[], double x2[], double x3[], double x4[], int n) { double U = dist2(x1, x2, n); double V = dist2(x1, x3, n); double W = dist2(x2, x3, n); double u = dist2(x3, x4, n); double v = dist2(x2, x4, n); double w = dist2(x1, x4, n); double a = v+w-U; double b = w+u-V; double c = u+v-W; return sqrt( (4*u*v*w - u*a*a - v*b*b - w*c*c + a*b*c) ) / 12.0 ; } // calculate the volume of a tetrahedron inline double tetrahedron_volume_old(double x[], double y[], double z[], double w[], int n) { // make an orthonormal basis in the xyz plane (with x at the origin) double u[n], v[n], v_proj[n]; sub(u, y, x, n); // u = y-x sub(v, z, x, n); // v = z-x proj(v_proj, v, u, n); // project v onto u sub(v, v, v_proj, n); // v -= v_proj mult(u, u, 1/norm(u,n), n); // normalize u mult(v, v, 1/norm(v,n), n); // normalize v // project (w-x) onto xyz plane double w2[n], wu[n], wv[n], w_proj[n]; sub(w2, w, x, n); // w2 = w-x proj(wu, w2, u, n); // project w2 onto u proj(wv, w2, v, n); // project w2 onto v add(w_proj, wu, wv, n); // w_proj = wu + wv sub(w2, w2, w_proj, n); // w2 -= w_proj double h = norm(w2, n); // height double A = triangle_area(x, y, z, n); return h*A/3.0; } // transpose a matrix void transpose(double **Y, double **X, int n, int m) { double **X2 = X; if (Y == X) X2 = matrix_clone(X,n,m); int i, j; for (i = 0; i < n; i++) for (j = 0; j < m; j++) Y[j][i] = X2[i][j]; if (Y == X) free_matrix2(X2); } /* int test_matrix_copy() { double X_data[6] = {1,2,3,4,5,6}; double **X = new_matrix2_data(3,2, X_data); //double **X = new_matrix2(2,2); //X[0][0] = 1; //X[0][1] = 2; //X[1][0] = 3; //X[1][1] = 4; // 1 2 // 3 4 } */ // matrix copy, Y = X void matrix_copy(double **Y, double **X, int n, int m) { memcpy(Y[0], X[0], n*m*sizeof(double)); } // matrix clone, Y = new(X) double **matrix_clone(double **X, int n, int m) { double **Y = new_matrix2(n,m); matrix_copy(Y, X, n, m); return Y; } // matrix addition, Z = X+Y void matrix_add(double **Z, double **X, double **Y, int n, int m) { add(Z[0], X[0], Y[0], n*m); } // matrix subtraction, Z = X-Y void matrix_sub(double **Z, double **X, double **Y, int n, int m) { sub(Z[0], X[0], Y[0], n*m); } // matrix multiplication, Z = X*Y, where X is n-by-p and Y is p-by-m void matrix_mult(double **Z, double **X, double **Y, int n, int p, int m) { double **Z2 = (Z==X || Z==Y ? new_matrix2(n,m) : Z); int i, j, k; for (i = 0; i < n; i++) { // row i for (j = 0; j < m; j++) { // column j Z2[i][j] = 0; for (k = 0; k < p; k++) Z2[i][j] += X[i][k]*Y[k][j]; } } if (Z==X || Z==Y) { matrix_copy(Z, Z2, n, m); free_matrix2(Z2); } } // matrix-vector multiplication, y = A*x void matrix_vec_mult(double *y, double **A, double *x, int n, int m) { int i; if (y == x) { double z[m]; memcpy(z, x, m*sizeof(double)); for (i = 0; i < n; i++) y[i] = dot(A[i], z, m); } else for (i = 0; i < n; i++) y[i] = dot(A[i], x, m); } // vector-matrix multiplication, y = x*A void vec_matrix_mult(double *y, double *x, double **A, int n, int m) { int i, j; if (y == x) { double z[n]; memcpy(z, x, n*sizeof(double)); for (j = 0; j < m; j++) { y[j] = 0; for (i = 0; i < n; i++) y[j] += z[i]*A[i][j]; } } else { for (j = 0; j < m; j++) { y[j] = 0; for (i = 0; i < n; i++) y[j] += x[i]*A[i][j]; } } } // matrix element-wise multiplication void matrix_elt_mult(double **Z, double **X, double **Y, int n, int m) { int i, j; for (i = 0; i < n; ++i) { for (j = 0; j < m; ++j) { Z[i][j] = X[i][j] * Y[i][j]; } } } void matrix_pow(double **Y, double **X, int n, int m, double pw) { int i, j; for (i = 0; i < n; ++i) for (j = 0; j < m; ++j) Y[i][j] = pow(X[i][j], pw); } void matrix_sum(double y[], double **X, int n, int m) { int i, j; memset(y, 0, n * sizeof(double)); for (i = 0; i < n; ++i) { for (j = 0; j < m; ++j) { y[j] += X[i][j]; } } } // outer product of x and y, Z = x'*y void outer_prod(double **Z, double x[], double y[], int n, int m) { int i, j; for (i = 0; i < n; i++) for (j = 0; j < m; j++) Z[i][j] = x[i]*y[j]; } // row vector min void row_min(double *y, double **X, int n, int m) { int i,j; memcpy(y, X[0], m*sizeof(double)); for (i = 1; i < n; i++) for (j = 0; j < m; j++) if (X[i][j] < y[j]) y[j] = X[i][j]; } // row vector max void row_max(double *y, double **X, int n, int m) { int i,j; memcpy(y, X[0], m*sizeof(double)); for (i = 1; i < n; i++) for (j = 0; j < m; j++) if (X[i][j] > y[j]) y[j] = X[i][j]; } // row vector mean // NOTE(sanja): this is adding up columns, not rows. void mean(double *mu, double **X, int n, int m) { memset(mu, 0, m*sizeof(double)); // mu = 0 int i, j; for (i = 0; i < n; i++) for (j = 0; j < m; j++) mu[j] += X[i][j]; mult(mu, mu, 1/(double)n, m); } void variance(double *vars, double **X, int n, int m) { double mu[m]; mean(mu, X, n, m); memset(vars, 0, m*sizeof(double)); int i, j; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { double dx = X[i][j] - mu[j]; vars[j] += dx*dx; } } mult(vars, vars, 1/(double)n, m); } // compute the covariance of the rows of X, given mean mu void cov(double **S, double **X, double *mu, int n, int m) { int i, j, k; memset(S[0], 0, m*m*sizeof(double)); double dx[m]; if (m == 3) { for (i = 0; i < n; i++) { dx[0] = X[i][0] - mu[0]; dx[1] = X[i][1] - mu[1]; dx[2] = X[i][2] - mu[2]; S[0][0] += dx[0]*dx[0]; S[0][1] += dx[0]*dx[1]; S[0][2] += dx[0]*dx[2]; S[1][0] += dx[1]*dx[0]; S[1][1] += dx[1]*dx[1]; S[1][2] += dx[1]*dx[2]; S[2][0] += dx[2]*dx[0]; S[2][1] += dx[2]*dx[1]; S[2][2] += dx[2]*dx[2]; } } else { for (i = 0; i < n; i++) { sub(dx, X[i], mu, m); for (j = 0; j < m; j++) for (k = 0; k < m; k++) S[j][k] += dx[j]*dx[k]; } } /* double **dX = matrix_clone(X, n, m); if (mu != NULL) for (i = 0; i < n; i++) sub(dX[i], X[i], mu, m); double **dXt = new_matrix2(m, n); transpose(dXt, dX, n, m); matrix_mult(S, dXt, dX, m, n, m); */ mult(S[0], S[0], 1/(double)n, m*m); //free_matrix2(dX); //free_matrix2(dXt); } // weighted row vector mean void wmean(double *mu, double **X, double *w, int n, int m) { memset(mu, 0, m*sizeof(double)); // mu = 0 int i, j; for (i = 0; i < n; i++) for (j = 0; j < m; j++) mu[j] += w[i]*X[i][j]; mult(mu, mu, 1.0/sum(w,n), m); } // compute the weighted covariance of the rows of X, given mean mu void wcov(double **S, double **X, double *w, double *mu, int n, int m) { int i; memset(S[0], 0, m*m*sizeof(double)); double **Si = new_matrix2(m,m); for (i = 0; i < n; i++) { outer_prod(Si, X[i], X[i], m, m); mult(Si[0], Si[0], w[i], m*m); matrix_add(S, S, Si, m, m); } mult(S[0], S[0], 1.0/sum(w,n), m*m); if (mu != NULL) { double **S_mu = new_matrix2(m,m); outer_prod(S_mu, mu, mu, m, m); sub(S[0], S[0], S_mu[0], m*m); free_matrix2(S_mu); } } // solve the equation Ax = b, where A is a square n-by-n matrix void solve(double *x, double **A, double *b, int n) { double **A_inv = new_matrix2(n,n); inv(A_inv, A, n); int i; for (i = 0; i < n; i++) x[i] = dot(A_inv[i], b, n); free_matrix2(A_inv); } // compute the determinant of the n-by-n matrix X double det(double **X, int n) { if (n == 1) return X[0][0]; else if (n == 2) return X[0][0]*X[1][1] - X[0][1]*X[1][0]; else if (n == 3) { double a = X[0][0]; double b = X[0][1]; double c = X[0][2]; double d = X[1][0]; double e = X[1][1]; double f = X[1][2]; double g = X[2][0]; double h = X[2][1]; double i = X[2][2]; return a*e*i - a*f*h + b*f*g - b*d*i + c*d*h - c*e*g; } else if (n == 4) { double a00 = X[0][0]; double a01 = X[0][1]; double a02 = X[0][2]; double a03 = X[0][3]; double a10 = X[1][0]; double a11 = X[1][1]; double a12 = X[1][2]; double a13 = X[1][3]; double a20 = X[2][0]; double a21 = X[2][1]; double a22 = X[2][2]; double a23 = X[2][3]; double a30 = X[3][0]; double a31 = X[3][1]; double a32 = X[3][2]; double a33 = X[3][3]; return a00*a11*a22*a33 - a00*a11*a23*a32 - a00*a12*a21*a33 + a00*a12*a23*a31 + a00*a13*a21*a32 - a00*a13*a22*a31 - a01*a10*a22*a33 + a01*a10*a23*a32 + a01*a12*a20*a33 - a01*a12*a23*a30 - a01*a13*a20*a32 + a01*a13*a22*a30 + a02*a10*a21*a33 - a02*a10*a23*a31 - a02*a11*a20*a33 + a02*a11*a23*a30 + a02*a13*a20*a31 - a02*a13*a21*a30 - a03*a10*a21*a32 + a03*a10*a22*a31 + a03*a11*a20*a32 - a03*a11*a22*a30 - a03*a12*a20*a31 + a03*a12*a21*a30; } else { fprintf(stderr, "Error: det() not supported for > 4x4 matrices\n"); exit(1); } return 0; } // compute the inverse (Y) of the n-by-n matrix X void inv(double **Y, double **X, int n) { double d = det(X,n); if (n == 1) Y[0][0] = 1/d; else if (n == 2) { Y[0][0] = X[1][1] / d; Y[0][1] = -X[0][1] / d; Y[1][0] = -X[1][0] / d; Y[1][1] = X[0][0] / d; } else if (n == 3) { Y[0][0] = (X[1][1]*X[2][2] - X[1][2]*X[2][1]) / d; Y[0][1] = (X[0][2]*X[2][1] - X[0][1]*X[2][2]) / d; Y[0][2] = (X[0][1]*X[1][2] - X[0][2]*X[1][1]) / d; Y[1][0] = (X[1][2]*X[2][0] - X[1][0]*X[2][2]) / d; Y[1][1] = (X[0][0]*X[2][2] - X[0][2]*X[2][0]) / d; Y[1][2] = (X[0][2]*X[1][0] - X[0][0]*X[1][2]) / d; Y[2][0] = (X[1][0]*X[2][1] - X[1][1]*X[2][0]) / d; Y[2][1] = (X[0][1]*X[2][0] - X[0][0]*X[2][1]) / d; Y[2][2] = (X[0][0]*X[1][1] - X[0][1]*X[1][0]) / d; } else if (n == 4) { double a00 = X[0][0]; double a01 = X[0][1]; double a02 = X[0][2]; double a03 = X[0][3]; double a10 = X[1][0]; double a11 = X[1][1]; double a12 = X[1][2]; double a13 = X[1][3]; double a20 = X[2][0]; double a21 = X[2][1]; double a22 = X[2][2]; double a23 = X[2][3]; double a30 = X[3][0]; double a31 = X[3][1]; double a32 = X[3][2]; double a33 = X[3][3]; Y[0][0] = (a11*a22*a33 - a11*a23*a32 - a12*a21*a33 + a12*a23*a31 + a13*a21*a32 - a13*a22*a31) / d; Y[0][1] = (a01*a23*a32 - a01*a22*a33 + a02*a21*a33 - a02*a23*a31 - a03*a21*a32 + a03*a22*a31) / d; Y[0][2] = (a01*a12*a33 - a01*a13*a32 - a02*a11*a33 + a02*a13*a31 + a03*a11*a32 - a03*a12*a31) / d; Y[0][3] = (a01*a13*a22 - a01*a12*a23 + a02*a11*a23 - a02*a13*a21 - a03*a11*a22 + a03*a12*a21) / d; Y[1][0] = (a10*a23*a32 - a10*a22*a33 + a12*a20*a33 - a12*a23*a30 - a13*a20*a32 + a13*a22*a30) / d; Y[1][1] = (a00*a22*a33 - a00*a23*a32 - a02*a20*a33 + a02*a23*a30 + a03*a20*a32 - a03*a22*a30) / d; Y[1][2] = (a00*a13*a32 - a00*a12*a33 + a02*a10*a33 - a02*a13*a30 - a03*a10*a32 + a03*a12*a30) / d; Y[1][3] = (a00*a12*a23 - a00*a13*a22 - a02*a10*a23 + a02*a13*a20 + a03*a10*a22 - a03*a12*a20) / d; Y[2][0] = (a10*a21*a33 - a10*a23*a31 - a11*a20*a33 + a11*a23*a30 + a13*a20*a31 - a13*a21*a30) / d; Y[2][1] = (a00*a23*a31 - a00*a21*a33 + a01*a20*a33 - a01*a23*a30 - a03*a20*a31 + a03*a21*a30) / d; Y[2][2] = (a00*a11*a33 - a00*a13*a31 - a01*a10*a33 + a01*a13*a30 + a03*a10*a31 - a03*a11*a30) / d; Y[2][3] = (a00*a13*a21 - a00*a11*a23 + a01*a10*a23 - a01*a13*a20 - a03*a10*a21 + a03*a11*a20) / d; Y[3][0] = (a10*a22*a31 - a10*a21*a32 + a11*a20*a32 - a11*a22*a30 - a12*a20*a31 + a12*a21*a30) / d; Y[3][1] = (a00*a21*a32 - a00*a22*a31 - a01*a20*a32 + a01*a22*a30 + a02*a20*a31 - a02*a21*a30) / d; Y[3][2] = (a00*a12*a31 - a00*a11*a32 + a01*a10*a32 - a01*a12*a30 - a02*a10*a31 + a02*a11*a30) / d; Y[3][3] = (a00*a11*a22 - a00*a12*a21 - a01*a10*a22 + a01*a12*a20 + a02*a10*a21 - a02*a11*a20) / d; } else { fprintf(stderr, "Error: inv() not supported for > 4x4 matrices\n"); exit(1); } } /** * Solves the quadratic equation: f(x) = a*x^2 + b*x + c * Sets x[0] and x[1] to be the real roots of f(x), if found. * Returns the number of real roots found. */ int solve_quadratic(double *x, double a, double b, double c) { double s2 = b*b - 4*a*c; if (s2 < 0.0) return 0; double s = sqrt(s2); x[0] = .5*(-b + s)/a; x[1] = .5*(-b - s)/a; return 2; } /** * Solves the cubic equation: f(x) = a*x^3 + b*x^2 + c*x + d * Sets x[0], x[1], and x[2] to be the real roots of f(x), if found. * Returns the number of real roots found. * int solve_cubic(double *x, double a, double b, double c, double d) { double p = -b/(3.0*a); double q = p*p*p + (b*c - 3.0*a*d)/(6*a*a); double r = c/(3.0*a); } */ /** * Compute the eigenvalues z and eigenvectors V of a real symmetric n-by-n matrix X * The eigenvalues, z, will be sorted from smallest to largest in magnitude, and the * eigenvectors will be stored in the rows of V. * @param X (input) Symmetric n-by-n matrix * @param n (input) Dimensionality of X * @param z (output) Eigenvalues of X, from smallest to largest in magnitude * @param V (output) Eigenvectors of X, in the rows */ /* void eigen_symm(double z[], double **V, double **X, int n) { double **Vt = matrix_clone(X,n,n); double z2[n]; int i, j; //TODO: replace this with solve_cubic() for n < 4 int info = LAPACKE_dsyevd(LAPACK_COL_MAJOR, 'V', 'U', n, Vt[0], n, z2); if (info) fprintf(stderr, "Error: eigen_symm failed to converge!\n"); // sort eigenvalues double tolerance = 1e-10; int idx[n]; sort_indices(z2, idx, n); if (z2[idx[0]] < -tolerance) // negative eigenvalues --> sort in reverse order reversei(idx, idx, n); for (i = 0; i < n; i++) z[i] = z2[idx[i]]; for (i = 0; i < n; i++) for (j = 0; j < n; j++) V[i][j] = Vt[j][idx[i]]; //cleanup free_matrix2(Vt); } */ void eigen_symm_2d(double z[], double **V, double **X) { double a = X[0][0]; double b = X[0][1]; double c = X[1][1]; const double epsilon = 1e-16; if (b*b < epsilon * fabs(a*c)) { if (fabs(a) < fabs(c)) { z[0] = a; z[1] = c; V[0][0] = V[1][1] = 1.0; V[0][1] = V[1][0] = 0.0; } else { z[0] = c; z[1] = a; V[0][0] = V[1][1] = 0.0; V[0][1] = V[1][0] = 1.0; } return; } double s = sqrt((a+c)*(a+c) + 4.*(b*b-a*c)); double z1 = (a+c+s)/2.; double z2 = (a+c-s)/2.; if (fabs(z1) < fabs(z2)) { z[0] = z1; z[1] = z2; } else { z[1] = z1; z[0] = z2; } double d0 = hypot(b, z[0]-a); double d1 = hypot(b, z[1]-a); V[0][0] = b/d0; V[0][1] = (z[0]-a)/d0; V[1][0] = b/d1; V[1][1] = (z[1]-a)/d1; } void eigen_symm(double z[], double **V, double **X, int n) { if (n == 2) { eigen_symm_2d(z,V,X); return; } // naive Jacobi method int i, j; double tolerance = 1e-10; double **A = matrix_clone(X,n,n); double **B = new_matrix2(n,n); double **G = new_matrix2(n,n); double **Gt = new_matrix2(n,n); int cnt = 1; //dbug // initialize V = I for (i = 0; i < n; i++) { V[i][i] = 1; for (j = i+1; j < n; j++) V[i][j] = V[j][i] = 0; } //printf("break 1\n"); //dbug while (1) { //dbug //printf("A:\n"); //print_matrix(A, n, n); //printf("\n"); // check for convergence double d_off = 0, d_diag = 0; for (i = 0; i < n; i++) { d_diag += A[i][i]*A[i][i]; for (j = i+1; j < n; j++) d_off = MAX(d_off, fabs(A[i][j])); } d_diag = sqrt(d_diag / (double)n); if (d_off < MAX(tolerance * d_diag, tolerance)) break; //dbug if (cnt++ % 1000 == 0) { printf("d_off = %e, d_diag = %e\n", d_off, d_diag); //dbug if (!isfinite(d_off) || !isfinite(d_diag)) return; } // find largest pivot double pivot = 0; int ip=0, jp=0; for (i = 0; i < n; i++) { for (j = i+1; j < n; j++) { double p = fabs(A[i][j]); if (p > pivot) { pivot = p; ip = i; jp = j; } } } //printf("pivot = %f, ip = %d, jp = %d\n", pivot, ip, jp); //dbug // compute Givens cos, sin double a = (A[jp][jp] - A[ip][ip]) / (2 * A[ip][jp]); double t = 1 / (fabs(a) + sqrt(1 + a*a)); // tan if (a < 0) t = -t; double c = 1 / sqrt(1 + t*t); // cos double s = t*c; // sin //printf("a = %f, t = %f, c = %f, s = %f\n", a, t, c, s); //dbug // compute Givens rotation matrix for (i = 0; i < n; i++) { G[i][i] = 1; for (j = i+1; j < n; j++) G[i][j] = G[j][i] = 0; } G[ip][ip] = G[jp][jp] = c; G[ip][jp] = s; G[jp][ip] = -s; //dbug //printf("givens rotation matrix:\n"); //print_matrix(G, n, n); //printf("\n"); // compute new A transpose(Gt, G, n, n); matrix_mult(B, A, G, n, n, n); // B = A*G matrix_mult(A, Gt, B, n, n, n); // A = Gt*B // compute new V (with eigenvectors in the rows) matrix_mult(B, Gt, V, n, n, n); // B = Gt*V matrix_copy(V, B, n, n); // V = B; } //printf("break 2\n"); //dbug // sort eigenvalues int idx[n]; double z2[n]; for (i = 0; i < n; i++) z[i] = A[i][i]; sort_indices(z, idx, n); if (z[idx[0]] < -tolerance) { // negative eigenvalues --> sort in reverse order reversei(idx, idx, n); //for (i = 0; i < n/2; i++) { // int tmp = idx[i]; // idx[i] = idx[n-i-1]; // idx[n-i-1] = tmp; //} } for (i = 0; i < n; i++) z2[i] = z[idx[i]]; for (i = 0; i < n; i++) z[i] = z2[i]; for (i = 0; i < n; i++) for (j = 0; j < n; j++) B[i][j] = V[idx[i]][j]; matrix_copy(V, B, n, n); free_matrix2(A); free_matrix2(B); free_matrix2(G); free_matrix2(Gt); } // reorder the rows of X, Y = X(idx,:) void reorder_rows(double **Y, double **X, int *idx, int n, int m) { int i; double **Y2 = (X==Y ? new_matrix2(n,m) : Y); for (i = 0; i < n; i++) memcpy(Y2[i], X[idx[i]], m*sizeof(double)); if (X==Y) { matrix_copy(Y, Y2, n, m); free_matrix2(Y2); } } // reorder the rows of X, Y = X(idx,:) void reorder_rowsi(int **Y, int **X, int *idx, int n, int m) { int i; int **Y2 = (X==Y ? new_matrix2i(n,m) : Y); for (i = 0; i < n; i++) memcpy(Y2[i], X[idx[i]], m*sizeof(int)); if (X==Y) { memcpy(Y[0], Y2[0], n*m*sizeof(int)); free_matrix2i(Y2); } } void repmat(double **B, double **A, int rep_n, int rep_m, int n, int m) { int i, rep_i, rep_j; // copy A into top-left corner of B if (A != B) for (i = 0; i < n; ++i) memcpy(B[i], A[i], m * sizeof(double)); // repeat top-left corner to the right for (i = 0; i < n; ++i) for (rep_j = 1; rep_j < rep_m; ++rep_j) memcpy(&B[i][rep_j * m], B[i], m * sizeof(double)); // repeat top of B downwards for (rep_i = 1; rep_i < rep_n; ++rep_i) memcpy(B[rep_i * n], B[0], m * rep_m * n * sizeof(double)); } void repmati(int **B, int **A, int rep_n, int rep_m, int n, int m) { int i, rep_i, rep_j; // copy A into top-left corner of B if (A != B) for (i = 0; i < n; ++i) memcpy(B[i], A[i], m * sizeof(int)); // repeat top-left corner to the right for (i = 0; i < n; ++i) for (rep_j = 1; rep_j < rep_m; ++rep_j) memcpy(&B[i][rep_j * m], B[i], m * sizeof(int)); // repeat top of B downwards for (rep_i = 1; rep_i < rep_n; ++rep_i) memcpy(B[rep_i * n], B[0], m * rep_m * n * sizeof(int)); } /* * blur matrix with a 3x3 gaussian filter with sigma=.5 */ void blur_matrix(double **dst, double **src, int n, int m) { double G[3] = {.6193, .0838, .0113}; double **I = (dst==src ? new_matrix2(n,m) : dst); memcpy(I[0], src[0], n*m*sizeof(double)); int i,j; for (i = 1; i < n-1; i++) for (j = 1; j < m-1; j++) I[i][j] = G[0]*src[i][j] + G[1]*(src[i+1][j] + src[i-1][j] + src[i][j+1] + src[i][j-1]) + G[2]*(src[i+1][j+1] + src[i+1][j-1] + src[i-1][j+1] + src[i-1][j-1]); if (dst==src) { memcpy(dst[0], I[0], n*m*sizeof(double)); free_matrix2(I); } } /* * blur masked matrix with a 3x3 gaussian filter with sigma=.5 */ void blur_matrix_masked(double **dst, double **src, int **mask, int n, int m) { double G[3] = {.6193, .0838, .0113}; double **I = (dst==src ? new_matrix2(n,m) : dst); memcpy(I[0], src[0], n*m*sizeof(double)); int i,j; for (i = 1; i < n-1; i++) { for (j = 1; j < m-1; j++) { double x[9] = {mask[i][j] ? src[i][j] : 0., mask[i+1][j] ? src[i+1][j] : 0., mask[i-1][j] ? src[i-1][j] : 0., mask[i][j+1] ? src[i][j+1] : 0., mask[i][j-1] ? src[i][j-1] : 0., mask[i+1][j+1] ? src[i+1][j+1] : 0., mask[i+1][j-1] ? src[i+1][j-1] : 0., mask[i-1][j+1] ? src[i-1][j+1] : 0., mask[i-1][j-1] ? src[i-1][j-1] : 0.}; double v = G[0]*x[0] + G[1]*(x[1] + x[2] + x[3] + x[4]) + G[2]*(x[5] + x[6] + x[7] + x[8]); int n0 = !!mask[i][j]; int n1 = !!mask[i+1][j] + !!mask[i-1][j] + !!mask[i][j+1] + !!mask[i][j-1]; int n2 = !!mask[i+1][j+1] + !!mask[i-1][j-1] + !!mask[i-1][j+1] + !!mask[i+1][j-1]; double g_tot = n0*G[0] + n1*G[1] + n2*G[2]; I[i][j] = v / g_tot; } } if (dst==src) { memcpy(dst[0], I[0], n*m*sizeof(double)); free_matrix2(I); } } void print_matrix(double **X, int n, int m) { int i, j; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) printf("%f ", X[i][j]); printf("\n"); } } // perform linear regression: dot(b,x[i]) = y[i], i=1..n void linear_regression(double *b, double **X, double *y, int n, int d) { double **Xt = new_matrix2(d,n); transpose(Xt,X,n,d); double **XtX = new_matrix2(d,d); matrix_mult(XtX,Xt,X,d,n,d); double Xty[d]; matrix_vec_mult(Xty,Xt,y,d,n); solve(b, XtX, Xty, d); free_matrix2(Xt); free_matrix2(XtX); } // fit a polynomial: \sum{b[i]*x[j]^i} = y[j], i=1..n, j=1..d void polynomial_regression(double *b, double *x, double *y, int n, int d) { double **X = new_matrix2(n,d); int i, j; for (i = 0; i < n; i++) X[i][0] = 1; for (i = 0; i < n; i++) for (j = 1; j < d; j++) X[i][j] = X[i][j-1]*x[i]; linear_regression(b,X,y,n,d); free_matrix2(X); } /* create a new graph graph_t *graph_new(int num_vertices, int edge_capacity) { int i; graph_t *g = (graph_t *)malloc(sizeof(graph_t)); g->nv = num_vertices; g->vertices = (vertex_t *)calloc(g->nv, sizeof(vertex_t)); for (i = 0; i < g->nv; i++) g->vertices[i].index = i; g->ne = 0; g->_edge_capacity = edge_capacity; g->edges = (edge_t *)calloc(edge_capacity, sizeof(edge_t)); return g; } */ // free a graph void graph_free(graph_t *g) { int i; free(g->edges); for (i = 0; i < g->nv; i++) { free(g->vertices[i].edges); ilist_free(g->vertices[i].neighbors); } free(g); } /* add an edge to a graph void graph_add_edge(graph_t *g, int i, int j) { ilist for if (g->ne == g->_edge_capacity) { g->_edge_capacity *= 2; g->edges = (edge_t *)realloc(g->edges, g->_edge_capacity * sizeof(edge_t)); } g->edges[g->ne].i = i; g->edges[g->ne].j = j; g->ne++; g->vertices[i] } */ // find the index of an edge in a graph int graph_find_edge(graph_t *g, int i, int j) { int k = ilist_find(g->vertices[i].neighbors, j); if (k < 0) return -1; return g->vertices[i].edges[k]; } // smooth the edges of a graph void graph_smooth(double **dst, double **src, graph_t *g, int d, double w) { int i, j; double p[d]; ilist_t *v; if (dst != src) memcpy(dst[0], src[0], d*g->nv*sizeof(double)); for (i = 0; i < g->nv; i++) { memset(p, 0, d * sizeof(double)); // p = 0 for (v = g->vertices[i].neighbors; v; v = v->next) { j = v->x; add(p, p, dst[j], d); // p += dst[j] } mult(p, p, 1/norm(p, d), d); // p = p/norm(p) wavg(dst[i], p, dst[i], w, d); // dst[i] = w*p + (1-w)*dst[i] } } static int dcomp(const void *px, const void *py) { double x = *(double *)px; double y = *(double *)py; if (x == y) return 0; return (x < y ? -1 : 1); } // sample uniformly from a simplex S with n vertices void sample_simplex(double x[], double **S, int n, int d) { int i; // get n-1 uniform samples, u, on [0,1], and sort them double u[n]; for (i = 0; i < n-1; i++) u[i] = frand(); u[n-1] = 1; qsort((void *)u, n-1, sizeof(double), dcomp); // mixing coefficients are the order statistics of u double c[n]; c[0] = u[0]; for (i = 1; i < n; i++) c[i] = u[i] - u[i-1]; // x = sum(c[i]*S[i]) mult(x, S[0], c[0], d); for (i = 1; i < n; i++) { double y[d]; mult(y, S[i], c[i], d); add(x, x, y, d); } } /******************* typedef struct { int nv; int ne; int nf; int *vertices; edge_t *edges; face_t *faces; int *nvn; // # vertex neighbors int *nen; // # edge neighbors int **vertex_neighbors; // vertex -> {vertices} int **vertex_edges; // vertex -> {edges} int **edge_neighbors; // edge -> {vertices} int **edge_faces; // edge -> {faces} // internal vars int _vcap; int _ecap; int _fcap; int *_vncap; int *_encap; } meshgraph_t; ******************/ /* * Create a new meshgraph with initial vertex capacity 'vcap' and degree capacity 'dcap'. */ meshgraph_t *meshgraph_new(int vcap, int dcap) { int i; meshgraph_t *g; safe_calloc(g, 1, meshgraph_t); safe_malloc(g->vertices, vcap, int); safe_malloc(g->edges, vcap, edge_t); safe_malloc(g->faces, vcap, face_t); g->_vcap = g->_ecap = g->_fcap = vcap; safe_malloc(g->_vncap, vcap, int); safe_malloc(g->_encap, vcap, int); safe_malloc(g->vertex_neighbors, vcap, int *); safe_malloc(g->vertex_edges, vcap, int *); safe_calloc(g->nvn, vcap, int); for (i = 0; i < vcap; i++) { safe_malloc(g->vertex_neighbors[i], dcap, int); safe_malloc(g->vertex_edges[i], dcap, int); g->_vncap[i] = dcap; } safe_malloc(g->edge_neighbors, vcap, int *); safe_malloc(g->edge_faces, vcap, int *); safe_calloc(g->nen, vcap, int); for (i = 0; i < vcap; i++) { safe_malloc(g->edge_neighbors[i], dcap, int); safe_malloc(g->edge_faces[i], dcap, int); g->_encap[i] = dcap; } return g; } void meshgraph_free(meshgraph_t *g) { int i; free(g->vertices); free(g->edges); free(g->faces); free(g->nvn); free(g->nen); free(g->_vncap); free(g->_encap); for (i = 0; i < g->nv; i++) { free(g->vertex_neighbors[i]); free(g->vertex_edges[i]); } free(g->vertex_neighbors); free(g->vertex_edges); for (i = 0; i < g->ne; i++) { free(g->edge_neighbors[i]); free(g->edge_faces[i]); } free(g->edge_neighbors); free(g->edge_faces); free(g); } int meshgraph_find_edge(meshgraph_t *g, int i, int j) { int n; for (n = 0; n < g->nvn[i]; n++) if (g->vertex_neighbors[i][n] == j) return g->vertex_edges[i][n]; return -1; } int meshgraph_find_face(meshgraph_t *g, int i, int j, int k) { int e = meshgraph_find_edge(g, i, j); if (e < 0) return -1; int n; for (n = 0; n < g->nen[e]; n++) if (g->edge_neighbors[e][n] == k) return g->edge_faces[e][n]; return -1; } static inline int meshgraph_add_vertex_neighbor(meshgraph_t *g, int i, int vertex, int edge) { int n = g->nvn[i]; if (n == g->_vncap[i]) { g->_vncap[i] *= 2; safe_realloc(g->vertex_neighbors[i], g->_vncap[i], int); safe_realloc(g->vertex_edges[i], g->_vncap[i], int); } g->vertex_neighbors[i][n] = vertex; g->vertex_edges[i][n] = edge; g->nvn[i]++; return n; } int meshgraph_add_edge(meshgraph_t *g, int i, int j) { //printf("meshgraph_add_edge(%d, %d)\n", i, j); int edge = meshgraph_find_edge(g, i, j); if (edge >= 0) return edge; //printf(" break 1\n"); // add the edge if (g->ne == g->_ecap) { int old_ecap = g->_ecap; g->_ecap *= 2; safe_realloc(g->edges, g->_ecap, edge_t); safe_realloc(g->edge_neighbors, g->_ecap, int *); safe_realloc(g->edge_faces, g->_ecap, int *); safe_realloc(g->nen, g->_ecap, int); safe_realloc(g->_encap, g->_ecap, int); //printf(" break 1.1\n"); int e; for (e = old_ecap; e < g->_ecap; e++) { //printf(" e = %d\n", e); g->nen[e] = 0; int dcap = g->_encap[0]; //printf(" dcap = %d\n", dcap); safe_malloc(g->edge_neighbors[e], dcap, int); //printf(" break 1.1.1\n"); safe_malloc(g->edge_faces[e], dcap, int); //printf(" break 1.1.2\n"); g->_encap[e] = dcap; } } //printf(" break 2\n"); edge = g->ne; g->edges[edge].i = i; g->edges[edge].j = j; g->ne++; //printf(" break 3\n"); // add the vertex neighbors meshgraph_add_vertex_neighbor(g, i, j, edge); meshgraph_add_vertex_neighbor(g, j, i, edge); //printf(" break 4\n"); return edge; } static inline int meshgraph_add_edge_neighbor(meshgraph_t *g, int i, int vertex, int face) { int n = g->nen[i]; //printf("g->nen[%d] = %d, g->_encap[%d] = %d\n", i, n, i, g->_encap[i]); if (n == g->_encap[i]) { //printf("n == g->_encap[%d]\n", i); g->_encap[i] *= 2; safe_realloc(g->edge_neighbors[i], g->_encap[i], int); safe_realloc(g->edge_faces[i], g->_encap[i], int); } //printf(" break 1\n"); g->edge_neighbors[i][n] = vertex; //printf(" break 2\n"); g->edge_faces[i][n] = face; //printf(" break 3\n"); g->nen[i]++; return n; } int meshgraph_add_face(meshgraph_t *g, int i, int j, int k) { //printf("meshgraph_add_face(%d, %d, %d)\n", i, j, k); int face = meshgraph_find_face(g, i, j, k); if (face >= 0) return face; //printf(" break 1\n"); // add the edges int edge_ij = meshgraph_add_edge(g, i, j); int edge_ik = meshgraph_add_edge(g, i, k); int edge_jk = meshgraph_add_edge(g, j, k); //printf(" break 2\n"); // add the face //printf("g->nf = %d, g->_fcap = %d\n", g->nf, g->_fcap); if (g->nf == g->_fcap) { g->_fcap *= 2; safe_realloc(g->faces, g->_fcap, face_t); } face = g->nf; g->faces[face].i = i; g->faces[face].j = j; g->faces[face].k = k; g->nf++; //printf(" break 3\n"); // add the edge neighbors meshgraph_add_edge_neighbor(g, edge_ij, k, face); meshgraph_add_edge_neighbor(g, edge_ik, j, face); meshgraph_add_edge_neighbor(g, edge_jk, i, face); //printf(" break 4\n"); return face; } static int _sortable_cmp(const void *x1, const void *x2) { double v1 = ((sortable_t *)x1)->value; double v2 = ((sortable_t *)x2)->value; if (v1 == v2) return 0; if (v1 < v2 || isnan(v1)) return -1; return 1; } // sort an array of weighted data using qsort void sort_data(sortable_t *x, size_t n) { qsort(x, n, sizeof(sortable_t), _sortable_cmp); } // sort the indices of x (leaving x unchanged) void sort_indices(double *x, int *idx, int n) { int i; sortable_t *s; int *xi; safe_malloc(s, n, sortable_t); safe_malloc(xi, n, int); for (i = 0; i < n; i++) { xi[i] = i; s[i].value = x[i]; s[i].data = (void *)(&xi[i]); } sort_data(s, n); for (i = 0; i < n; i++) idx[i] = *(int *)(s[i].data); free(s); free(xi); } /* * fills idx with the indices of the k min entries of x * --> works by maintaining the invariant that idx[0] always has the * largest x value of the min k found so far */ void mink(double *x, int *idx, int n, int k) { int i, j; // initialize idx with 1:k for (i = 0; i < k; i++) idx[i] = i; // maintain invariant for (i = 1; i < k; i++) { if (x[idx[i]] > x[idx[0]]) { int tmp = idx[i]; idx[i] = idx[0]; idx[0] = tmp; } } // process the rest of x for (i = k; i < n; i++) { if (x[i] < x[idx[0]]) { idx[0] = i; // maintain invariant for (j = 1; j < k; j++) { if (x[idx[j]] > x[idx[0]]) { int tmp = idx[j]; idx[j] = idx[0]; idx[0] = tmp; } } } } // sort the min k values double xmink[k]; int idx2[k]; for (i = 0; i < k; i++) xmink[i] = x[idx[i]]; sort_indices(xmink, idx2, k); for (i = 0; i < k; i++) idx2[i] = idx[idx2[i]]; for (i = 0; i < k; i++) idx[i] = idx2[i]; } short double_is_equal(double a, double b) { return fabs(a - b) < 0.00001; } // fast select algorithm int qselect(double *x, int n, int k) { if (n == 1) return 0; double pivot = x[k]; // partition x into y < pivot, z > pivot int i, ny=0, nz=0; for (i = 0; i < n; i++) { if (x[i] < pivot) ny++; else if (x[i] > pivot) nz++; } if (k < ny) { double *y; int *yi; safe_calloc(y, ny, double); safe_calloc(yi, ny, int); ny = 0; for (i = 0; i < n; i++) { if (x[i] < pivot) { yi[ny] = i; y[ny++] = x[i]; } } i = yi[qselect(y, ny, k)]; free(y); free(yi); return i; } else if (k >= n - nz) { double *z; int *zi; safe_calloc(z, nz, double); safe_calloc(zi, nz, int); nz = 0; for (i = 0; i < n; i++) { if (x[i] > pivot) { zi[nz] = i; z[nz++] = x[i]; } } i = zi[qselect(z, nz, k-(n-nz))]; free(z); free(zi); return i; } return k; } static kdtree_t *build_kdtree(double **X, int *xi, int n, int d, int depth) { if (n == 0) return NULL; int i, axis = depth % d; kdtree_t *node; safe_calloc(node, 1, kdtree_t); node->axis = axis; double *x; safe_calloc(x, n, double); for (i = 0; i < n; i++) x[i] = X[i][axis]; int median = qselect(x, n, n/2); // node location node->i = xi[median]; node->d = d; safe_malloc(node->x, d, double); memcpy(node->x, X[median], d*sizeof(double)); // node bbox init: bbox_min = bbox_max = x safe_malloc(node->bbox_min, d, double); safe_malloc(node->bbox_max, d, double); memcpy(node->bbox_min, node->x, d*sizeof(double)); memcpy(node->bbox_max, node->x, d*sizeof(double)); // partition x into y < pivot, z > pivot double pivot = x[median]; int ny=0, nz=0; for (i = 0; i < n; i++) { if (i == median) continue; if (x[i] <= pivot) ny++; else if (x[i] > pivot) nz++; } //printf("n = %d, d = %d, depth = %d, axis = %d --> median = %d, X[median] = (%f, %f, %f), ny = %d, nz = %d\n", // n, d, depth, axis, median, X[median][0], X[median][1], X[median][2], ny, nz); if (ny > 0) { double **Y = new_matrix2(ny, d); int *yi; safe_calloc(yi, ny, int); ny = 0; for (i = 0; i < n; i++) { if (i == median) continue; if (x[i] <= pivot) { yi[ny] = xi[i]; memcpy(Y[ny], X[i], d*sizeof(double)); ny++; } } node->left = build_kdtree(Y, yi, ny, d, depth+1); // update bbox for (i = 0; i < d; i++) { if (node->left->bbox_min[i] < node->bbox_min[i]) node->bbox_min[i] = node->left->bbox_min[i]; if (node->left->bbox_max[i] > node->bbox_max[i]) node->bbox_max[i] = node->left->bbox_max[i]; } free_matrix2(Y); free(yi); } if (nz > 0) { double **Z = new_matrix2(nz, d); int *zi; safe_calloc(zi, nz, int); nz = 0; for (i = 0; i < n; i++) { if (i == median) continue; if (x[i] > pivot) { zi[nz] = xi[i]; memcpy(Z[nz], X[i], d*sizeof(double)); nz++; } } node->right = build_kdtree(Z, zi, nz, d, depth+1); // update bbox for (i = 0; i < d; i++) { if (node->right->bbox_min[i] < node->bbox_min[i]) node->bbox_min[i] = node->right->bbox_min[i]; if (node->right->bbox_max[i] > node->bbox_max[i]) node->bbox_max[i] = node->right->bbox_max[i]; } free_matrix2(Z); free(zi); } free(x); return node; } kdtree_t *kdtree(double **X, int n, int d) { int i, *xi; safe_malloc(xi, n, int); for (i = 0; i < n; i++) xi[i] = i; kdtree_t *tree = build_kdtree(X, xi, n, d, 0); free(xi); return tree; } static kdtree_t *kdtree_NN_node(kdtree_t *tree, double *x, kdtree_t *best) { if (tree == NULL) return best; //printf("node %d", tree->i); int i, d = tree->d; double dbest = (best ? dist(x, best->x, d) : DBL_MAX); // first, check if any node in tree can possibly be better than 'best' if (best) { double y[d]; // closest point on the tree's bbox to x for (i = 0; i < d; i++) { if (x[i] < tree->bbox_min[i]) y[i] = tree->bbox_min[i]; else if (x[i] > tree->bbox_max[i]) y[i] = tree->bbox_max[i]; else y[i] = x[i]; } if (dist(y, x, d) >= dbest) { // 'best' is closer than the closest possible point in tree, so return //printf(" --> pruned!\n"); return best; } } int axis = tree->axis; kdtree_t *nn = best; // compare with the node itself double dtree = dist(x, tree->x, d); //printf(" (%f)", dtree); if (dtree < dbest) { nn = tree; dbest = dtree; //printf(" --> new best"); } //printf("\n"); // compare with the NN in each sub-tree if (x[axis] <= tree->x[axis]) { nn = kdtree_NN_node(tree->left, x, nn); nn = kdtree_NN_node(tree->right, x, nn); } else if (x[axis] > tree->x[axis]) { nn = kdtree_NN_node(tree->right, x, nn); nn = kdtree_NN_node(tree->left, x, nn); } //dbest = dist(x, nn->x, d); //printf(" ... return %d (%f)\n", nn->i, dbest); return nn; } int kdtree_NN(kdtree_t *tree, double *x) { kdtree_t *nn = kdtree_NN_node(tree, x, NULL); return (nn ? nn->i : -1); } void kdtree_free(kdtree_t *tree) { if (tree == NULL) return; kdtree_free(tree->left); kdtree_free(tree->right); free(tree->x); free(tree->bbox_min); free(tree->bbox_max); free(tree); } // RGB to CIELAB color space void rgb2lab(double lab[], double rgb[]) { double R = rgb[0]; double G = rgb[1]; double B = rgb[2]; //if (R > 1.0 || G > 1.0 || B > 1.0) { R /= 255.0; G /= 255.0; B /= 255.0; //} // set a threshold double T = 0.008856; // RGB to XYZ double X = 0.412453*R + 0.357580*G + 0.180423*B; double Y = 0.212671*R + 0.715160*G + 0.072169*B; double Z = 0.019334*R + 0.119193*G + 0.950227*B; // normalize for D65 white point X /= 0.950456; Z /= 1.088754; double X3 = pow(X, 1/3.); double Y3 = pow(Y, 1/3.); double Z3 = pow(Z, 1/3.); double fX = (X>T ? X3 : 7.787*X + 16/116.); double fY = (Y>T ? Y3 : 7.787*Y + 16/116.); double fZ = (Z>T ? Z3 : 7.787*Z + 16/116.); lab[0] = (Y>T ? 116*Y3 - 16.0 : 903.3*Y); lab[1] = 500*(fX - fY); lab[2] = 200*(fY - fZ); } // CIELAB to RGB color space void lab2rgb(double rgb[], double lab[]) { // Thresholds double T1 = 0.008856; double T2 = 0.206893; double L = lab[0]; double a = lab[1]; double b = lab[2]; // Compute Y double fY = pow((L + 16) / 116., 3); int YT = (fY > T1); if (!YT) fY = L / 903.3; double Y = fY; // Alter fY slightly for further calculations fY = (YT ? pow(fY, 1/3.) : 7.787 * fY + 16/116.); // Compute X double fX = a / 500. + fY; int XT = fX > T2; double X = (XT ? pow(fX, 3) : (fX - 16/116.) / 7.787); // Compute Z double fZ = fY - b / 200.; int ZT = fZ > T2; double Z = (ZT ? pow(fZ, 3) : (fZ - 16/116.) / 7.787); // Normalize for D65 white point X = X * 0.950456; Z = Z * 1.088754; // XYZ to RGB double R = 3.240479*X - 1.537150*Y - 0.498535*Z; double G = -0.969256*X + 1.875992*Y + 0.041556*Z; double B = 0.055648*X - 0.204043*Y + 1.057311*Z; rgb[0] = 255*MAX(MIN(R, 1.0), 0.0); rgb[1] = 255*MAX(MIN(G, 1.0), 0.0); rgb[2] = 255*MAX(MIN(B, 1.0), 0.0); }
{ "alphanum_fraction": 0.508167065, "avg_line_length": 20.4678378378, "ext": "c", "hexsha": "f4b775f3cf1ff6f52d0da2df746cf0309c91df7f", "lang": "C", "max_forks_count": 27, "max_forks_repo_forks_event_max_datetime": "2022-03-21T22:05:44.000Z", "max_forks_repo_forks_event_min_datetime": "2015-06-12T18:28:07.000Z", "max_forks_repo_head_hexsha": "a3948cba29bb1288c3ab97141479273d493a139a", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "adamconkey/bingham", "max_forks_repo_path": "c/util.c", "max_issues_count": 11, "max_issues_repo_head_hexsha": "a3948cba29bb1288c3ab97141479273d493a139a", "max_issues_repo_issues_event_max_datetime": "2022-03-27T22:38:55.000Z", "max_issues_repo_issues_event_min_datetime": "2015-06-10T08:13:05.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "adamconkey/bingham", "max_issues_repo_path": "c/util.c", "max_line_length": 838, "max_stars_count": 35, "max_stars_repo_head_hexsha": "a3948cba29bb1288c3ab97141479273d493a139a", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "adamconkey/bingham", "max_stars_repo_path": "c/util.c", "max_stars_repo_stars_event_max_datetime": "2022-02-11T14:19:23.000Z", "max_stars_repo_stars_event_min_datetime": "2015-06-23T02:49:27.000Z", "num_tokens": 30542, "size": 75731 }
/** */ #ifndef _DRZ2PET_UTILS_H #define _DRZ2PET_UTILS_H #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include "aXe_grism.h" #include <math.h> #include <string.h> ap_pixel * make_spc_drztable(observation * const obs, observation * const wobs, const object *ob, const double lambda0, const double dlambda); extern char * get_ID_num(char *grism_image,char *extname); extern void normalize_weight(observation * wobs, object *ob, const int opt_extr); extern gsl_matrix * comp_equ_weight(gsl_matrix *exp_map, const object *ob); gsl_matrix * comp_exp_weight(gsl_matrix *exp_map, const object *ob); gsl_matrix * comp_opt_weight(gsl_matrix *mod_map, gsl_matrix *var_map, const object *ob); #endif /* !_DRZ2PET_UTILS_H */
{ "alphanum_fraction": 0.7016229713, "avg_line_length": 23.5588235294, "ext": "h", "hexsha": "6d5f6d417eb99a3b4d4c9ccd5cb7278842b0e6b8", "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/drz2pet_utils.h", "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/drz2pet_utils.h", "max_line_length": 68, "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/drz2pet_utils.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 207, "size": 801 }
/** * * @file potrf.h * * @copyright 2009-2014 The University of Tennessee and The University of * Tennessee Research Foundation. All rights reserved. * @copyright 2012-2018 Bordeaux INP, CNRS (LaBRI UMR 5800), Inria, * Univ. Bordeaux. All rights reserved. * *** * * @brief Chameleon step2 example header * * @version 1.1.0 * @author Florent Pruvost * @date 2019-02-06 * */ #ifndef _potrf_h_ #define _potrf_h_ /* Common include for all steps of the tutorial */ /* Specific includes for potrf */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <math.h> #include <errno.h> #include <assert.h> #include <stdarg.h> #include <pthread.h> #include <al4san.h> #include "runtime/al4san_runtime.h" #include "control/al4san_descriptor.h" #include <al4san/timer.h> //#include <lapacke.h> #include <mkl.h> #include <sys/time.h> #include <sys/times.h> #if defined( _WIN32 ) || defined( _WIN64 ) #include <windows.h> #else /* Non-Windows */ #include <unistd.h> #include <sys/resource.h> #endif /* Common functions for all steps of the tutorial */ static void get_thread_count(int *thrdnbr) { #if defined WIN32 || defined WIN64 sscanf( getenv( "NUMBER_OF_PROCESSORS" ), "%d", thrdnbr ); #else *thrdnbr = sysconf(_SC_NPROCESSORS_ONLN); #endif } /* define complexity of algorithms - see Lawn 41 page 120 */ #define FMULS_POTRF(__n) ((double)(__n) * (((1. / 6.) * (double)(__n) + 0.5) * (double)(__n) + (1. / 3.))) #define FADDS_POTRF(__n) ((double)(__n) * (((1. / 6.) * (double)(__n) ) * (double)(__n) - (1. / 6.))) #define FMULS_TRSM(__m, __n) (0.5 * (double)(__n) * (double)(__m) * ((double)(__m)+1.)) #define FADDS_TRSM(__m, __n) (0.5 * (double)(__n) * (double)(__m) * ((double)(__m)-1.)) /* Cholesky Task Headers */ void Task_dpotrf( const AL4SAN_option_t *options, al4san_uplo_t uplo, int n, int nb, const AL4SAN_desc_t *A, int Am, int An, int lda, int iinfo ); void Task_dgemm( const AL4SAN_option_t *options, al4san_trans_t transA, al4san_trans_t transB, int m, int n, int k, int nb, double alpha, const AL4SAN_desc_t *A, int Am, int An, int lda, const AL4SAN_desc_t *B, int Bm, int Bn, int ldb, double beta, const AL4SAN_desc_t *C, int Cm, int Cn, int ldc ); void TASK_dplgsy( const AL4SAN_option_t *options, double bump, int m, int n, AL4SAN_desc_t *A, int Am, int An, int lda, int bigM, int m0, int n0, unsigned long long int seed ); void Task_dsyrk( const AL4SAN_option_t *options, al4san_uplo_t uplo, al4san_trans_t trans, int n, int k, int nb, double alpha, const AL4SAN_desc_t *A, int Am, int An, int lda, double beta, const AL4SAN_desc_t *C, int Cm, int Cn, int ldc ); void Task_dtrsm( const AL4SAN_option_t *options, al4san_side_t side, al4san_uplo_t uplo, al4san_trans_t transA, al4san_diag_t diag, int m, int n, int nb, double alpha, const AL4SAN_desc_t *A, int Am, int An, int lda, const AL4SAN_desc_t *B, int Bm, int Bn, int ldb ); void CORE_dplgsy( double bump, int m, int n, double *A, int lda, int bigM, int m0, int n0, unsigned long long int seed ); int dplgsy_Tile( double bump, al4san_uplo_t uplo, AL4SAN_desc_t *A, unsigned long long int seed ); int dplgsy_Tile_Async( double bump, al4san_uplo_t uplo, AL4SAN_desc_t *A, unsigned long long int seed, AL4SAN_sequence_t *sequence, AL4SAN_request_t *request ); void pdplgsy( double bump, al4san_uplo_t uplo, AL4SAN_desc_t *A, unsigned long long int seed, AL4SAN_sequence_t *sequence, AL4SAN_request_t *request ); extern char runtime[20]; /* Integer parameters for step2 */ enum iparam_step2 { IPARAM_THRDNBR, /* Number of cores */ IPARAM_GPUS, /* Number of gpus */ IPARAM_N, /* Number of columns of the matrix */ IPARAM_NRHS, /* Number of RHS */ IPARAM_NB, /* Number of NB */ IPARAM_P, /* Number of P */ IPARAM_Q, /* Number of Q */ /* End */ IPARAM_SIZEOF }; /* Specific routines used in step2.c main program */ /** * Initialize integer parameters */ static void init_iparam(int iparam[IPARAM_SIZEOF]){ iparam[IPARAM_THRDNBR ] = -1; iparam[IPARAM_GPUS ] = -1; iparam[IPARAM_N ] = 500; iparam[IPARAM_NRHS ] = 1; iparam[IPARAM_NB ] = 10; iparam[IPARAM_P ] = 1; iparam[IPARAM_Q ] = 1; } /** * Print how to use the program */ static void show_help(char *prog_name) { printf( "Usage:\n%s [options]\n\n", prog_name ); printf( "Options are:\n" " --help Show this help\n" "\n" " --n=X dimension (N). (default: 500)\n" " --nrhs=X number of RHS. (default: 1)\n" " --nb=X number of RHS. (default: 10)\n" "\n" " --threads=X Number of CPU workers (default: _SC_NPROCESSORS_ONLN)\n" "\n"); } static int startswith(const char *s, const char *prefix) { size_t n = strlen( prefix ); if (strncmp( s, prefix, n )) return 0; return 1; } /** * Read arguments following step2 program call */ static void read_args(int argc, char *argv[], int *iparam){ int i; for (i = 1; i < argc && argv[i]; ++i) { if ( startswith( argv[i], "--help") || startswith( argv[i], "-help") || startswith( argv[i], "--h") || startswith( argv[i], "-h") ) { show_help( argv[0] ); exit(0); } else if (startswith( argv[i], "--n=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%d", &(iparam[IPARAM_N]) ); } else if (startswith( argv[i], "--nrhs=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%d", &(iparam[IPARAM_NRHS]) ); } else if (startswith( argv[i], "--nb=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%d", &(iparam[IPARAM_NB]) ); } else if (startswith( argv[i], "--threads=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%d", &(iparam[IPARAM_THRDNBR]) ); } else if (startswith( argv[i], "--gpus=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%d", &(iparam[IPARAM_GPUS]) ); }else if (startswith( argv[i], "--p=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%d", &(iparam[IPARAM_P]) ); } else if (startswith( argv[i], "--q=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%d", &(iparam[IPARAM_Q]) ); } else if (startswith( argv[i], "--runtime=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%s", runtime); } else { fprintf( stderr, "Unknown option: %s\n", argv[i] ); } } } /** * Print a header message to summarize main parameters */ static void print_header(char *prog_name, int * iparam) { #if defined(CHAMELEON_SIMULATION) double eps = 0.; #else double eps = LAPACKE_dlamch_work( 'e' ); #endif if(AL4SAN_My_Mpi_Rank()==0){ printf( "#\n" "# AL4SAN %d.%d.%d, %s\n" "# Nb threads: %d\n" "# Nb gpus: %d\n" "# Nb Prows: %d\n" "# Nb Qcols: %d\n" "# N: %d\n" "# NB: %d\n" "# eps: %e\n" "# Activated runtime: %s\n" "#\n", AL4SAN_VERSION_MAJOR, AL4SAN_VERSION_MINOR, AL4SAN_VERSION_MICRO, prog_name, iparam[IPARAM_THRDNBR], iparam[IPARAM_GPUS], iparam[IPARAM_P], iparam[IPARAM_Q], iparam[IPARAM_N], iparam[IPARAM_NB], eps, runtime ); printf( "# M N K/NRHS NB seconds Gflop/s\n"); printf( "#%7d %7d %7d %7d ", iparam[IPARAM_N], iparam[IPARAM_N], iparam[IPARAM_NRHS], iparam[IPARAM_NB]); fflush( stdout ); } return; } #endif /* _step2_h_ */
{ "alphanum_fraction": 0.5182348234, "avg_line_length": 35.7020408163, "ext": "h", "hexsha": "e3b99139fa69a27c95dbfb9952e2e56544d6f46b", "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": "93bc603d2b6262439a659ef98908839f678f1c95", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "ecrc/al4san", "max_forks_repo_path": "example/potrf/potrf.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "93bc603d2b6262439a659ef98908839f678f1c95", "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": "ecrc/al4san", "max_issues_repo_path": "example/potrf/potrf.h", "max_line_length": 109, "max_stars_count": 9, "max_stars_repo_head_hexsha": "93bc603d2b6262439a659ef98908839f678f1c95", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "ecrc/al4san", "max_stars_repo_path": "example/potrf/potrf.h", "max_stars_repo_stars_event_max_datetime": "2021-05-12T19:35:26.000Z", "max_stars_repo_stars_event_min_datetime": "2019-02-25T19:18:14.000Z", "num_tokens": 2438, "size": 8747 }
//////////////////////////////////////////////////////////////////////// /// \class OscProb::PMNS_Sterile /// /// \brief Implementation of oscillations of neutrinos in matter in a /// N-neutrino framework. /// /// This class implements neutrino oscillations for any number of /// neutrino falvours. The extra flavours above 3 are treated as /// sterile neutrinos, i.e. it implements a 3+N model. One can also /// run a 2-neutrino model in principle, but an analytical solution /// would be feasible and more efficient in that case. /// /// The eigensystem solution is performed by GSL, which makes it slower /// than the PMNS_Fast class, which only works for 3 neutrinos. /// /// \author coelho\@lal.in2p3.fr //////////////////////////////////////////////////////////////////////// #ifndef PMNS_STERILE_H #define PMNS_STERILE_H #include "PMNS_Base.h" #include <gsl/gsl_eigen.h> namespace OscProb { class PMNS_Sterile : public PMNS_Base { public: PMNS_Sterile(int NumNus); ///< Constructor virtual ~PMNS_Sterile(); ///< Destructor protected: /// Solve the full Hamiltonian for eigenvectors and eigenvalues virtual void SolveHam(); gsl_vector* fEvalGSL; ///< Stores the GSL eigenvalues gsl_matrix_complex* fEvecGSL; ///< Stores the GSL eigenvectors gsl_matrix_complex* H_GSL; ///< The Hamiltonian to be solved by GSL gsl_eigen_hermv_workspace* W_GSL; ///< Allocates memory for GSL solution }; } #endif ////////////////////////////////////////////////////////////////////////
{ "alphanum_fraction": 0.604859335, "avg_line_length": 34, "ext": "h", "hexsha": "1b37cc7116ab26c2f04cdb69420182a7f7ff239d", "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": "25646a568cedc0641febe758023b0e340dc7a108", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "maxjos9/OscProbDecoh", "max_forks_repo_path": "PMNS_Sterile.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "25646a568cedc0641febe758023b0e340dc7a108", "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": "maxjos9/OscProbDecoh", "max_issues_repo_path": "PMNS_Sterile.h", "max_line_length": 78, "max_stars_count": null, "max_stars_repo_head_hexsha": "25646a568cedc0641febe758023b0e340dc7a108", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "maxjos9/OscProbDecoh", "max_stars_repo_path": "PMNS_Sterile.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 361, "size": 1564 }
#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_herk (void) { const double flteps = 1e-4, dbleps = 1e-6; { int order = 101; int uplo = 121; int trans = 111; int N = 2; int K = 1; float alpha = 1.0f; float beta = 1.0f; float A[] = { 0.934f, 0.664f, 0.426f, 0.263f }; int lda = 1; float C[] = { 0.251f, -0.97f, 0.76f, -0.349f, 0.152f, -0.899f, -0.17f, 0.707f }; int ldc = 2; float C_expected[] = { 1.56425f, 0.0f, 1.33252f, -0.311778f, 0.152f, -0.899f, 0.080645f, 0.0f }; cblas_cherk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cherk(case 1606) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cherk(case 1606) imag"); }; }; }; { int order = 102; int uplo = 121; int trans = 111; int N = 2; int K = 1; float alpha = 1.0f; float beta = 1.0f; float A[] = { 0.16f, 0.464f, -0.623f, 0.776f }; int lda = 2; float C[] = { 0.771f, -0.449f, 0.776f, 0.112f, -0.134f, 0.317f, 0.547f, -0.551f }; int ldc = 2; float C_expected[] = { 1.0119f, 0.0f, 0.776f, 0.112f, 0.126384f, -0.096232f, 1.5373f, 0.0f }; cblas_cherk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cherk(case 1607) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cherk(case 1607) imag"); }; }; }; { int order = 101; int uplo = 121; int trans = 113; int N = 2; int K = 1; float alpha = 0.1f; float beta = 1.0f; float A[] = { 0.787f, 0.057f, -0.49f, 0.47f }; int lda = 2; float C[] = { -0.758f, 0.912f, 0.992f, -0.356f, 0.584f, 0.806f, 0.965f, 0.674f }; int ldc = 2; float C_expected[] = { -0.695738f, 0.0f, 0.956116f, -0.316218f, 0.584f, 0.806f, 1.0111f, 0.0f }; cblas_cherk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cherk(case 1608) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cherk(case 1608) imag"); }; }; }; { int order = 102; int uplo = 121; int trans = 113; int N = 2; int K = 1; float alpha = 0.1f; float beta = 1.0f; float A[] = { 0.961f, -0.384f, 0.165f, 0.395f }; int lda = 1; float C[] = { -0.186f, 0.404f, -0.873f, 0.09f, -0.451f, -0.972f, -0.203f, -0.304f }; int ldc = 2; float C_expected[] = { -0.0789023f, 0.0f, -0.873f, 0.09f, -0.450312f, -0.927704f, -0.184675f, 0.0f }; cblas_cherk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cherk(case 1609) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cherk(case 1609) imag"); }; }; }; { int order = 101; int uplo = 122; int trans = 111; int N = 2; int K = 1; float alpha = 0.0f; float beta = -0.3f; float A[] = { 0.04f, 0.608f, 0.21f, -0.44f }; int lda = 1; float C[] = { 0.285f, -0.943f, 0.581f, -0.56f, 0.112f, 0.529f, 0.16f, -0.913f }; int ldc = 2; float C_expected[] = { -0.0855f, 0.0f, 0.581f, -0.56f, -0.0336f, -0.1587f, -0.048f, 0.0f }; cblas_cherk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cherk(case 1610) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cherk(case 1610) imag"); }; }; }; { int order = 102; int uplo = 122; int trans = 111; int N = 2; int K = 1; float alpha = 0.0f; float beta = -0.3f; float A[] = { -0.984f, -0.398f, -0.379f, 0.919f }; int lda = 2; float C[] = { -0.44f, -0.087f, 0.156f, -0.945f, -0.943f, -0.355f, 0.577f, 0.053f }; int ldc = 2; float C_expected[] = { 0.132f, 0.0f, -0.0468f, 0.2835f, -0.943f, -0.355f, -0.1731f, 0.0f }; cblas_cherk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cherk(case 1611) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cherk(case 1611) imag"); }; }; }; { int order = 101; int uplo = 122; int trans = 113; int N = 2; int K = 1; float alpha = 1.0f; float beta = -1.0f; float A[] = { 0.269f, -0.428f, -0.029f, 0.964f }; int lda = 2; float C[] = { 0.473f, -0.932f, -0.689f, -0.072f, -0.952f, -0.862f, 0.001f, 0.282f }; int ldc = 2; float C_expected[] = { -0.217455f, 0.0f, -0.689f, -0.072f, 0.531607f, 0.615096f, 0.929137f, 0.0f }; cblas_cherk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cherk(case 1612) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cherk(case 1612) imag"); }; }; }; { int order = 102; int uplo = 122; int trans = 113; int N = 2; int K = 1; float alpha = 1.0f; float beta = -1.0f; float A[] = { -0.303f, -0.037f, -0.411f, -0.243f }; int lda = 1; float C[] = { 0.652f, -0.227f, -0.849f, 0.87f, -0.051f, -0.535f, 0.418f, -0.681f }; int ldc = 2; float C_expected[] = { -0.558822f, 0.0f, 0.982524f, -0.928422f, -0.051f, -0.535f, -0.19003f, 0.0f }; cblas_cherk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cherk(case 1613) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cherk(case 1613) imag"); }; }; }; { int order = 101; int uplo = 121; int trans = 111; int N = 2; int K = 1; double alpha = 0.1; double beta = 1; double A[] = { -0.384, -0.851, 0.518, 0.492 }; int lda = 1; double C[] = { -0.117, -0.194, -0.915, 0.069, 0.445, 0.089, 0.213, -0.889 }; int ldc = 2; double C_expected[] = { -0.0298343, 0.0, -0.9767604, 0.043811, 0.445, 0.089, 0.2640388, 0.0 }; cblas_zherk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zherk(case 1614) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zherk(case 1614) imag"); }; }; }; { int order = 102; int uplo = 121; int trans = 111; int N = 2; int K = 1; double alpha = 0.1; double beta = 1; double A[] = { 0.13, 0.236, 0.788, 0.629 }; int lda = 2; double C[] = { 0.021, -0.376, -0.804, 0.689, -0.912, 0.21, -0.581, 0.406 }; int ldc = 2; double C_expected[] = { 0.0282596, 0.0, -0.804, 0.689, -0.8869116, 0.2204198, -0.4793415, 0.0 }; cblas_zherk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zherk(case 1615) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zherk(case 1615) imag"); }; }; }; { int order = 101; int uplo = 121; int trans = 113; int N = 2; int K = 1; double alpha = 0; double beta = 1; double A[] = { 0.593, 0.846, -0.144, 0.128 }; int lda = 2; double C[] = { 0.02, 0.313, 0.222, 0.301, 0.412, -0.645, -0.411, -0.02 }; int ldc = 2; double C_expected[] = { 0.02, 0.313, 0.222, 0.301, 0.412, -0.645, -0.411, -0.02 }; cblas_zherk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zherk(case 1616) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zherk(case 1616) imag"); }; }; }; { int order = 102; int uplo = 121; int trans = 113; int N = 2; int K = 1; double alpha = 0; double beta = 1; double A[] = { 0.857, 0.994, -0.933, 0.069 }; int lda = 1; double C[] = { 0.253, -0.521, 0.937, -0.73, 0.24, 0.177, -0.27, -0.225 }; int ldc = 2; double C_expected[] = { 0.253, -0.521, 0.937, -0.73, 0.24, 0.177, -0.27, -0.225 }; cblas_zherk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zherk(case 1617) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zherk(case 1617) imag"); }; }; }; { int order = 101; int uplo = 122; int trans = 111; int N = 2; int K = 1; double alpha = 0; double beta = 1; double A[] = { -0.343, -0.433, -0.381, -0.087 }; int lda = 1; double C[] = { -0.695, 0.911, 0.719, -0.074, -0.621, -0.256, 0.216, -0.889 }; int ldc = 2; double C_expected[] = { -0.695, 0.911, 0.719, -0.074, -0.621, -0.256, 0.216, -0.889 }; cblas_zherk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zherk(case 1618) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zherk(case 1618) imag"); }; }; }; { int order = 102; int uplo = 122; int trans = 111; int N = 2; int K = 1; double alpha = 0; double beta = 1; double A[] = { -0.887, 0.557, -0.43, 0.912 }; int lda = 2; double C[] = { -0.083, 0.219, 0.417, 0.817, -0.294, -0.683, -0.633, 0.831 }; int ldc = 2; double C_expected[] = { -0.083, 0.219, 0.417, 0.817, -0.294, -0.683, -0.633, 0.831 }; cblas_zherk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zherk(case 1619) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zherk(case 1619) imag"); }; }; }; { int order = 101; int uplo = 122; int trans = 113; int N = 2; int K = 1; double alpha = -0.3; double beta = -1; double A[] = { -0.531, 0.187, -0.777, -0.329 }; int lda = 2; double C[] = { -0.173, 0.833, 0.155, -0.52, -0.99, 0.28, 0.455, 0.481 }; int ldc = 2; double C_expected[] = { 0.077921, 0.0, 0.155, -0.52, 0.8846808, -0.1840006, -0.668591, 0.0 }; cblas_zherk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zherk(case 1620) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zherk(case 1620) imag"); }; }; }; { int order = 102; int uplo = 122; int trans = 113; int N = 2; int K = 1; double alpha = -0.3; double beta = -1; double A[] = { -0.287, 0.068, 0.917, -0.449 }; int lda = 1; double C[] = { -0.248, -0.608, -0.124, -0.718, -0.037, -0.115, 0.998, -0.551 }; int ldc = 2; double C_expected[] = { 0.2219021, 0.0, 0.2121133, 0.7379521, -0.037, -0.115, -1.310747, 0.0 }; cblas_zherk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zherk(case 1621) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zherk(case 1621) imag"); }; }; }; }
{ "alphanum_fraction": 0.5181474646, "avg_line_length": 28.7348484848, "ext": "c", "hexsha": "7dbe7f436cc4685b425c2425fb002343b60af19a", "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_herk.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_herk.c", "max_line_length": 104, "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_herk.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": 5221, "size": 11379 }
/* * SpanDSP - a series of DSP components for telephony * * make_line_models.c * * Written by Steve Underwood <steveu@coppice.org> * * Copyright (C) 2004 Steve Underwood * * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, as * published by the Free Software Foundation. * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ /*! \page make_line_models_page Telephony line model construction \section make_line_models_page_sec_1 What does it do? ???. \section make_line_models_page_sec_2 How does it work? ???. */ #if defined(HAVE_CONFIG_H) #include "config.h" #endif #include <stdlib.h> #include <unistd.h> #include <inttypes.h> #include <string.h> #include <stdio.h> #if defined(HAVE_FFTW3_H) #include <fftw3.h> #else #include <fftw.h> #endif #include <math.h> #if defined(HAVE_STDBOOL_H) #include <stdbool.h> #else #include "spandsp/stdbool.h" #endif #include "spandsp.h" #if !defined(M_PI) # define M_PI 3.14159265358979323846 /* pi */ #endif #define LINE_MODEL_FILE_NAME "line_models.c" #define SAMPLE_RATE 8000 #define LINE_FILTER_SIZE 129 #define FFT_SIZE 1024 /* Tabulated medium range telephone line response (from p 537, Digital Communication, John G. Proakis */ /* amp 1.0 -> 2.15, freq = 3000 Hz -> 3.2, by 0.2 increments delay = 4 ms -> 2.2 */ struct { int frequency; float amp; float delay; } proakis[] = { { 0, 0.00, 4.80}, { 200, 0.90, 3.50}, { 400, 1.40, 2.20}, { 600, 1.80, 0.90}, { 800, 2.00, 0.50}, {1000, 2.10, 0.25}, {1200, 2.30, 0.10}, {1400, 2.30, 0.05}, {1600, 2.20, 0.00}, {1800, 2.10, 0.00}, {2000, 2.00, 0.00}, {2200, 1.85, 0.05}, {2400, 1.75, 0.10}, {2600, 1.55, 0.20}, {2800, 1.30, 0.40}, {3000, 1.10, 0.50}, {3200, 0.80, 0.90}, {3400, 0.55, 1.20}, {3600, 0.25, 2.20}, {3800, 0.05, 3.20}, {4000, 0.05, 4.20}, {4200, 0.05, 5.20} }; #define CPE_TO_CO_ATTENUATION 0 /* In dB */ #define CPE_TO_CO_DELAY 1 /* In us */ #define CPE_TO_CO_IMPEDANCE 2 /* In ohms */ #define CPE_TO_CO_PHASE 3 /* In degrees */ #define CO_TO_CPE_IMPEDANCE 4 /* In ohms */ #define CO_TO_CPE_PHASE 5 /* In degrees */ #define CO_TO_CPE_ATTENUATION 6 /* In dB */ #define CO_TO_CPE_DELAY 7 /* In us */ /* Terms used, for V.56bis: AD = attenuation distortion EDD = envelope delay distortion */ /* V.56bis EIA LL-1, non-loaded loop */ struct { int freq; float ad[8]; } eia_ll1[] = { { 200, {0.0, 0.4, 767, -1.4, 767, -1.4, 0.0, 0.4}}, { 300, {0.0, 0.7, 766, -2.0, 766, -2.0, 0.0, 0.7}}, { 400, {0.0, 0.5, 763, -2.8, 763, -2.8, 0.0, 0.5}}, { 500, {0.0, 0.6, 765, -3.4, 765, -3.4, 0.0, 0.6}}, { 600, {0.0, 0.2, 764, -4.1, 764, -4.1, 0.0, 0.2}}, { 700, {0.0, 0.4, 764, -4.7, 764, -4.7, 0.0, 0.4}}, { 800, {0.0, 0.4, 762, -5.4, 762, -5.4, 0.0, 0.4}}, { 900, {0.0, 0.2, 762, -6.0, 762, -6.0, 0.0, 0.2}}, {1000, {1.2, 0.5, 761, -6.7, 761, -6.7, 1.2, 0.5}}, {1100, {0.0, 0.6, 759, -7.4, 759, -7.4, 0.0, 0.6}}, {1200, {0.0, 0.4, 757, -8.1, 757, -8.1, 0.0, 0.4}}, {1300, {0.0, 0.1, 757, -8.6, 757, -8.6, 0.0, 0.1}}, {1400, {0.0, 0.3, 755, -9.3, 755, -9.3, 0.0, 0.3}}, {1500, {0.0, 0.4, 753, -10.0, 753, -10.0, 0.0, 0.4}}, {1600, {0.0, 0.3, 751, -10.7, 751, -10.7, 0.0, 0.3}}, {1700, {0.0, 0.1, 748, -11.3, 748, -11.3, 0.0, 0.1}}, {1800, {0.0, 11.0, 748, -11.9, 748, -11.9, 0.0, 11.0}}, {1900, {0.1, 0.1, 745, -12.5, 745, -12.5, 0.1, 0.1}}, {2000, {0.1, 0.3, 743, -13.9, 743, -13.9, 0.1, 0.3}}, {2100, {0.1, 0.3, 740, -13.9, 740, -13.9, 0.1, 0.3}}, {2200, {0.1, 0.3, 737, -14.5, 737, -14.5, 0.1, 0.3}}, {2300, {0.1, 0.3, 734, -15.2, 734, -15.2, 0.1, 0.3}}, {2400, {0.1, 0.2, 731, -15.8, 731, -15.8, 0.1, 0.2}}, {2500, {0.1, 0.0, 728, -16.4, 728, -16.4, 0.1, 0.0}}, {2600, {0.1, 0.0, 729, -16.8, 729, -16.8, 0.1, 0.0}}, {2700, {0.2, 0.1, 726, -17.4, 726, -17.4, 0.2, 0.1}}, {2800, {0.2, 0.2, 722, -18.0, 722, -18.0, 0.2, 0.2}}, {2900, {0.2, 0.3, 719, -18.6, 719, -18.6, 0.2, 0.3}}, {3000, {0.2, 0.4, 715, -19.3, 715, -19.3, 0.2, 0.4}}, {3100, {0.2, 0.4, 712, -19.9, 712, -19.9, 0.2, 0.4}}, {3200, {0.2, 0.5, 708, -20.5, 708, -20.5, 0.2, 0.5}}, {3300, {0.2, 0.5, 704, -21.1, 704, -21.1, 0.2, 0.5}}, {3400, {0.2, 0.5, 700, -21.7, 700, -21.7, 0.2, 0.5}}, {3500, {0.2, 0.5, 696, -22.3, 696, -22.3, 0.2, 0.5}}, {3600, {0.2, 0.4, 692, -22.9, 692, -22.9, 0.2, 0.4}}, {3700, {0.2, 0.3, 688, -23.5, 688, -23.5, 0.2, 0.3}}, {3800, {0.2, 0.2, 684, -24.1, 684, -24.1, 0.2, 0.2}}, {3900, {0.2, 0.1, 680, -24.7, 680, -24.7, 0.2, 0.1}}, {4000, {0.2, -0.1, 676, -25.2, 676, -25.2, 0.2, -0.1}} }; /* V.56bis EIA LL-2, non-loaded loop */ struct { int freq; float ad[8]; } eia_ll2[] = { { 200, {-0.2, 6.6, 1086, -4.9, 1085, -5.6, -0.2, 6.6}}, { 300, {-0.2, 7.7, 1079, -7.3, 1077, -8.3, -0.2, 7.7}}, { 400, {-0.2, 6.7, 1062, -9.9, 1058, -11.2, -0.2, 6.7}}, { 500, {-0.2, 7.1, 1059, -12.0, 1053, -13.6, -0.2, 7.1}}, { 600, {-0.1, 5.2, 1041, -14.4, 1034, -16.3, -0.1, 5.2}}, { 700, {-0.1, 5.8, 1030, -16.5, 1020, -18.6, -0.1, 5.8}}, { 800, {-0.1, 5.4, 1010, -18.7, 998, -21.0, -0.1, 5.4}}, { 900, { 0.0, 4.5, 997, -20.5, 982, -23.1, 0.0, 4.5}}, {1000, { 3.2, 5.1, 976, -22.5, 959, -25.3, 3.2, 5.1}}, {1100, { 0.1, 5.0, 954, -24.5, 934, -27.4, 0.1, 5.0}}, {1200, { 0.1, 4.0, 931, -26.2, 909, -29.4, 0.1, 4.0}}, {1300, { 0.2, 2.7, 918, -27.6, 894, -30.9, 0.2, 2.7}}, {1400, { 0.2, 2.8, 897, -29.2, 871, -32.6, 0.2, 2.8}}, {1500, { 0.3, 2.6, 874, -30.7, 847, -34.3, 0.3, 2.6}}, {1600, { 0.3, 2.0, 852, -32.1, 823, -35.8, 0.3, 2.0}}, {1700, { 0.4, 0.9, 831, -33.4, 800, -37.2, 0.4, 0.9}}, {1800, { 0.5, 40.8, 816, -34.4, 783, -38.4, 0.5, 40.8}}, {1900, { 0.6, 0.0, 796, -35.6, 762, -39.6, 0.6, 0.0}}, {2000, { 0.6, -0.2, 776, -36.6, 741, -40.7, 0.6, -0.2}}, {2100, { 0.7, -0.6, 756, -37.6, 720, -41.8, 0.7, -0.6}}, {2200, { 0.8, -1.1, 737, -38.6, 700, -42.9, 0.8, -1.1}}, {2300, { 0.9, -1.8, 719, -39.4, 681, -43.8, 0.9, -1.8}}, {2400, { 1.0, -2.6, 701, -40.2, 663, -44.7, 1.0, -2.6}}, {2500, { 1.0, -3.7, 684, -41.0, 646, -45.5, 1.0, -3.7}}, {2600, { 1.1, -4.1, 678, -41.3, 639, -45.9, 1.1, -4.1}}, {2700, { 1.2, -4.3, 663, -42.0, 623, -46.6, 1.2, -4.3}}, {2800, { 1.3, -4.5, 647, -42.6, 607, -47.3, 1.3, -4.5}}, {2900, { 1.4, -4.8, 632, -43.1, 591, -47.9, 1.4, -4.8}}, {3000, { 1.5, -5.2, 617, -43.6, 576, -48.4, 1.5, -5.2}}, {3100, { 1.6, -5.6, 603, -44.1, 562, -49.0, 1.6, -5.6}}, {3200, { 1.7, -6.0, 589, -44.5, 548, -49.5, 1.7, -6.0}}, {3300, { 1.8, -6.5, 576, -44.9, 535, -49.9, 1.8, -6.5}}, {3400, { 1.9, -7.1, 563, -45.3, 522, -50.3, 1.9, -7.1}}, {3500, { 2.0, -7.7, 551, -45.6, 509, -50.7, 2.0, -7.7}}, {3600, { 2.1, -8.4, 539, -45.9, 498, -51.0, 2.1, -8.4}}, {3700, { 2.2, -9.1, 528, -46.2, 486, -51.3, 2.2, -9.1}}, {3800, { 2.3, -9.9, 518, -46.4, 476, -51.6, 2.3, -9.9}}, {3900, { 2.4, -10.6, 507, -46.6, 466, -51.9, 2.4, -10.6}}, {4000, { 2.5, -11.5, 498, -46.8, 456, -52.1, 2.5, -11.5}} }; /* V.56bis EIA LL-3, non-loaded loop */ struct { int freq; float ad[8]; } eia_ll3[] = { { 200, {-0.3, 10.5, 1176, -5.9, 1173, -7.4, -0.3, 10.5}}, { 300, {-0.3, 11.5, 1165, -8.8, 1159, -11.0, -0.3, 11.5}}, { 400, {-0.3, 10.6, 1140, -11.8, 1130, -14.7, -0.3, 10.6}}, { 500, {-0.3, 11.0, 1133, -14.3, 1117, -17.8, -0.3, 11.0}}, { 600, {-0.2, 8.5, 1108, -17.1, 1086, -21.2, -0.2, 8.5}}, { 700, {-0.2, 8.5, 1090, -19.4, 1062, -24.0, -0.2, 8.5}}, { 800, {-0.1, 8.4, 1062, -21.9, 1029, -27.0, -0.1, 8.4}}, { 900, { 0.0, 7.1, 1042, -23.9, 1003, -29.4, 0.0, 7.1}}, {1000, { 3.8, 7.7, 1013, -23.0, 969, -31.9, 3.8, 7.7}}, {1100, { 0.1, 7.4, 982, -28.1, 934, -34.3, 0.1, 7.4}}, {1200, { 0.1, 6.0, 953, -29.9, 900, -36.5, 0.1, 6.0}}, {1300, { 0.2, 4.2, 935, -31.3, 878, -38.1, 0.2, 4.2}}, {1400, { 0.3, 4.2, 907, -32.8, 847, -40.0, 0.3, 4.2}}, {1500, { 0.4, 3.7, 880, -34.3, 817, -41.7, 0.4, 3.7}}, {1600, { 0.5, 2.7, 853, -35.6, 787, -43.2, 0.5, 2.7}}, {1700, { 0.6, 1.2, 827, -36.8, 760, -44.6, 0.6, 1.2}}, {1800, { 0.7, 48.7, 809, -37.8, 739, -45.8, 0.7, 48.7}}, {1900, { 0.8, -0.2, 785, -38.8, 715, -47.0, 0.8, -0.2}}, {2000, { 0.9, -0.7, 763, -39.7, 691, -48.0, 0.9, -0.7}}, {2100, { 1.0, -1.3, 741, -40.5, 668, -49.1, 1.0, -1.3}}, {2200, { 1.1, -2.1, 719, -41.3, 647, -50.0, 1.1, -2.1}}, {2300, { 1.2, -2.1, 699, -42.0, 625, -50.8, 1.2, -2.1}}, {2400, { 1.2, -4.3, 680, -42.6, 606, -51.6, 1.2, -4.3}}, {2500, { 1.3, -5.6, 663, -43.2, 588, -52.3, 1.3, -5.6}}, {2600, { 1.6, -6.2, 656, -43.4, 581, -52.7, 1.6, -6.2}}, {2700, { 1.7, -6.6, 640, -43.9, 564, -53.3, 1.7, -6.6}}, {2800, { 1.8, -7.0, 624, -44.3, 548, -53.9, 1.8, -7.0}}, {2900, { 1.9, -7.5, 609, -44.7, 533, -54.4, 1.9, -7.5}}, {3000, { 2.0, -8.0, 594, -45.0, 518, -54.8, 2.0, -8.0}}, {3100, { 2.2, -8.6, 580, -45.3, 504, -55.3, 2.2, -8.6}}, {3200, { 2.3, -9.2, 566, -45.6, 490, -55.7, 2.3, -9.2}}, {3300, { 2.4, -9.9, 553, -45.8, 477, -56.0, 2.4, -9.9}}, {3400, { 2.6, -10.7, 540, -46.0, 465, -56.3, 2.6, -10.7}}, {3500, { 2.7, -11.4, 529, -46.2, 454, -56.6, 2.7, -11.4}}, {3600, { 2.8, -12.3, 517, -46.3, 443, -56.9, 2.8, -12.3}}, {3700, { 3.0, -13.1, 507, -46.4, 432, -57.1, 3.0, -13.1}}, {3800, { 3.1, -14.0, 497, -46.5, 422, -57.3, 3.1, -14.0}}, {3900, { 3.2, -14.9, 487, -46.6, 413, -57.5, 3.2, -14.9}}, {4000, { 3.3, -15.9, 478, -46.6, 404, -57.7, 3.3, -15.9}} }; /* V.56bis EIA LL-4, non-loaded loop */ struct { int freq; float ad[8]; } eia_ll4[] = { { 200, {-0.8, 31.0, 1564, -10.7, 1564, -10.7, -0.8, 31.0}}, { 300, {-0.8, 32.6, 1520, -15.6, 1520, -15.6, -0.8, 32.6}}, { 400, {-0.8, 29.8, 1447, -20.5, 1447, -20.5, -0.8, 29.8}}, { 500, {-0.6, 29.7, 1402, -24.3, 1402, -24.3, -0.6, 29.7}}, { 600, {-0.5, 24.9, 1328, -28.1, 1328, -28.1, -0.5, 24.9}}, { 700, {-0.4, 24.8, 1270, -31.2, 1270, -31.2, -0.4, 24.8}}, { 800, {-0.3, 22.7, 1200, -34.0, 1200, -34.0, -0.3, 22.7}}, { 900, {-0.1, 19.8, 1148, -36.2, 1148, -36.2, -0.1, 19.8}}, {1000, { 6.1, 19.3, 1086, -38.3, 1086, -38.3, 6.1, 19.3}}, {1100, { 0.1, 17.5, 1027, -40.1, 1027, -40.1, 0.1, 17.5}}, {1200, { 0.3, 14.3, 974, -41.6, 974, -41.6, 0.3, 14.3}}, {1300, { 0.5, 10.9, 941, -42.6, 941, -42.6, 0.5, 10.9}}, {1400, { 0.7, 9.6, 897, -43.7, 897, -43.7, 0.7, 9.6}}, {1500, { 0.9, 7.7, 856, -44.6, 856, -44.6, 0.9, 7.7}}, {1600, { 1.1, 5.3, 818, -45.3, 818, -45.3, 1.1, 5.3}}, {1700, { 1.3, 2.4, 784, -45.9, 784, -45.9, 1.3, 2.4}}, {1800, { 1.4, 69.1, 761, -46.3, 761, -46.3, 1.4, 69.1}}, {1900, { 1.7, -1.3, 732, -46.6, 732, -46.6, 1.7, -1.3}}, {2000, { 1.9, -2.7, 706, -46.9, 706, -46.9, 1.9, -2.7}}, {2100, { 2.1, -4.3, 682, -47.1, 682, -47.1, 2.1, -4.3}}, {2200, { 2.3, -6.0, 659, -47.3, 659, -47.3, 2.3, -6.0}}, {2300, { 2.5, -7.9, 638, -47.4, 638, -47.4, 2.5, -7.9}}, {2400, { 2.7, -9.9, 619, -47.4, 619, -47.4, 2.7, -9.9}}, {2500, { 2.9, -12.0, 602, -47.5, 602, -47.5, 2.9, -12.0}}, {2600, { 3.1, -13.0, 596, -47.4, 596, -47.4, 3.1, -13.0}}, {2700, { 3.3, -13.9, 580, -47.4, 580, -47.4, 3.3, -13.9}}, {2800, { 3.5, -14.8, 566, -47.3, 566, -47.3, 3.5, -14.8}}, {2900, { 3.7, -15.7, 552, -47.2, 552, -47.2, 3.7, -15.7}}, {3000, { 3.9, -16.7, 539, -47.1, 539, -47.1, 3.9, -16.7}}, {3100, { 4.1, -17.7, 526, -47.0, 526, -47.0, 4.1, -17.7}}, {3200, { 4.3, -18.7, 515, -46.8, 515, -46.8, 4.3, -18.7}}, {3300, { 4.5, -19.8, 504, -46.7, 504, -46.7, 4.5, -19.8}}, {3400, { 4.7, -20.8, 493, -46.5, 493, -46.5, 4.7, -20.8}}, {3500, { 4.9, -21.8, 484, -46.4, 484, -46.4, 4.9, -21.8}}, {3600, { 5.1, -22.9, 475, -46.2, 475, -46.2, 5.1, -22.9}}, {3700, { 5.3, -23.9, 466, -46.0, 466, -46.0, 5.3, -23.9}}, {3800, { 5.5, -25.0, 458, -45.9, 458, -45.9, 5.5, -25.0}}, {3900, { 5.6, -26.1, 451, -45.7, 451, -45.7, 5.6, -26.1}}, {4000, { 5.8, -27.2, 444, -45.5, 444, -45.5, 5.8, -27.2}} }; /* V.56bis EIA LL-5, non-loaded loop */ struct { int freq; float ad[8]; } eia_ll5[] = { { 200, {-1.4, 55.8, 1607, -12.7, 1574, -17.4, -1.4, 55.8}}, { 300, {-1.3, 57.2, 1541, -18.3, 1478, -24.8, -1.3, 57.2}}, { 400, {-1.2, 52.2, 1443, -23.6, 1350, -31.5, -1.2, 52.2}}, { 500, {-1.0, 51.0, 1379, -27.5, 1261, -36.4, -1.0, 51.0}}, { 600, {-0.9, 43.2, 1287, -31.2, 1150, -40.7, -0.9, 43.2}}, { 700, {-0.7, 41.8, 1216, -34.0, 1066, -44.0, -0.7, 41.8}}, { 800, {-0.5, 37.4, 1137, -36.5, 979, -46.9, -0.5, 37.4}}, { 900, {-0.2, 32.4, 1080, -38.3, 915, -48.9, -0.2, 32.4}}, {1000, { 7.0, 30.5, 1015, -39.8, 848, -50.7, 7.0, 30.5}}, {1100, { 0.3, 26.8, 956, -41.1, 788, -52.2, 0.3, 26.8}}, {1200, { 0.5, 21.5, 904, -42.1, 736, -53.3, 0.5, 21.5}}, {1300, { 0.8, 16.6, 873, -42.7, 703, -54.1, 0.8, 16.6}}, {1400, { 1.0, 14.1, 832, -43.2, 663, -54.8, 1.0, 14.1}}, {1500, { 1.3, 10.9, 795, -43.7, 627, -55.3, 1.3, 10.9}}, {1600, { 1.6, 7.3, 762, -44.0, 595, -55.7, 1.6, 7.3}}, {1700, { 1.9, 3.2, 733, -44.2, 567, -56.0, 1.9, 3.2}}, {1800, { 2.2, 81.5, 713, -44.3, 547, -56.2, 2.2, 81.5}}, {1900, { 2.4, -1.9, 689, -44.4, 524, -56.4, 2.4, -1.9}}, {2000, { 2.7, -3.9, 667, -44.4, 503, -56.5, 2.7, -3.9}}, {2100, { 3.0, -6.1, 646, -44.4, 485, -56.5, 3.0, -6.1}}, {2200, { 3.3, -8.3, 628, -44.4, 466, -56.5, 3.3, -8.3}}, {2300, { 3.6, -10.7, 610, -44.3, 450, -56.5, 3.6, -10.7}}, {2400, { 3.8, -13.1, 595, -44.2, 436, -56.4, 3.8, -13.1}}, {2500, { 4.1, -15.5, 581, -44.1, 422, -56.3, 4.1, -15.5}}, {2600, { 4.3, -16.7, 577, -44.0, 417, -56.2, 4.3, -16.7}}, {2700, { 4.6, -17.7, 565, -43.9, 406, -56.1, 4.6, -17.7}}, {2800, { 4.8, -18.8, 553, -43.8, 395, -56.0, 4.8, -18.8}}, {2900, { 5.1, -19.9, 542, -43.7, 395, -55.9, 5.1, -19.9}}, {3000, { 5.4, -21.0, 531, -43.6, 375, -55.7, 5.4, -21.0}}, {3100, { 5.6, -22.1, 521, -43.5, 366, -55.6, 5.6, -22.1}}, {3200, { 5.9, -23.2, 511, -43.4, 357, -55.4, 5.9, -23.2}}, {3300, { 6.1, -24.3, 502, -43.3, 349, -55.3, 6.1, -24.3}}, {3400, { 6.4, -25.4, 494, -43.2, 341, -55.1, 6.4, -25.4}}, {3500, { 6.6, -26.5, 486, -43.1, 334, -55.0, 6.6, -26.5}}, {3600, { 6.9, -27.6, 478, -43.0, 327, -54.8, 6.9, -27.6}}, {3700, { 7.1, -28.7, 471, -42.9, 321, -54.7, 7.1, -28.7}}, {3800, { 7.3, -29.9, 464, -42.8, 315, -54.6, 7.3, -29.9}}, {3900, { 7.5, -31.0, 458, -42.7, 310, -54.4, 7.5, -31.0}}, {4000, { 7.8, -32.1, 452, -42.7, 304, -54.3, 7.8, -32.1}} }; /* V.56bis EIA LL-6, non-loaded loop */ struct { int freq; float ad[8]; } eia_ll6[] = { { 200, {-0.2, -39.3, 1756, -12.0, 1748, -19.8, -0.2, -39.3}}, { 300, {-0.2, -31.7, 1642, -15.9, 1689, -26.9, -0.2, -31.7}}, { 400, {-0.2, -37.5, 1506, -18.4, 1427, -33.4, -0.2, -37.5}}, { 500, {-0.1, -34.7, 1442, -19.5, 1301, -37.7, -0.1, -34.7}}, { 600, {-0.1, -46.0, 1363, -20.1, 1153, -40.7, -0.1, -46.0}}, { 700, { 0.0, -40.8, 1320, -20.7, 1045, -42.2, 0.0, -40.8}}, { 800, { 0.0, -40.1, 1269, -21.5, 943, -42.3, 0.0, -40.1}}, { 900, { 0.0, -40.6, 1227, -22.5, 878, -41.3, 0.0, -40.6}}, {1000, { 6.6, -28.0, 1161, -23.4, 825, -39.3, 6.6, -28.0}}, {1100, { 0.0, -16.5, 1082, -23.5, 797, -36.8, 0.0, -16.5}}, {1200, {-0.1, 0.3, 1000, -22.2, 798, -34.4, -0.1, 0.3}}, {1300, { 0.0, -2.3, 943, -19.3, 826, -33.2, 0.0, -2.3}}, {1400, { 0.0, 13.5, 896, -14.0, 870, -33.8, 0.0, 13.5}}, {1500, { 0.1, 22.6, 890, -7.2, 916, -36.8, 0.1, 22.6}}, {1600, { 0.3, 30.3, 940, -0.3, 938, -42.0, 0.3, 30.3}}, {1700, { 0.5, 12.5, 1052, 4.6, 929, -48.0, 0.5, 12.5}}, {1800, { 0.8, 458.6, 1212, 6.9, 880, -52.8, 0.8, 458.6}}, {1900, { 1.1, -5.1, 1410, 3.5, 814, -56.5, 1.1, -5.1}}, {2000, { 1.4, -5.0, 1579, -3.6, 747, -58.5, 1.4, -5.0}}, {2100, { 1.5, 6.1, 1618, -13.2, 688, -58.8, 1.5, 6.1}}, {2200, { 1.5, 33.5, 1491, -21.5, 646, -57.7, 1.5, 33.5}}, {2300, { 1.4, 80.5, 1275, -24.9, 625, -55.6, 1.4, 80.5}}, {2400, { 1.3, 142.3, 1078, -20.8, 633, -53.8, 1.3, 142.3}}, {2500, { 1.4, 196.5, 985, -9.3, 664, -54.5, 1.4, 196.5}}, {2600, { 1.6, 214.5, 1045, 2.4, 692, -57.6, 1.6, 214.5}}, {2700, { 2.4, 196.8, 1326, 13.7, 684, -63.5, 2.4, 196.8}}, {2800, { 3.4, 150.4, 1887, 14.7, 637, -68.3, 3.4, 150.4}}, {2900, { 4.3, 125.3, 2608, 1.3, 501, -70.7, 4.3, 125.3}}, {3000, { 4.9, 174.6, 2730, -21.8, 533, -70.6, 4.9, 174.6}}, {3100, { 4.9, 380.0, 2094, -33.7, 506, -68.5, 4.9, 380.0}}, {3200, { 5.2, 759.3, 1642, -21.3, 522, -67.0, 5.2, 759.3}}, {3300, { 8.0, 680.1, 2348, 0.5, 531, -72.9, 8.0, 680.1}}, {3400, {13.1, 237.8, 4510, -20.9, 482, -77.3, 13.1, 237.8}}, {3500, {18.2, -18.8, 4116, -59.6, 439, -78.0, 18.2, -18.8}}, {3600, {22.7, -145.4, 3041, -74.4, 487, -77.7, 22.7, -145.4}}, {3700, {26.8, -214.5, 2427, -80.1, 383, -77.1, 26.8, -214.5}}, {3800, {30.4, -257.0, 2054, -82.7, 364, -76.4, 30.4, -257.0}}, {3900, {33.7, -285.6, 1803, -84.2, 348, -75.0, 33.7, -285.6}}, {4000, {36.8, -306.2, 1621, -85.1, 334, -75.7, 36.8, -306.2}} }; /* V.56bis EIA LL-7, non-loaded loop */ struct { int freq; float ad[8]; } eia_ll7[] = { { 200, { 0.4, -81.3, 1848, -10.5, 1737, -15.6, 0.4, -81.3}}, { 300, { 0.3, -68.9, 1785, -16.2, 1585, -21.6, 0.3, -68.9}}, { 400, { 0.2, -68.1, 1646, -22.0, 1388, -25.8, 0.2, -68.1}}, { 500, { 0.1, -57.0, 1528, -26.2, 1247, -27.7, 0.1, -57.0}}, { 600, { 0.0, -59.8, 1349, -28.9, 1087, -27.3, 0.0, -59.8}}, { 700, { 0.0, -45.0, 1205, -29.1, 975, -24.8, 0.0, -45.0}}, { 800, {-0.1, -36.9, 1064, -26.8, 885, -19.7, -0.1, -36.9}}, { 900, {-0.1, -37.1, 989, -22.6, 846, -13.5, -0.1, -37.1}}, {1000, { 5.9, -29.2, 944, -16.6, 847, -6.1, 5.9, -29.2}}, {1100, { 0.1, -30.8, 951, -10.5, 900, 0.3, 0.1, -30.8}}, {1200, { 0.2, -40.7, 1008, -5.9, 999, 4.9, 0.2, -40.7}}, {1300, { 0.4, -53.3, 1897, -4.0, 1122, 4.6, 0.4, -53.3}}, {1400, { 0.5, -52.7, 1197, -4.8, 1253, 1.9, 0.5, -52.7}}, {1500, { 0.6, -48.3, 1269, -8.4, 1339, -3.8, 0.6, -48.3}}, {1600, { 0.6, -38.0, 1274, -13.2, 1337, -10.4, 0.6, -38.0}}, {1700, { 0.5, -21.6, 1208, -16.9, 1250, -15.2, 0.5, -21.6}}, {1800, { 0.4, 539.7, 1119, -17.8, 1143, -16.6, 0.4, 539.7}}, {1900, { 0.3, 35.4, 1027, -14.7, 1036, -13.7, 0.3, 35.4}}, {2000, { 0.3, 64.1, 989, -7.9, 998, -6.9, 0.3, 64.1}}, {2100, { 0.4, 76.1, 1045, 0.1, 1040, 1.0, 0.4, 76.1}}, {2200, { 0.6, 69.8, 1210, 5.3, 1197, 6.9, 0.6, 69.8}}, {2300, { 1.0, 55.9, 1460, 4.6, 1430, 5.4, 1.0, 55.9}}, {2400, { 1.2, 51.3, 1692, -2.8, 1640, -1.7, 1.2, 51.3}}, {2500, { 1.3, 72.6, 1730, -13.4, 1666, -11.5, 1.3, 72.6}}, {2600, { 1.3, 117.1, 1613, -49.6, 1556, -16.9, 1.3, 117.1}}, {2700, { 1.1, 222.5, 1371, -19.5, 1334, -16.1, 1.1, 222.5}}, {2800, { 1.1, 332.3, 1258, -8.9, 1243, -5.1, 1.1, 332.3}}, {2900, { 1.7, 356.1, 1474, 4.8, 1480, 8.4, 1.7, 356.1}}, {3000, { 2.8, 299.9, 2128, 6.6, 2143, 9.8, 2.8, 299.9}}, {3100, { 3.9, 309.4, 2813, -10.5, 2882, -7.1, 3.9, 309.4}}, {3200, { 4.4, 576.4, 2490, -27.7, 2487, -22.2, 4.4, 576.4}}, {3300, { 5.6, 1030.6, 2237, -17.4, 2385, -9.0, 5.6, 1030.6}}, {3400, {10.7, 570.2, 3882, -19.2, 4855, -14.9, 10.7, 570.2}}, {3500, {17.3, 83.5, 4116, -57.4, 4649, -63.5, 17.3, 83.5}}, {3600, {23.2, -130.6, 3057, -74.0, 3175, -78.6, 23.2, -130.6}}, {3700, {28.3, -153.9, 2432, -80.0, 2471, -83.1, 28.3, -153.9}}, {3800, {32.8, -292.4, 2055, -82.8, 2072, -85.1, 32.8, -292.4}}, {3900, {36.9, -249.9, 1803, -84.2, 1811, -86.1, 36.9, -249.9}}, {4000, {40.7, -356.2, 1621, -85.1, 1625, -86.7, 40.7, -356.2}} }; /* V.56bis ETSI LL-1, non-loaded loop */ struct { int freq; float ad[8]; } etsi_ll1[] = { { 200, {-0.78, 14.0, 1248.5, -9.7, 1248.5, -9.7, -0.78, 14.0}}, { 300, {-0.74, 10.0, 1220.9, -14.3, 1220.9, -14.3, -0.74, 10.0}}, { 400, {-0.68, 8.0, 1185.2, -18.6, 1185.2, -18.6, -0.68, 8.0}}, { 500, {-0.60, 7.0, 1143.9, -22.6, 1143.9, -22.6, -0.60, 7.0}}, { 600, {-0.51, 6.0, 1099.0, -26.2, 1099.0, -26.2, -0.51, 6.0}}, { 700, {-0.40, 5.6, 1052.5, -29.5, 1052.5, -29.5, -0.40, 5.6}}, { 800, {-0.28, 5.3, 1005.9, -32.4, 1005.9, -32.4, -0.28, 5.3}}, { 900, {-0.14, 5.0, 960.3, -35.0, 960.3, -35.0, -0.14, 5.0}}, {1000, { 4.7, 4.6, 916.4, -37.3, 916.4, -37.3, 4.7, 4.6}}, {1100, { 0.16, 4.3, 874.6, -39.3, 874.6, -39.3, 0.16, 4.3}}, {1200, { 0.33, 3.6, 835.3, -41.1, 835.3, -41.1, 0.33, 3.6}}, {1300, { 0.49, 2.6, 798.5, -42.6, 798.5, -42.6, 0.49, 2.6}}, {1400, { 0.67, 2.0, 764.2, -43.9, 764.2, -43.9, 0.67, 2.0}}, {1500, { 0.85, 1.0, 732.3, -45.1, 732.3, -45.1, 0.85, 1.0}}, {1600, { 1.04, 0.6, 702.7, -46.1, 702.7, -46.1, 1.04, 0.6}}, {1700, { 1.23, 0.3, 675.3, -47.0, 675.3, -47.0, 1.23, 0.3}}, {1800, { 1.43, 40.0, 649.8, -47.7, 649.8, -47.7, 1.43, 40.0}}, {1900, { 1.63, -1.0, 626.2, -48.4, 626.2, -48.4, 1.63, -1.0}}, {2000, { 1.83, -2.0, 604.3, -48.9, 604.3, -48.9, 1.83, -2.0}}, {2100, { 2.03, -3.3, 584.0, -49.4, 584.0, -49.4, 2.03, -3.3}}, {2200, { 2.23, -3.6, 565.1, -49.8, 565.1, -49.8, 2.23, -3.6}}, {2300, { 2.44, -4.3, 547.5, -50.1, 547.5, -50.1, 2.44, -4.3}}, {2400, { 2.64, -5.0, 531.1, -50.4, 531.1, -50.4, 2.64, -5.0}}, {2500, { 2.84, -6.1, 515.9, -50.6, 515.9, -50.6, 2.84, -6.1}}, {2600, { 3.05, -6.6, 501.6, -50.8, 501.6, -50.8, 3.05, -6.6}}, {2700, { 3.25, -7.3, 488.2, -51.0, 488.2, -51.0, 3.25, -7.3}}, {2800, { 3.45, -7.6, 475.7, -51.1, 475.7, -51.1, 3.45, -7.6}}, {2900, { 3.65, -8.3, 464.0, -51.1, 464.0, -51.1, 3.65, -8.3}}, {3000, { 3.85, -8.6, 453.0, -51.2, 453.0, -51.2, 3.85, -8.6}}, {3100, { 4.04, -9.3, 442.6, -51.2, 442.6, -51.2, 4.04, -9.3}}, {3200, { 4.24, -10.3, 432.9, -51.2, 432.9, -51.2, 4.24, -10.3}}, {3300, { 4.43, -10.6, 423.7, -51.2, 423.7, -51.2, 4.43, -10.6}}, {3400, { 4.62, -11.3, 415.1, -51.2, 415.1, -51.2, 4.62, -11.3}}, {3500, { 4.81, -11.6, 406.9, -51.1, 406.9, -51.1, 4.81, -11.6}}, {3600, { 5.00, -12.3, 399.1, -51.1, 399.1, -51.1, 5.00, -12.3}}, {3700, { 5.19, -13.0, 391.8, -51.0, 391.8, -51.0, 5.19, -13.0}}, {3800, { 5.37, -13.4, 384.9, -51.0, 384.9, -51.0, 5.37, -13.4}}, {3900, { 5.56, -13.8, 378.3, -50.9, 378.3, -50.9, 5.56, -13.8}}, {4000, { 5.74, -14.4, 372.0, -50.8, 372.0, -50.8, 5.74, -14.4}} }; /* V.56bis ETSI LL-2, non-loaded loop */ struct { int freq; float ad[8]; } etsi_ll2[] = { { 200, {-0.10, 15.0, 850.3, -3.4, 850.3, -3.4, -0.10, 15.0}}, { 300, {-0.09, 8.0, 848.1, -5.1, 848.1, -5.1, -0.09, 8.0}}, { 400, {-0.09, 7.0, 845.1, -6.7, 845.1, -6.7, -0.09, 7.0}}, { 500, {-0.08, 5.0, 841.3, -8.4, 841.3, -8.4, -0.08, 5.0}}, { 600, {-0.07, 4.6, 836.7, -10.0, 836.7, -10.0, -0.07, 4.6}}, { 700, {-0.06, 4.3, 831.3, -11.6, 831.3, -11.6, -0.06, 4.3}}, { 800, {-0.04, 3.8, 825.3, -13.2, 825.3, -13.2, -0.04, 3.8}}, { 900, {-0.02, 3.4, 818.6, -14.8, 818.6, -14.8, -0.02, 3.4}}, {1000, { 1.80, 3.0, 811.4, -16.3, 811.4, -16.3, 1.8, 3.0}}, {1100, { 0.02, 2.6, 803.6, -17.8, 803.6, -17.8, 0.02, 2.6}}, {1200, { 0.04, 2.3, 795.3, -19.3, 795.3, -19.3, 0.04, 2.3}}, {1300, { 0.06, 1.3, 786.6, -20.7, 786.6, -20.7, 0.06, 1.3}}, {1400, { 0.09, 0.9, 777.5, -22.1, 777.5, -22.1, 0.09, 0.9}}, {1500, { 0.12, 0.6, 768.1, -23.5, 768.1, -23.5, 0.12, 0.6}}, {1600, { 0.15, 0.3, 758.4, -24.8, 758.4, -24.8, 0.15, 0.3}}, {1700, { 0.18, 0.0, 748.4, -26.1, 748.4, -26.1, 0.18, 0.0}}, {1800, { 0.21, 15, 738.4, -27.3, 738.4, -27.3, 0.21, 15.0}}, {1900, { 0.24, -1.0, 728.1, -28.5, 728.1, -28.5, 0.24, -1.0}}, {2000, { 0.28, -2.3, 717.8, -29.7, 717.8, -29.7, 0.28, -2.3}}, {2100, { 0.32, -2.6, 707.4, -30.8, 707.4, -30.8, 0.32, -2.6}}, {2200, { 0.36, -3.0, 697.0, -31.9, 697.0, -31.9, 0.36, -3.0}}, {2300, { 0.40, -3.3, 686.6, -33.0, 686.6, -33.0, 0.40, -3.3}}, {2400, { 0.44, -3.6, 676.2, -34.0, 676.2, -34.0, 0.44, -3.6}}, {2500, { 0.48, -4.5, 665.9, -35.0, 665.9, -35.0, 0.48, -4.5}}, {2600, { 0.53, -5.4, 655.6, -35.9, 655.6, -35.9, 0.53, -5.4}}, {2700, { 0.57, -6.3, 645.5, -36.8, 645.5, -36.8, 0.57, -6.3}}, {2800, { 0.62, -6.6, 635.5, -37.7, 635.5, -37.7, 0.62, -6.6}}, {2900, { 0.67, -6.9, 625.6, -38.6, 625.6, -38.6, 0.67, -6.9}}, {3000, { 0.72, -7.5, 615.8, -39.4, 615.8, -39.4, 0.72, -7.5}}, {3100, { 0.77, -8.3, 606.2, -40.2, 606.2, -40.2, 0.77, -8.3}}, {3200, { 0.82, -8.6, 596.7, -40.9, 596.7, -40.9, 0.82, -8.6}}, {3300, { 0.87, -9.3, 587.4, -41.6, 587.4, -41.6, 0.87, -9.3}}, {3400, { 0.92, -9.6, 578.3, -42.3, 578.3, -42.3, 0.92, -9.6}}, {3500, { 0.98, -10.3, 569.3, -43.0, 569.3, -43.0, 0.98, -10.3}}, {3600, { 1.03, -10.6, 560.6, -43.7, 560.6, -43.7, 1.03, -10.6}}, {3700, { 1.09, -11.3, 552.0, -44.3, 552.0, -44.3, 1.09, -11.3}}, {3800, { 1.14, -11.6, 543.5, -44.9, 543.5, -44.9, 1.14, -11.6}}, {3900, { 1.20, -12.3, 535.3, -45.4, 535.3, -45.4, 1.20, -12.3}}, {4000, { 1.26, -13.3, 527.2, -46.0, 527.2, -46.0, 1.26, -13.3}} }; /* V.56bis AD-1 AD-5 AD-6 AD-7 AD-8 AD-9 */ struct { int freq; float ad[6]; } ad[] = { { 0, {90.0, 90.0, 90.0, 90.0, 90.0, 90.0}}, { 200, { 6.0, 3.2, 3.0, 2.9, 11.6, 23.3}}, { 300, { 1.3, 1.4, 1.2, 1.1, 6.9, 13.9}}, { 400, { 0.0, 0.4, 0.3, 0.3, 4.0, 7.9}}, { 500, { 0.0, -0.1, 0.0, 0.1, 2.0, 4.1}}, { 600, { 0.0, -0.1, 0.0, 0.1, 1.2, 2.4}}, { 700, { 0.0, 0.1, 0.0, 0.0, 0.8, 1.7}}, { 800, { 0.0, 0.0, 0.0, -0.1, 0.5, 1.1}}, { 900, { 0.0, 0.0, 0.0, -0.1, 0.2, 0.4}}, {1000, { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}}, {1100, { 0.0, 0.0, 0.1, 0.0, -0.1, -0.2}}, {1200, { 0.0, 0.0, 0.1, 0.1, -0.1, -0.2}}, {1300, { 0.0, 0.1, 0.2, 0.3, -0.1, -0.2}}, {1400, { 0.0, 0.2, 0.3, 0.4, -0.1, -0.3}}, {1500, { 0.0, 0.2, 0.3, 0.4, -0.2, -0.4}}, {1600, { 0.0, 0.3, 0.5, 0.5, -0.1, -0.3}}, {1700, { 0.0, 0.3, 0.5, 0.6, -0.1, -0.1}}, {1800, { 0.0, 0.3, 0.5, 0.6, 0.0, 0.0}}, {1900, { 0.0, 0.4, 0.7, 0.7, 0.1, 0.2}}, {2000, { 0.0, 0.5, 0.8, 0.9, 0.2, 0.5}}, {2100, { 0.1, 0.6, 1.0, 1.0, 0.5, 0.9}}, {2200, { 0.2, 0.7, 1.1, 1.1, 0.6, 1.1}}, {2300, { 0.3, 0.9, 1.2, 1.4, 0.8, 1.5}}, {2400, { 0.4, 1.1, 1.5, 1.6, 0.9, 1.8}}, {2500, { 0.5, 1.3, 1.8, 2.0, 1.1, 2.3}}, {2600, { 0.6, 1.6, 2.4, 2.7, 1.4, 2.8}}, {2700, { 0.7, 2.0, 3.0, 3.5, 1.7, 3.4}}, {2800, { 0.7, 2.3, 3.5, 4.3, 2.0, 4.0}}, {2900, { 0.9, 2.8, 4.2, 5.0, 2.4, 4.9}}, {3000, { 1.1, 3.2, 4.9, 5.8, 3.0, 5.9}}, {3100, { 1.2, 3.5, 5.6, 6.7, 3.4, 6.8}}, {3200, { 1.3, 4.1, 6.7, 8.0, 3.9, 7.7}}, {3300, { 1.6, 4.8, 8.0, 9.6, 4.6, 9.2}}, {3400, { 1.8, 5.3, 9.1, 11.0, 5.4, 10.7}}, {3500, { 2.4, 5.7, 10.3, 12.2, 6.3, 12.6}}, {3600, { 3.0, 6.6, 12.1, 13.9, 7.8, 15.5}}, {3700, { 5.7, 8.9, 15.8, 17.3, 10.3, 20.5}}, {3800, {13.5, 15.7, 24.4, 25.7, 16.2, 32.4}}, {3900, {31.2, 31.1, 42.2, 43.3, 29.9, 59.9}}, {4000, {31.2, 31.1, 42.2, 43.3, 29.9, 59.9}} }; /* V.56bis EDD-1 EDD-2 EDD-3 */ struct { int freq; float edd[3]; } edd[] = { { 0, {3.98, 3.76, 8.00}}, { 200, {3.98, 3.76, 8.00}}, { 300, {2.70, 3.76, 8.00}}, { 400, {1.69, 2.20, 6.90}}, { 500, {1.15, 1.36, 5.50}}, { 600, {0.80, 0.91, 4.40}}, { 700, {0.60, 0.64, 3.40}}, { 800, {0.50, 0.46, 2.80}}, { 900, {0.40, 0.34, 2.00}}, {1000, {0.30, 0.24, 1.50}}, {1100, {0.20, 0.16, 1.00}}, {1200, {0.20, 0.11, 0.70}}, {1300, {0.10, 0.07, 0.40}}, {1400, {0.05, 0.05, 0.30}}, {1500, {0.00, 0.03, 0.20}}, {1600, {0.00, 0.01, 0.10}}, {1700, {0.00, 0.00, 0.10}}, {1800, {0.00, 0.00, 0.00}}, {1900, {0.00, 0.02, 0.10}}, {2000, {0.00, 0.04, 0.10}}, {2100, {0.02, 0.08, 0.10}}, {2200, {0.02, 0.12, 0.20}}, {2300, {0.02, 0.16, 0.20}}, {2400, {0.02, 0.20, 0.30}}, {2500, {0.10, 0.27, 0.40}}, {2600, {0.12, 0.36, 0.50}}, {2700, {0.15, 0.47, 0.80}}, {2800, {0.20, 0.60, 1.10}}, {2900, {0.27, 0.77, 1.50}}, {3000, {0.40, 1.01, 2.00}}, {3100, {0.56, 1.32, 2.60}}, {3200, {0.83, 1.78, 3.20}}, {3300, {1.07, 1.78, 4.00}}, {3400, {1.39, 1.78, 4.00}}, {3500, {1.39, 1.78, 4.00}}, {3600, {1.39, 1.78, 4.00}}, {3700, {1.39, 1.78, 4.00}}, {3800, {1.39, 1.78, 4.00}}, {3900, {1.39, 1.78, 4.00}}, {4000, {1.39, 1.78, 4.00}} }; /* V.56bis PCM AD-1, AD-2, AD-3 */ struct { int freq; float ad[3]; } pcm_ad[] = { { 50, {41.4, 77.8, 114.2}}, { 100, {15.5, 27.7, 39.9}}, { 150, { 3.7, 6.1, 8.6}}, { 200, { 0.5, 0.8, 1.0}}, { 250, {-0.2, -0.2, -0.3}}, { 300, {-0.2, -0.3, -0.4}}, { 400, { 0.0, -0.2, -0.3}}, { 500, {-0.2, -0.4, -0.5}}, { 600, {-0.2, -0.3, -0.5}}, { 700, {-0.2, -0.3, -0.5}}, { 800, {-0.2, -0.4, -0.5}}, { 900, {-0.2, -0.3, -0.4}}, {1000, {-0.1, -0.2, -0.3}}, {1100, {-0.2, -0.3, -0.3}}, {1200, {-0.2, -0.3, -0.4}}, {1300, {-0.2, -0.3, -0.5}}, {1400, {-0.1, -0.3, -0.4}}, {1500, {-0.1, -0.3, -0.4}}, {1600, {-0.1, -0.2, -0.3}}, {1700, {-0.1, -0.3, -0.4}}, {1800, {-0.2, -0.3, -0.4}}, {1900, {-0.2, -0.3, -0.3}}, {2000, {-0.1, -0.2, -0.3}}, {2100, {-0.1, -0.2, -0.3}}, {2200, {-0.1, -0.3, -0.4}}, {2300, {-0.1, -0.1, -0.2}}, {2400, {-0.1, -0.1, -0.2}}, {2500, { 0.0, -0.1, -0.1}}, {2600, { 0.0, -0.1, -0.1}}, {2700, { 0.0, 0.0, 0.1}}, {2800, { 0.0, 0.0, 0.1}}, {2900, { 0.1, 0.2, 0.2}}, {3000, { 0.0, 0.0, 0.1}}, {3100, { 0.0, 0.0, 0.0}}, {3200, { 0.0, 0.0, 0.1}}, {3300, { 0.3, 0.7, 1.0}}, {3400, { 1.2, 2.4, 3.6}}, {3500, { 3.2, 6.3, 9.5}}, {3550, { 5.0, 9.6, 14.3}}, {3600, { 7.0, 13.5, 19.9}}, {3650, {10.0, 18.7, 27.5}}, {3700, {13.4, 24.6, 35.8}}, {3750, {18.1, 32.1, 46.2}}, {3800, {24.3, 41.2, 58.2}}, {3850, {32.5, 52.6, 72.7}}, {3900, {43.4, 66.6, 89.8}}, {4000, {43.4, 66.6, 89.8}} }; /* V.56bis PCM EDD-1, EDD-2, EDD-3 */ struct { int freq; float edd[3]; } pcm_edd[] = { { 150, { 2.76, 5.5, 8.3}}, { 200, { 1.70, 3.4, 5.1}}, { 250, { 0.92, 1.8, 2.8}}, { 300, { 0.55, 1.1, 1.7}}, { 400, { 0.25, 0.5, 0.7}}, { 500, { 0.12, 0.2, 0.4}}, { 600, { 0.06, 0.1, 0.2}}, { 700, { 0.03, 0.1, 0.1}}, { 800, { 0.01, 0.0, 0.0}}, { 900, { 0.00, 0.0, 0.0}}, {1000, {-0.01, 0.0, 0.0}}, {1100, {-0.01, 0.0, 0.0}}, {1200, {-0.02, 0.0, -0.1}}, {1300, {-0.02, 0.0, -0.1}}, {1400, {-0.01, 0.0, 0.0}}, {1500, {-0.01, 0.0, 0.0}}, {1600, { 0.00, 0.0, 0.0}}, {1700, { 0.00, 0.0, 0.0}}, {1800, { 0.01, 0.0, 0.0}}, {1900, { 0.02, 0.0, 0.0}}, {2000, { 0.02, 0.0, 0.1}}, {2100, { 0.04, 0.1, 0.1}}, {2200, { 0.05, 0.1, 0.2}}, {2300, { 0.06, 0.1, 0.2}}, {2400, { 0.07, 0.1, 0.2}}, {2500, { 0.10, 0.2, 0.3}}, {2600, { 0.11, 0.2, 0.3}}, {2700, { 0.14, 0.3, 0.4}}, {2800, { 0.18, 0.4, 0.5}}, {2900, { 0.22, 0.4, 0.6}}, {3000, { 0.27, 0.5, 0.8}}, {3100, { 0.34, 0.7, 1.0}}, {3200, { 0.45, 0.9, 1.4}}, {3250, { 0.52, 1.0, 1.6}}, {3300, { 0.60, 1.2, 1.8}}, {3350, { 0.66, 1.3, 2.0}}, {3400, { 0.74, 1.5, 2.2}}, {3450, { 0.79, 1.6, 2.4}}, {3500, { 0.83, 1.7, 2.5}}, {3550, { 0.84, 1.7, 2.5}}, {3600, { 0.81, 1.6, 2.4}}, {3700, { 0.81, 1.6, 2.4}}, {3800, { 0.81, 1.6, 2.4}}, {3900, { 0.81, 1.6, 2.4}}, {4000, { 0.81, 1.6, 2.4}} }; FILE *outfile; float impulse_responses[100][LINE_FILTER_SIZE]; int filter_sets = 0; static void generate_ad_edd(void) { float f; float offset; float amp; float phase; //float delay; float pw; #if defined(HAVE_FFTW3_H) double in[FFT_SIZE][2]; double out[FFT_SIZE][2]; #else fftw_complex in[FFT_SIZE]; fftw_complex out[FFT_SIZE]; #endif fftw_plan p; int i; int j; int k; int l; #if defined(HAVE_FFTW3_H) p = fftw_plan_dft_1d(FFT_SIZE, in, out, FFTW_BACKWARD, FFTW_ESTIMATE); #else p = fftw_create_plan(FFT_SIZE, FFTW_BACKWARD, FFTW_ESTIMATE); #endif for (j = 0; j < 6; j++) { for (k = 0; k < 3; k++) { for (i = 0; i < FFT_SIZE; i++) { #if defined(HAVE_FFTW3_H) in[i][0] = in[i][1] = 0.0f; #else in[i].re = in[i].im = 0.0f; #endif } for (i = 1; i < FFT_SIZE/2; i++) { f = (float) i*SAMPLE_RATE/FFT_SIZE; amp = 0.0f; for (l = 0; l < (int) (sizeof(ad)/sizeof(ad[0])); l++) { if (f < ad[l].freq) break; } if (l < (int) (sizeof(ad)/sizeof(ad[0]))) { offset = (f - ad[l - 1].freq)/(ad[l].freq - ad[l - 1].freq); amp = (1.0 - offset)*ad[l - 1].ad[j] + offset*ad[l].ad[j]; amp = pow(10.0, -amp/20.0); } //delay = 0.0f; for (l = 0; l < (int) (sizeof(edd)/sizeof(edd[0])); l++) { if (f < edd[l].freq) break; } if (l < (int) (sizeof(edd)/sizeof(edd[0]))) { offset = (f - edd[l - 1].freq)/(edd[l].freq - edd[l - 1].freq); //delay = (1.0f - offset)*edd[l - 1].edd[k] + offset*edd[l].edd[k]; } //phase = 2.0f*M_PI*f*delay*0.001f; phase = 0.0f; #if defined(HAVE_FFTW3_H) in[i][0] = amp*cosf(phase); in[i][1] = amp*sinf(phase); in[FFT_SIZE - i][0] = in[i][0]; in[FFT_SIZE - i][1] = -in[i][1]; #else in[i].re = amp*cosf(phase); in[i].im = amp*sinf(phase); in[FFT_SIZE - i].re = in[i].re; in[FFT_SIZE - i].im = -in[i].im; #endif } #if 0 for (i = 0; i < FFT_SIZE; i++) fprintf(outfile, "%5d %15.5f,%15.5f\n", i, in[i].re, in[i].im); #endif #if defined(HAVE_FFTW3_H) fftw_execute(p); #else fftw_one(p, in, out); #endif fprintf(outfile, "/* V.56bis AD-%d, EDD%d */\n", (j == 0) ? 1 : j + 4, k + 1); fprintf(outfile, "const float ad_%d_edd_%d_model[] =\n", (j == 0) ? 1 : j + 4, k + 1); fprintf(outfile, "{\n"); /* Normalise the filter's gain */ pw = 0.0f; l = FFT_SIZE - (LINE_FILTER_SIZE - 1)/2; for (i = 0; i < LINE_FILTER_SIZE; i++) { #if defined(HAVE_FFTW3_H) pw += out[l][0]*out[l][0]; #else pw += out[l].re*out[l].re; #endif if (++l == FFT_SIZE) l = 0; } pw = sqrt(pw); l = FFT_SIZE - (LINE_FILTER_SIZE - 1)/2; for (i = 0; i < LINE_FILTER_SIZE; i++) { #if defined(HAVE_FFTW3_H) impulse_responses[filter_sets][i] = out[l][0]/pw; #else impulse_responses[filter_sets][i] = out[l].re/pw; #endif fprintf(outfile, "%15.5f,\n", impulse_responses[filter_sets][i]); if (++l == FFT_SIZE) l = 0; } fprintf(outfile, "};\n\n"); filter_sets++; } } } static void generate_proakis(void) { float f; float f1; float offset; float amp; float phase; //float delay; float pw; int index; int i; int l; #if defined(HAVE_FFTW3_H) double in[FFT_SIZE][2]; double out[FFT_SIZE][2]; #else fftw_complex in[FFT_SIZE]; fftw_complex out[FFT_SIZE]; #endif fftw_plan p; #if defined(HAVE_FFTW3_H) p = fftw_plan_dft_1d(FFT_SIZE, in, out, FFTW_BACKWARD, FFTW_ESTIMATE); #else p = fftw_create_plan(FFT_SIZE, FFTW_BACKWARD, FFTW_ESTIMATE); #endif for (i = 0; i < FFT_SIZE; i++) { #if defined(HAVE_FFTW3_H) in[i][0] = in[i][1] = 0.0f; #else in[i].re = in[i].im = 0.0f; #endif } for (i = 1; i < FFT_SIZE/2; i++) { f = (float) i*SAMPLE_RATE/FFT_SIZE; f1 = f/200.0f; offset = f1 - floor(f1); index = (int) floor(f1); /* Linear interpolation */ amp = ((1.0f - offset)*proakis[index].amp + offset*proakis[index + 1].amp)/2.3f; //delay = (1.0f - offset)*proakis[index].delay + offset*proakis[index + 1].delay; //phase = 2.0f*M_PI*f*delay*0.001f; phase = 0.0f; #if defined(HAVE_FFTW3_H) in[i][0] = amp*cosf(phase); in[i][1] = amp*sinf(phase); in[FFT_SIZE - i][0] = in[i][0]; in[FFT_SIZE - i][1] = -in[i][1]; #else in[i].re = amp*cosf(phase); in[i].im = amp*sinf(phase); in[FFT_SIZE - i].re = in[i].re; in[FFT_SIZE - i].im = -in[i].im; #endif } #if defined(HAVE_FFTW3_H) fftw_execute(p); #else fftw_one(p, in, out); #endif fprintf(outfile, "/* Medium range telephone line response\n"); fprintf(outfile, " (from p 537, Digital Communication, John G. Proakis */\n"); fprintf(outfile, "const float proakis_line_model[] =\n"); fprintf(outfile, "{\n"); /* Normalise the filter's gain */ pw = 0.0f; l = FFT_SIZE - (LINE_FILTER_SIZE - 1)/2; for (i = 0; i < LINE_FILTER_SIZE; i++) { #if defined(HAVE_FFTW3_H) pw += out[l][0]*out[l][0]; #else pw += out[l].re*out[l].re; #endif if (++l == FFT_SIZE) l = 0; } pw = sqrt(pw); l = FFT_SIZE - (LINE_FILTER_SIZE - 1)/2; for (i = 0; i < LINE_FILTER_SIZE; i++) { #if defined(HAVE_FFTW3_H) impulse_responses[filter_sets][i] = out[l][0]/pw; #else impulse_responses[filter_sets][i] = out[l].re/pw; #endif fprintf(outfile, "%15.5f,\n", impulse_responses[filter_sets][i]); if (++l == FFT_SIZE) l = 0; } fprintf(outfile, "};\n\n"); filter_sets++; } int main(int argc, char *argv[]) { int i; int j; if ((outfile = fopen(LINE_MODEL_FILE_NAME, "w")) == NULL) { fprintf(stderr, "Failed to open %s\n", "line_model.txt"); exit(2); } generate_proakis(); generate_ad_edd(); fclose(outfile); if (argc > 1) { for (i = 0; i < LINE_FILTER_SIZE; i++) { printf("%d, ", i); for (j = 0; j < filter_sets; j++) { printf("%15.5f, ", impulse_responses[j][i]); } printf("\n"); } } return 0; }
{ "alphanum_fraction": 0.3586734906, "avg_line_length": 46.1729106628, "ext": "c", "hexsha": "cac9d75cc1d0d9c71e7fdd0bd68c0a5ec19ef1bb", "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": "c2bba464eaddc9ec70604a8614d84c5334461e8e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zengfanmao/mpds", "max_forks_repo_path": "VideoServer/libs/spandsp/spandsp-sim/make_line_models.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c2bba464eaddc9ec70604a8614d84c5334461e8e", "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": "zengfanmao/mpds", "max_issues_repo_path": "VideoServer/libs/spandsp/spandsp-sim/make_line_models.c", "max_line_length": 102, "max_stars_count": null, "max_stars_repo_head_hexsha": "c2bba464eaddc9ec70604a8614d84c5334461e8e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zengfanmao/mpds", "max_stars_repo_path": "VideoServer/libs/spandsp/spandsp-sim/make_line_models.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 26433, "size": 48066 }
// --------------------------------------------------------------------------- // // Author : github.com/luncliff (luncliff@gmail.com) // License : CC BY 4.0 // // Note // Async I/O operation support for socket // // --------------------------------------------------------------------------- #pragma once // clang-format off #ifdef USE_STATIC_LINK_MACRO // ignore macro declaration in static build # define _INTERFACE_ # define _HIDDEN_ #else # if defined(_MSC_VER) // MSVC # define _HIDDEN_ # ifdef _WINDLL # define _INTERFACE_ __declspec(dllexport) # else # define _INTERFACE_ __declspec(dllimport) # endif # elif defined(__GNUC__) || defined(__clang__) # define _INTERFACE_ __attribute__((visibility("default"))) # define _HIDDEN_ __attribute__((visibility("hidden"))) # else # error "unexpected compiler" # endif // compiler check #endif // clang-format on #ifndef COROUTINE_NET_IO_H #define COROUTINE_NET_IO_H #include <coroutine/yield.hpp> #include <chrono> #include <gsl/gsl> #if defined(_MSC_VER) #include <WS2tcpip.h> #include <WinSock2.h> #include <ws2def.h> #pragma comment(lib, "Ws2_32.lib") using io_control_block = OVERLAPPED; static constexpr bool is_winsock = true; static constexpr bool is_netinet = false; #else #include <fcntl.h> #include <netdb.h> #include <netinet/in.h> #include <sys/socket.h> #include <unistd.h> // - Note // follow the definition of Windows `OVERLAPPED` struct io_control_block { uint64_t internal; // uint32_t errc; int32_t flag; uint64_t internal_high; union { struct { int32_t offset; // socklen_t addrlen; int32_t offset_high; }; void* ptr; }; int64_t handle; // int64_t sd; }; static constexpr bool is_winsock = false; static constexpr bool is_netinet = true; #endif // - Note // Even though this class violates C++ Core Guidelines, // it will be used for simplicity union endpoint_t final { sockaddr_storage storage{}; sockaddr addr; sockaddr_in in4; sockaddr_in6 in6; }; using io_task_t = std::experimental::coroutine_handle<void>; using buffer_view_t = gsl::span<gsl::byte>; struct io_work_t : public io_control_block { io_task_t task{}; buffer_view_t buffer{}; endpoint_t* ep{}; public: _INTERFACE_ bool ready() const noexcept; _INTERFACE_ uint32_t error() const noexcept; }; static_assert(sizeof(buffer_view_t) <= sizeof(void*) * 2); static_assert(sizeof(io_work_t) <= 64); class io_send_to final : public io_work_t { public: _INTERFACE_ void suspend(io_task_t rh) noexcept(false); _INTERFACE_ int64_t resume() noexcept; public: auto await_ready() const noexcept { return this->ready(); } void await_suspend(io_task_t rh) noexcept(false) { return this->suspend(rh); } auto await_resume() noexcept { return this->resume(); } }; static_assert(sizeof(io_send_to) == sizeof(io_work_t)); [[nodiscard]] _INTERFACE_ auto send_to(uint64_t sd, const sockaddr_in& remote, // buffer_view_t buffer, io_work_t& work) noexcept(false) -> io_send_to&; [[nodiscard]] _INTERFACE_ // auto send_to(uint64_t sd, const sockaddr_in6& remote, // buffer_view_t buffer, io_work_t& work) noexcept(false) -> io_send_to&; class io_recv_from final : public io_work_t { public: _INTERFACE_ void suspend(io_task_t rh) noexcept(false); _INTERFACE_ int64_t resume() noexcept; public: auto await_ready() const noexcept { return this->ready(); } void await_suspend(io_task_t rh) noexcept(false) { return this->suspend(rh); } auto await_resume() noexcept { return this->resume(); } }; static_assert(sizeof(io_recv_from) == sizeof(io_work_t)); [[nodiscard]] _INTERFACE_ // auto recv_from(uint64_t sd, sockaddr_in6& remote, // buffer_view_t buffer, io_work_t& work) noexcept(false) -> io_recv_from&; [[nodiscard]] _INTERFACE_ // auto recv_from(uint64_t sd, sockaddr_in& remote, // buffer_view_t buffer, io_work_t& work) noexcept(false) -> io_recv_from&; class io_send final : public io_work_t { public: _INTERFACE_ void suspend(io_task_t rh) noexcept(false); _INTERFACE_ int64_t resume() noexcept; public: auto await_ready() const noexcept { return this->ready(); } void await_suspend(io_task_t rh) noexcept(false) { return this->suspend(rh); } auto await_resume() noexcept { return this->resume(); } }; static_assert(sizeof(io_send) == sizeof(io_work_t)); [[nodiscard]] _INTERFACE_ // auto send_stream(uint64_t sd, buffer_view_t buffer, uint32_t flag, io_work_t& work) noexcept(false) -> io_send&; class io_recv final : public io_work_t { public: _INTERFACE_ void suspend(io_task_t rh) noexcept(false); _INTERFACE_ int64_t resume() noexcept; public: auto await_ready() const noexcept { return this->ready(); } void await_suspend(io_task_t rh) noexcept(false) { return this->suspend(rh); } auto await_resume() noexcept { return this->resume(); } }; static_assert(sizeof(io_recv) == sizeof(io_work_t)); [[nodiscard]] _INTERFACE_ // auto recv_stream(uint64_t sd, buffer_view_t buffer, uint32_t flag, io_work_t& work) noexcept(false) -> io_recv&; // - Note // This function is only non-windows platform. // Over windows api, it always yields nothing. // // User must continue looping without break so that there is no leak of // event. Also, the library doesn't guarantee all coroutines(i/o tasks) // will be fetched at once. Therefore it is strongly recommended for user // to have a method to detect that coroutines are returned. _INTERFACE_ auto wait_io_tasks(std::chrono::nanoseconds timeout) noexcept(false) -> coro::enumerable<io_task_t>; _INTERFACE_ auto host_name() noexcept -> gsl::czstring<NI_MAXHOST>; _INTERFACE_ std::errc peer_name(uint64_t sd, sockaddr_in6& ep) noexcept; _INTERFACE_ std::errc sock_name(uint64_t sd, sockaddr_in6& ep) noexcept; _INTERFACE_ auto resolve(const addrinfo& hint, // gsl::czstring<NI_MAXHOST> name, gsl::czstring<NI_MAXSERV> serv) noexcept -> coro::enumerable<sockaddr_in6>; _INTERFACE_ std::errc nameof(const sockaddr_in& ep, // gsl::zstring<NI_MAXHOST> name) noexcept; _INTERFACE_ std::errc nameof(const sockaddr_in6& ep, // gsl::zstring<NI_MAXHOST> name) noexcept; _INTERFACE_ std::errc nameof(const sockaddr_in6& ep, // gsl::zstring<NI_MAXHOST> name, gsl::zstring<NI_MAXSERV> serv) noexcept; #endif // COROUTINE_NET_IO_H
{ "alphanum_fraction": 0.6298003072, "avg_line_length": 27.125, "ext": "h", "hexsha": "788434b39025d0e98bed6d89809e40e4d8a87268", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-09-16T09:09:16.000Z", "max_forks_repo_forks_event_min_datetime": "2021-09-16T09:09:16.000Z", "max_forks_repo_head_hexsha": "5082bc1ff710dcd17b3b4fb1b8cdfc1b3a1828a4", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "eddeighton/coroutine", "max_forks_repo_path": "interface/coroutine/net.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5082bc1ff710dcd17b3b4fb1b8cdfc1b3a1828a4", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "eddeighton/coroutine", "max_issues_repo_path": "interface/coroutine/net.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "5082bc1ff710dcd17b3b4fb1b8cdfc1b3a1828a4", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "eddeighton/coroutine", "max_stars_repo_path": "interface/coroutine/net.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1697, "size": 7161 }
#include <petsc.h> #include "compressibleFlow.h" #include "mesh.h" #define DIM 2 /* Geometric dimension */ typedef struct { PetscReal gamma; PetscReal rhoL; PetscReal rhoR; PetscReal uL; PetscReal uR; PetscReal pL; PetscReal pR; PetscReal maxTime; PetscReal length; } InitialConditions; typedef struct { PetscReal rho; PetscReal rhoU[2];//Hardcode for 2 for now PetscReal rhoE; } EulerNode; typedef struct { PetscReal pstar,ustar,rhostarL,astarL,SL,SHL,STL,rhostarR,astarR,SR,SHR,STR,gamm1,gamp1; } StarState; typedef struct { InitialConditions initialConditions; StarState starState; } ProblemSetup; typedef struct{ PetscReal f; PetscReal fprm; } PressureFunction; static PressureFunction f_and_fprm_rarefaction(PetscReal pstar, PetscReal pLR, PetscReal aLR, PetscReal gam, PetscReal gamm1,PetscReal gamp1) { // compute value of pressure function for rarefaction PressureFunction function; function.f = ((2. * aLR) / gamm1) * (pow(pstar / pLR, 0.5 * gamm1 / gam) - 1.); function.fprm = (aLR / pLR / gam) * pow(pstar / pLR, -0.5 * gamp1 / gam); return function; } static PressureFunction f_and_fprm_shock(PetscReal pstar, PetscReal pLR, PetscReal rhoLR, PetscReal gam, PetscReal gamm1, PetscReal gamp1){ // compute value of pressure function for shock PetscReal A = 2./gamp1/rhoLR; PetscReal B = gamm1*pLR/gamp1; PetscReal sqrtterm = PetscSqrtReal(A/(pstar+B)); PressureFunction function; function.f = (pstar-pLR)*sqrtterm; function.fprm = sqrtterm*(1.-0.5*(pstar-pLR)/(B+pstar)); return function; } #define EPS 1.e-6 #define MAXIT 100 PetscErrorCode DetermineStarState(const InitialConditions* setup, StarState* starState){ // compute the speed of sound PetscReal aL = PetscSqrtReal(setup->gamma*setup->pL/setup->rhoL); PetscReal aR = PetscSqrtReal(setup->gamma*setup->pR/setup->rhoR); //first guess pstar based on two-rarefacation approximation starState->pstar = aL+aR - 0.5*(setup->gamma-1.)*(setup->uR-setup->uL); starState->pstar = starState->pstar / (aL/pow(setup->pL,0.5*(setup->gamma-1.)/setup->gamma) + aR/pow(setup->pR,0.5*(setup->gamma-1.)/setup->gamma) ); starState->pstar = pow(starState->pstar,2.*setup->gamma/(setup->gamma-1.)); starState->gamm1 = setup->gamma-1.; starState->gamp1 = setup->gamma+1.; PressureFunction fL; if (starState->pstar <= setup->pL){ fL = f_and_fprm_rarefaction(starState->pstar, setup->pL,aL,setup->gamma,starState->gamm1,starState->gamp1); }else{ fL = f_and_fprm_shock(starState->pstar,setup->pL,setup->rhoL,setup->gamma,starState->gamm1,starState->gamp1); } PressureFunction fR; if (starState->pstar <= setup->pR) { fR = f_and_fprm_rarefaction(starState->pstar, setup->pR, aR, setup->gamma, starState->gamm1, starState->gamp1); }else { fR = f_and_fprm_shock(starState->pstar, setup->pR, setup->rhoR, setup->gamma, starState->gamm1, starState->gamp1); } PetscReal delu = setup->uR-setup->uL; // iterate using Newton-Rapson if ((fL.f+fR.f+delu)> EPS) { // iterate using Newton-Rapson for(PetscInt it =0; it < MAXIT+4; it++){ PetscReal pold = starState->pstar; starState->pstar = pold - (fL.f+fR.f+delu)/(fL.fprm+fR.fprm); if(starState->pstar < 0){ starState->pstar = EPS; } if(2.0*PetscAbsReal(starState->pstar - pold)/(starState->pstar + pold) < EPS){ break; }else{ if(starState->pstar < setup->pL){ fL = f_and_fprm_rarefaction(starState->pstar, setup->pL,aL,setup->gamma,starState->gamm1,starState->gamp1); }else{ fL = f_and_fprm_shock(starState->pstar,setup->pL,setup->rhoL,setup->gamma,starState->gamm1,starState->gamp1); } if (starState->pstar<=setup->pR) { fR = f_and_fprm_rarefaction(starState->pstar, setup->pR, aR, setup->gamma, starState->gamm1, starState->gamp1); }else { fR = f_and_fprm_shock(starState->pstar, setup->pR, setup->rhoR, setup->gamma, starState->gamm1, starState->gamp1); } } if (it>MAXIT){ SETERRQ(PETSC_COMM_WORLD,1,"error in Riemann.find_pstar - did not converage for pstar" ); } } } // determine rest of star state starState->ustar = 0.5*(setup->uL+setup->uR+fR.f-fL.f); // left star state PetscReal pratio = starState->pstar/setup->pL; if (starState->pstar<=setup->pL) { // rarefaction starState->rhostarL = setup->rhoL * PetscPowReal(pratio, 1. / setup->gamma); starState->astarL = aL * PetscPowReal(pratio, 0.5 * starState->gamm1 / setup->gamma); starState->SHL = setup->uL - aL; starState->STL = starState->ustar - starState->astarL; }else { // #shock starState->rhostarL = setup->rhoL * (pratio + starState->gamm1 / starState->gamp1) / (starState->gamm1 * pratio / starState->gamp1 + 1.); starState->SL = setup->uL - aL * PetscSqrtReal(0.5 * starState->gamp1 / setup->gamma * pratio + 0.5 * starState->gamm1 / setup->gamma); } // right star state pratio = starState->pstar/setup->pR; if (starState->pstar<=setup->pR) { // # rarefaction starState->rhostarR = setup->rhoR * PetscPowReal(pratio, 1. / setup->gamma); starState->astarR = aR * PetscPowReal(pratio, 0.5 * starState->gamm1 / setup->gamma); starState-> SHR = setup->uR + aR; starState->STR = starState->ustar + starState->astarR; }else { // shock starState->rhostarR = setup->rhoR * (pratio + starState->gamm1 / starState->gamp1) / (starState->gamm1 * pratio / starState->gamp1 + 1.); starState->SR = setup->uR + aR * PetscSqrtReal(0.5 * starState->gamp1 / setup->gamma * pratio + 0.5 * starState->gamm1 / setup->gamma); } return 0; } void SetExactSolutionAtPoint(PetscInt dim, PetscReal xDt, const InitialConditions* setup, const StarState* starState, EulerNode* uu){ PetscReal p; // compute the speed of sound PetscReal aL = PetscSqrtReal(setup->gamma*setup->pL/setup->rhoL); PetscReal aR = PetscSqrtReal(setup->gamma*setup->pR/setup->rhoR); for(PetscInt i =0; i < dim; i++){ uu->rhoU[i] = 0.0; } if (xDt <= starState->ustar) { //# left of contact surface if (starState->pstar <= setup->pL) { // # rarefaction if (xDt <= starState->SHL) { uu->rho = setup->rhoL; p = setup->pL; uu->rhoU[0] = setup->uL*uu->rho; }else if (xDt <=starState->STL) { //#SHL < x / t < STL PetscReal tmp = 2. / starState->gamp1 + (starState->gamm1 / starState->gamp1 / aL) * (setup->uL - xDt); uu->rho = setup->rhoL * pow(tmp, 2. / starState->gamm1); uu->rhoU[0] = uu->rho * (2. / starState->gamp1) * (aL + 0.5 * starState->gamm1 * setup->uL + xDt); p = setup->pL * pow(tmp, 2. * setup->gamma / starState->gamm1); }else { //# STL < x/t < u* uu->rho = starState->rhostarL; p = starState->pstar; uu->rhoU[0] = uu->rho * starState->ustar; } }else{ //# shock if (xDt<= starState->SL) { // # xDt < SL uu->rho = setup->rhoL; p = setup->pL; uu->rhoU[0] = uu->rho * setup->uL; }else { //# SL < xDt < ustar uu->rho = starState->rhostarL; p = starState->pstar; uu->rhoU[0] = uu->rho * starState->ustar; } } }else{//# right of contact surface if (starState->pstar<=setup->pR) { //# rarefaction if (xDt>= starState->SHR) { uu->rho = setup->rhoR; p = setup->pR; uu->rhoU[0] = uu->rho * setup->uR; }else if (xDt >= starState->STR) { // # SHR < x/t < SHR PetscReal tmp = 2./starState->gamp1 - (starState->gamm1/starState->gamp1/aR)*(setup->uR-xDt); uu->rho = setup->rhoR*PetscPowReal(tmp,2./starState->gamm1); uu->rhoU[0] = uu->rho * (2./starState->gamp1)*(-aR + 0.5*starState->gamm1*setup->uR+xDt); p = setup->pR*PetscPowReal(tmp,2.*setup->gamma/starState->gamm1); }else{ //# u* < x/t < STR uu->rho = starState->rhostarR; p = starState->pstar; uu->rhoU[0] = uu->rho * starState->ustar; } }else {//# shock if (xDt>= starState->SR) { // # xDt > SR uu->rho = setup->rhoR; p = setup->pR; uu->rhoU[0] = uu->rho * setup->uR; }else {//#ustar < xDt < SR uu->rho = starState->rhostarR; p = starState->pstar; uu->rhoU[0] = uu->rho * starState->ustar; } } } PetscReal e = p/starState->gamm1/uu->rho; PetscReal E = e + 0.5*(uu->rhoU[0]/uu->rho)*(uu->rhoU[0]/uu->rho); uu->rhoE = uu->rho*E; } static PetscErrorCode SetExactSolutionRho(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx){ ProblemSetup* prob = (ProblemSetup*)ctx; PetscReal xDt = (x[0]-prob->initialConditions.length/2)/time; EulerNode uu; SetExactSolutionAtPoint(dim, xDt, &prob->initialConditions, &prob->starState, &uu); u[0] = uu.rho; return 0; } static PetscErrorCode SetExactSolutionRhoU(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx){ ProblemSetup* prob = (ProblemSetup*)ctx; PetscReal xDt = (x[0]-prob->initialConditions.length/2)/time; EulerNode uu; SetExactSolutionAtPoint(dim, xDt, &prob->initialConditions, &prob->starState, &uu); u[0] = uu.rhoU[0]; u[1] = uu.rhoU[1]; return 0; } static PetscErrorCode SetExactSolutionRhoE(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx){ ProblemSetup* prob = (ProblemSetup*)ctx; PetscReal xDt = (x[0]-prob->initialConditions.length/2)/time; EulerNode uu; SetExactSolutionAtPoint(dim, xDt, &prob->initialConditions, &prob->starState, &uu); u[0] = uu.rhoE; return 0; } static PetscErrorCode PrintVector(DM dm, Vec v, PetscInt step, const char * fileName){ Vec cellgeom; PetscErrorCode ierr = DMPlexGetGeometryFVM(dm, NULL, &cellgeom, NULL);CHKERRQ(ierr); PetscInt cStart, cEnd; ierr = DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd);CHKERRQ(ierr); DM dmCell; ierr = VecGetDM(cellgeom, &dmCell);CHKERRQ(ierr); const PetscScalar *cgeom; ierr = VecGetArrayRead(cellgeom, &cgeom);CHKERRQ(ierr); const PetscScalar *x; ierr = VecGetArrayRead(v, &x);CHKERRQ(ierr); // print the header for each file char filename[100]; ierr = PetscSNPrintf(filename,sizeof(filename),"%s.%d.txt",fileName, step);CHKERRQ(ierr); PetscInt rank = 0; PetscInt size; ierr = MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank);CHKERRMPI(ierr); ierr = MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size);CHKERRMPI(ierr); for(PetscInt r =0; r < size; r++ ) { if(r == rank) { FILE *fptr; if(r == 0){ fptr = fopen(filename, "w"); fprintf(fptr, "x rho u e rhou rhoe\n"); }else{ fptr = fopen(filename, "a"); } for (PetscInt c = cStart; c < cEnd; ++c) { PetscFVCellGeom *cg; const EulerNode *xc; ierr = DMPlexPointLocalRead(dmCell, c, cgeom, &cg); CHKERRQ(ierr); ierr = DMPlexPointGlobalFieldRead(dm, c, 0, x, &xc); CHKERRQ(ierr); if(xc) {// must be real cell and not ghost PetscReal u0 = xc->rhoU[0] / xc->rho; fprintf(fptr, "%f %f %f %f %f %f\n", cg->centroid[0], xc->rho, u0, (xc->rhoE / xc->rho) - 0.5 * u0 * u0, xc->rhoU[0], xc->rhoE); } } fclose(fptr); } MPI_Barrier(PetscObjectComm((PetscObject)dm)); } ierr = VecRestoreArrayRead(cellgeom, &cgeom);CHKERRQ(ierr); ierr = VecRestoreArrayRead(v, &x);CHKERRQ(ierr); return 0; } static PetscErrorCode MonitorError(TS ts, PetscInt step, PetscReal time, Vec u, void *ctx) { PetscFunctionBeginUser; PetscErrorCode ierr; // Get the DM DM dm; ierr = TSGetDM(ts, &dm);CHKERRQ(ierr); // Create a copy of the u vector Vec e; ierr = DMCreateGlobalVector(dm, &e);CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject)e, "exact");CHKERRQ(ierr); // Set the values PetscErrorCode (*func[3]) (PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) = {SetExactSolutionRho, SetExactSolutionRhoU, SetExactSolutionRhoE}; void* ctxs[3] ={ctx, ctx, ctx}; ierr = DMProjectFunction(dm,time,func,ctxs,INSERT_ALL_VALUES,e);CHKERRQ(ierr); // just print to a file for now ierr = PrintVector(dm, e, step, "exact");CHKERRQ(ierr); ierr = PrintVector(dm, u, step, "solution");CHKERRQ(ierr); PetscPrintf(PETSC_COMM_WORLD, "TS %d: %f\n", step, time); DMRestoreGlobalVector(dm, &e); PetscFunctionReturn(0); } static PetscErrorCode PhysicsBoundary_Euler_Mirror(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *a_xI, PetscScalar *a_xG, void *ctx) { const EulerNode *xI = (const EulerNode*)a_xI; EulerNode *xG = (EulerNode*)a_xG; ProblemSetup* prob = (ProblemSetup*)ctx; PetscFunctionBeginUser; xG->rho = xI->rho; xG->rhoE = xI->rhoE; xG->rhoU[0] = xI->rhoU[0]; xG->rhoU[1] = xI->rhoU[1]; PetscFunctionReturn(0); } /* PetscReal* => EulerNode* conversion */ static PetscErrorCode PhysicsBoundary_Euler_Left(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *a_xI, PetscScalar *a_xG, void *ctx) { const EulerNode *xI = (const EulerNode*)a_xI; EulerNode *xG = (EulerNode*)a_xG; ProblemSetup* prob = (ProblemSetup*)ctx; PetscFunctionBeginUser; xG->rho = prob->initialConditions.rhoL; PetscReal eT = prob->initialConditions.rhoL*((prob->initialConditions.pL /(prob->initialConditions.gamma -1) / prob->initialConditions.rhoL) + 0.5 * prob->initialConditions.uL * prob->initialConditions.uL); xG->rhoE = eT; xG->rhoU[0] = prob->initialConditions.rhoL * prob->initialConditions.uL; xG->rhoU[1] = 0.0; PetscFunctionReturn(0); } /* PetscReal* => EulerNode* conversion */ static PetscErrorCode PhysicsBoundary_Euler_Right(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *a_xI, PetscScalar *a_xG, void *ctx) { const EulerNode *xI = (const EulerNode*)a_xI; EulerNode *xG = (EulerNode*)a_xG; ProblemSetup* prob = (ProblemSetup*)ctx; PetscFunctionBeginUser; xG->rho = prob->initialConditions.rhoR; PetscReal eT = prob->initialConditions.rhoR*((prob->initialConditions.pR /(prob->initialConditions.gamma -1)/ prob->initialConditions.rhoR) + 0.5 * prob->initialConditions.uR * prob->initialConditions.uR); xG->rhoE = eT; xG->rhoU[0] = prob->initialConditions.rhoR * prob->initialConditions.uR; xG->rhoU[1] = 0.0; PetscFunctionReturn(0); } int main(int argc, char **argv) { PetscErrorCode ierr; // create the mesh // setup the ts DM dm; /* problem definition */ TS ts; /* timestepper */ // initialize petsc and mpi PetscInitialize(&argc, &argv, NULL, "HELP"); // Create a ts ierr = TSCreate(PETSC_COMM_WORLD, &ts);CHKERRQ(ierr); ierr = TSSetProblemType(ts, TS_NONLINEAR);CHKERRQ(ierr); ierr = TSSetType(ts, TSEULER);CHKERRQ(ierr); ierr = TSSetExactFinalTime(ts, TS_EXACTFINALTIME_MATCHSTEP);CHKERRQ(ierr); // Create a mesh // hard code the problem setup PetscReal start[] = {0.0, 0.0}; PetscReal end[] = {1.0, 1}; PetscInt nx[] = {100, 1}; DMBoundaryType bcType[] = {DM_BOUNDARY_NONE, DM_BOUNDARY_NONE}; ierr = DMPlexCreateBoxMesh(PETSC_COMM_WORLD, DIM, PETSC_FALSE, nx, start, end, bcType, PETSC_TRUE, &dm);CHKERRQ(ierr); // Setup the problem ProblemSetup problem; // case 1 - Sod problem problem.initialConditions.rhoL=1.0; problem.initialConditions.uL=0.0; problem.initialConditions.pL=1.0; problem.initialConditions.rhoR=0.125; problem.initialConditions.uR=0.0; problem.initialConditions.pR=0.1; problem.initialConditions.maxTime = 0.25; problem.initialConditions.length = 1; problem.initialConditions.gamma = 1.4; // case 2 // problem.initialConditions.rhoL=1.0; // problem.initialConditions.uL=-2.0; // problem.initialConditions.pL=0.4; // problem.initialConditions.rhoR=1.0; // problem.initialConditions.uR=2.0; // problem.initialConditions.pR=0.4; // problem.initialConditions.maxTime = 0.15; // problem.initialConditions.length = 1; // problem.initialConditions.gamma = 1.4; // case 5 // problem.initialConditions.rhoL=5.99924; // problem.initialConditions.uL=19.5975; // problem.initialConditions.pL=460.894; // problem.initialConditions.rhoR=5.99242; // problem.initialConditions.uR=-6.19633; // problem.initialConditions.pR=46.0950; // problem.initialConditions.maxTime = 0.035; // problem.initialConditions.length = 1; // problem.initialConditions.gamma = 1.4; // Compute the star state ierr = DetermineStarState(&problem.initialConditions, &problem.starState);CHKERRQ(ierr); // Setup the flow data FlowData flowData; /* store some of the flow data*/ ierr = FlowCreate(&flowData);CHKERRQ(ierr); //Setup CompressibleFlow_SetupDiscretization(flowData, dm); // Add in the flow parameters PetscScalar params[TOTAL_COMPRESSIBLE_FLOW_PARAMETERS]; params[CFL] = 0.5; params[GAMMA] = problem.initialConditions.gamma; // set up the finite volume fluxes CompressibleFlow_StartProblemSetup(flowData, TOTAL_COMPRESSIBLE_FLOW_PARAMETERS, params); DMView(flowData->dm, PETSC_VIEWER_STDERR_SELF); // Add in any boundary conditions PetscDS prob; ierr = DMGetDS(flowData->dm, &prob); CHKERRABORT(PETSC_COMM_WORLD, ierr); const PetscInt idsLeft[]= {4}; ierr = PetscDSAddBoundary(prob, DM_BC_NATURAL_RIEMANN, "wall left", "Face Sets", 0, 0, NULL, (void (*)(void)) PhysicsBoundary_Euler_Left, NULL, 1, idsLeft, &problem);CHKERRQ(ierr); const PetscInt idsRight[]= {2}; ierr = PetscDSAddBoundary(prob, DM_BC_NATURAL_RIEMANN, "wall right", "Face Sets", 0, 0, NULL, (void (*)(void)) PhysicsBoundary_Euler_Right, NULL, 1, idsRight, &problem);CHKERRQ(ierr); const PetscInt mirror[]= {1, 3}; ierr = PetscDSAddBoundary(prob, DM_BC_NATURAL_RIEMANN, "mirrorWall", "Face Sets", 0, 0, NULL, (void (*)(void)) PhysicsBoundary_Euler_Mirror, NULL, 2, mirror, &problem);CHKERRQ(ierr); // Complete the problem setup ierr = CompressibleFlow_CompleteProblemSetup(flowData, ts); CHKERRABORT(PETSC_COMM_WORLD, ierr); // Name the flow field ierr = PetscObjectSetName(((PetscObject)flowData->flowField), "Numerical Solution"); CHKERRABORT(PETSC_COMM_WORLD, ierr); // Setup the TS ierr = TSSetFromOptions(ts); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = TSMonitorSet(ts, MonitorError, &problem, NULL);CHKERRQ(ierr); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = TSSetMaxTime(ts,problem.initialConditions.maxTime);CHKERRQ(ierr); // set the initial conditions PetscErrorCode (*func[3]) (PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) = {SetExactSolutionRho, SetExactSolutionRhoU, SetExactSolutionRhoE}; void* ctxs[3] ={&problem, &problem, &problem}; ierr = DMProjectFunction(flowData->dm,0.0,func,ctxs,INSERT_ALL_VALUES,flowData->flowField);CHKERRQ(ierr); ierr = TSSolve(ts,flowData->flowField);CHKERRQ(ierr); return PetscFinalize(); }
{ "alphanum_fraction": 0.6262004432, "avg_line_length": 41.3543788187, "ext": "c", "hexsha": "2208cb87c95ebbff3a409a626aba7054732cb0c9", "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": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "mmcgurn/MattFlowCases", "max_forks_repo_path": "eulerFlow.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "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": "mmcgurn/MattFlowCases", "max_issues_repo_path": "eulerFlow.c", "max_line_length": 210, "max_stars_count": null, "max_stars_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "mmcgurn/MattFlowCases", "max_stars_repo_path": "eulerFlow.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6261, "size": 20305 }
/** * * @file testing_zpotri.c * * PLASMA testing routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Hatem Ltaief * @date 2010-11-15 * @precisions normal z -> c d s * **/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <plasma.h> #include <cblas.h> #include <lapacke.h> #include <core_blas.h> #include "testing_zmain.h" enum blas_order_type { blas_rowmajor = 101, blas_colmajor = 102 }; enum blas_cmach_type { blas_base = 151, blas_t = 152, blas_rnd = 153, blas_ieee = 154, blas_emin = 155, blas_emax = 156, blas_eps = 157, blas_prec = 158, blas_underflow = 159, blas_overflow = 160, blas_sfmin = 161}; enum blas_norm_type { blas_one_norm = 171, blas_real_one_norm = 172, blas_two_norm = 173, blas_frobenius_norm = 174, blas_inf_norm = 175, blas_real_inf_norm = 176, blas_max_norm = 177, blas_real_max_norm = 178 }; static void BLAS_error(char *rname, int err, int val, int x) { fprintf( stderr, "%s %d %d %d\n", rname, err, val, x ); abort(); } static void BLAS_zge_norm(enum blas_order_type order, enum blas_norm_type norm, int m, int n, const PLASMA_Complex64_t *a, int lda, double *res) { int i, j; float anorm, v; char rname[] = "BLAS_zge_norm"; if (order != blas_colmajor) BLAS_error( rname, -1, order, 0 ); if (norm == blas_frobenius_norm) { anorm = 0.0f; for (j = n; j; --j) { for (i = m; i; --i) { v = a[0]; anorm += v * v; a++; } a += lda - m; } anorm = sqrt( anorm ); } else if (norm == blas_inf_norm) { anorm = 0.0f; for (i = 0; i < m; ++i) { v = 0.0f; for (j = 0; j < n; ++j) { v += cabs( a[i + j * lda] ); } if (v > anorm) anorm = v; } } else if (norm == blas_one_norm) { anorm = 0.0f; for (i = 0; i < m; ++i) { v = 0.0f; for (j = 0; j < n; ++j) { v += cabs( a[i + j * lda] ); } if (v > anorm) anorm = v; } } else { BLAS_error( rname, -2, norm, 0 ); return; } if (res) *res = anorm; } static double BLAS_dpow_di(double x, int n) { double rv = 1.0; if (n < 0) { n = -n; x = 1.0 / x; } for (; n; n >>= 1, x *= x) { if (n & 1) rv *= x; } return rv; } static double BLAS_dfpinfo(enum blas_cmach_type cmach) { double eps = 1.0, r = 1.0, o = 1.0, b = 2.0; int t = 53, l = 1024, m = -1021; char rname[] = "BLAS_dfpinfo"; if ((sizeof eps) == sizeof(float)) { t = 24; l = 128; m = -125; } else { t = 53; l = 1024; m = -1021; } /* for (i = 0; i < t; ++i) eps *= half; */ eps = BLAS_dpow_di( b, -t ); /* for (i = 0; i >= m; --i) r *= half; */ r = BLAS_dpow_di( b, m-1 ); o -= eps; /* for (i = 0; i < l; ++i) o *= b; */ o = (o * BLAS_dpow_di( b, l-1 )) * b; switch (cmach) { case blas_eps: return eps; case blas_sfmin: return r; default: BLAS_error( rname, -1, cmach, 0 ); break; } return 0.0; } static int check_factorization(int, PLASMA_Complex64_t*, PLASMA_Complex64_t*, int, int, double); static int check_inverse(int, PLASMA_Complex64_t *, PLASMA_Complex64_t *, int, int, double); int testing_zpotri(int argc, char **argv) { /* Check for number of arguments*/ if (argc != 2){ USAGE("POTRI", "N LDA", " - N : the size of the matrix\n" " - LDA : leading dimension of the matrix A\n"); return -1; } int N = atoi(argv[0]); int LDA = atoi(argv[1]); double eps; int uplo; int info_inverse, info_factorization; PLASMA_Complex64_t *A1 = (PLASMA_Complex64_t *)malloc(LDA*N*sizeof(PLASMA_Complex64_t)); PLASMA_Complex64_t *A2 = (PLASMA_Complex64_t *)malloc(LDA*N*sizeof(PLASMA_Complex64_t)); PLASMA_Complex64_t *WORK = (PLASMA_Complex64_t *)malloc(2*LDA*sizeof(PLASMA_Complex64_t)); /* Check if unable to allocate memory */ if ((!A1)||(!A2)){ printf("Out of Memory \n "); return -2; } eps = BLAS_dfpinfo( blas_eps ); uplo = PlasmaUpper; /*------------------------------------------------------------- * TESTING ZPOTRI */ /* Initialize A1 and A2 for Symmetric Positif Matrix */ PLASMA_zplghe( (double)N, N, A1, LDA, 51 ); PLASMA_zlacpy( PlasmaUpperLower, N, N, A1, LDA, A2, LDA ); printf("\n"); printf("------ TESTS FOR PLASMA ZPOTRI ROUTINE ------- \n"); printf(" Size of the Matrix %d by %d\n", N, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n", eps); printf(" Computational tests pass if scaled residuals are less than 60.\n"); /* PLASMA ZPOTRF */ PLASMA_zpotrf(uplo, N, A2, LDA); /* Check the factorization */ info_factorization = check_factorization( N, A1, A2, LDA, uplo, eps); /* PLASMA ZPOTRI */ PLASMA_zpotri(uplo, N, A2, LDA); /* Check the inverse */ info_inverse = check_inverse(N, A1, A2, LDA, uplo, eps); if ( (info_inverse == 0) && (info_factorization == 0) ) { printf("***************************************************\n"); printf(" ---- TESTING ZPOTRI ..................... PASSED !\n"); printf("***************************************************\n"); } else { printf("***************************************************\n"); printf(" - TESTING ZPOTRI ... FAILED !\n"); printf("***************************************************\n"); } free(A1); free(A2); free(WORK); return 0; } /*------------------------------------------------------------------------ * Check the factorization of the matrix A2 */ static int check_factorization(int N, PLASMA_Complex64_t *A1, PLASMA_Complex64_t *A2, int LDA, int uplo, double eps) { double Anorm, Rnorm; PLASMA_Complex64_t alpha; int info_factorization; int i,j; PLASMA_Complex64_t *Residual = (PLASMA_Complex64_t *)malloc(N*N*sizeof(PLASMA_Complex64_t)); PLASMA_Complex64_t *L1 = (PLASMA_Complex64_t *)malloc(N*N*sizeof(PLASMA_Complex64_t)); PLASMA_Complex64_t *L2 = (PLASMA_Complex64_t *)malloc(N*N*sizeof(PLASMA_Complex64_t)); double *work = (double *)malloc(N*sizeof(double)); memset((void*)L1, 0, N*N*sizeof(PLASMA_Complex64_t)); memset((void*)L2, 0, N*N*sizeof(PLASMA_Complex64_t)); alpha= 1.0; LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,' ', N, N, A1, LDA, Residual, N); /* Dealing with L'L or U'U */ if (uplo == PlasmaUpper){ LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L1, N); LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L2, N); cblas_ztrmm(CblasColMajor, CblasLeft, CblasUpper, CblasConjTrans, CblasNonUnit, N, N, CBLAS_SADDR(alpha), L1, N, L2, N); } else{ LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L1, N); LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L2, N); cblas_ztrmm(CblasColMajor, CblasRight, CblasLower, CblasConjTrans, CblasNonUnit, N, N, CBLAS_SADDR(alpha), L1, N, L2, N); } /* Compute the Residual || A -L'L|| */ for (i = 0; i < N; i++) for (j = 0; j < N; j++) Residual[j*N+i] = L2[j*N+i] - Residual[j*N+i]; BLAS_zge_norm( blas_colmajor, blas_inf_norm, N, N, Residual, N, &Rnorm ); BLAS_zge_norm( blas_colmajor, blas_inf_norm, N, N, A1, LDA, &Anorm ); printf("============\n"); printf("Checking the Cholesky Factorization \n"); printf("-- ||L'L-A||_oo/(||A||_oo.N.eps) = %e \n",Rnorm/(Anorm*N*eps)); if ( isnan(Rnorm/(Anorm*N*eps)) || isinf(Rnorm/(Anorm*N*eps)) || (Rnorm/(Anorm*N*eps) > 60.0) ){ printf("-- Factorization is suspicious ! \n"); info_factorization = 1; } else{ printf("-- Factorization is CORRECT ! \n"); info_factorization = 0; } free(Residual); free(L1); free(L2); free(work); return info_factorization; } /*------------------------------------------------------------------------ * Check the accuracy of the computed inverse */ static int check_inverse(int N, PLASMA_Complex64_t *A1, PLASMA_Complex64_t *A2, int LDA, int uplo, double eps ) { int info_inverse; int i, j; double Rnorm, Anorm, Ainvnorm, result; PLASMA_Complex64_t alpha, beta, zone; PLASMA_Complex64_t *work = (PLASMA_Complex64_t *)malloc(N*N*sizeof(PLASMA_Complex64_t)); alpha = -1.0; beta = 0.0; zone = 1.0; /* Rebuild the other part of the inverse matrix */ if(uplo == PlasmaUpper){ for(j=0; j<N; j++) for(i=0; i<j; i++) *(A2+j+i*LDA) = *(A2+i+j*LDA); cblas_zhemm(CblasColMajor, CblasLeft, CblasUpper, N, N, CBLAS_SADDR(alpha), A2, LDA, A1, LDA, CBLAS_SADDR(beta), work, N); } else { for(j=0; j<N; j++) for(i=j; i<N; i++) *(A2+j+i*LDA) = *(A2+i+j*LDA); cblas_zhemm(CblasColMajor, CblasLeft, CblasLower, N, N, CBLAS_SADDR(alpha), A2, LDA, A1, LDA, CBLAS_SADDR(beta), work, N); } /* Add the identity matrix to work */ for(i=0; i<N; i++) *(work+i+i*N) = *(work+i+i*N) + zone; BLAS_zge_norm( blas_colmajor, blas_one_norm, N, N, work, N, &Rnorm ); BLAS_zge_norm( blas_colmajor, blas_one_norm, N, N, A1, LDA, &Anorm ); BLAS_zge_norm( blas_colmajor, blas_one_norm, N, N, A2, LDA, &Ainvnorm ); if (getenv("PLASMA_TESTING_VERBOSE")) printf( "||A||_1=%f\n||Ainv||_1=%f\n||Id - A*Ainv||_1=%e\n", Anorm, Ainvnorm, Rnorm ); result = Rnorm / ( (Anorm*Ainvnorm)*N*eps ) ; printf("============\n"); printf("Checking the Residual of the inverse \n"); printf("-- ||Id - A*Ainv||_1/((||A||_1||Ainv||_1).N.eps) = %e \n", result); if ( isnan(Ainvnorm) || isinf(Ainvnorm) || isnan(result) || isinf(result) || (result > 60.0) ) { printf("-- The inverse is suspicious ! \n"); info_inverse = 1; } else{ printf("-- The inverse is CORRECT ! \n"); info_inverse = 0; } free(work); return info_inverse; }
{ "alphanum_fraction": 0.5365922844, "avg_line_length": 29.2154696133, "ext": "c", "hexsha": "e7d00f873724eea6173519158ee10c78ca8e9c1d", "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": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "testing/testing_zpotri.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "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": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "testing/testing_zpotri.c", "max_line_length": 129, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "testing/testing_zpotri.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3504, "size": 10576 }
/** * * @file timing.c * * PLASMA auxiliary routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author ??? * @author Mathieu Faverge * @author Dulceneia Becker * @date 2010-11-15 * **/ #if defined( _WIN32 ) || defined( _WIN64 ) #define int64_t __int64 #endif #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef PLASMA_EZTRACE #include <eztrace.h> #endif #if defined( _WIN32 ) || defined( _WIN64 ) #include <windows.h> #include <time.h> #include <sys/timeb.h> #if defined(_MSC_VER) || defined(_MSC_EXTENSIONS) #define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64 #else #define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL #endif struct timezone { int tz_minuteswest; /* minutes W of Greenwich */ int tz_dsttime; /* type of dst correction */ }; int gettimeofday(struct timeval* tv, struct timezone* tz) { FILETIME ft; unsigned __int64 tmpres = 0; static int tzflag; if (NULL != tv) { GetSystemTimeAsFileTime(&ft); tmpres |= ft.dwHighDateTime; tmpres <<= 32; tmpres |= ft.dwLowDateTime; /*converting file time to unix epoch*/ tmpres /= 10; /*convert into microseconds*/ tmpres -= DELTA_EPOCH_IN_MICROSECS; tv->tv_sec = (long)(tmpres / 1000000UL); tv->tv_usec = (long)(tmpres % 1000000UL); } if (NULL != tz) { if (!tzflag) { _tzset(); tzflag++; } tz->tz_minuteswest = _timezone / 60; tz->tz_dsttime = _daylight; } return 0; } #else /* Non-Windows */ #include <unistd.h> #include <sys/time.h> #include <sys/resource.h> #endif #include <cblas.h> #include <lapacke.h> #include <plasma.h> #include <core_blas.h> #include "flops.h" #include "timing.h" #include "auxiliary.h" #include <omp.h> static int RunTest(int *iparam, _PREC *dparam, double *t_); double cWtime(void); int ISEED[4] = {0,0,0,1}; /* initial seed for zlarnv() */ /* * struct timeval {time_t tv_sec; suseconds_t tv_usec;}; */ double cWtime(void) { struct timeval tp; gettimeofday( &tp, NULL ); return tp.tv_sec + 1e-6 * tp.tv_usec; } static int Test(int64_t n, int *iparam) { int i, j, iter; int thrdnbr, niter; int64_t M, N, K, NRHS; double *t; _PREC eps = _LAMCH( 'e' ); _PREC dparam[IPARAM_DNBPARAM]; double fmuls, fadds, fp_per_mul, fp_per_add; double sumgf, sumgf2, sumt, sd, flops, gflops; char *s; char *env[] = { "OMP_NUM_THREADS", "MKL_NUM_THREADS", "GOTO_NUM_THREADS", "ACML_NUM_THREADS", "ATLAS_NUM_THREADS", "BLAS_NUM_THREADS", "" }; int gnuplot = 0; memset( &dparam, 0, IPARAM_DNBPARAM * sizeof(_PREC) ); thrdnbr = iparam[IPARAM_THRDNBR]; niter = iparam[IPARAM_NITER]; M = iparam[IPARAM_M]; N = iparam[IPARAM_N]; K = iparam[IPARAM_K]; NRHS = K; (void)M;(void)N;(void)K;(void)NRHS; if ( (n < 0) || (thrdnbr < 0 ) ) { if (gnuplot) { printf( "set title '%d_NUM_THREADS: ", thrdnbr ); for (i = 0; env[i][0]; ++i) { s = getenv( env[i] ); if (i) printf( " " ); /* separating space */ for (j = 0; j < 5 && env[i][j] && env[i][j] != '_'; ++j) printf( "%c", env[i][j] ); if (s) printf( "=%s", s ); else printf( "->%s", "?" ); } printf( "'\n" ); printf( "%s\n%s\n%s\n%s\n%s%s%s\n", "set xlabel 'Matrix size'", "set ylabel 'Gflop/s'", "set key bottom", gnuplot > 1 ? "set terminal png giant\nset output 'timeplot.png'" : "", "plot '-' using 1:5 title '", _NAME, "' with linespoints" ); } return 0; } printf( "%7d %7d %7d ", iparam[IPARAM_M], iparam[IPARAM_N], iparam[IPARAM_K] ); fflush( stdout ); t = (double*)malloc(niter*sizeof(double)); memset(t, 0, niter*sizeof(double)); if (sizeof(_TYPE) == sizeof(_PREC)) { fp_per_mul = 1; fp_per_add = 1; } else { fp_per_mul = 6; fp_per_add = 2; } fadds = (double)(_FADDS); fmuls = (double)(_FMULS); flops = 1e-9 * (fmuls * fp_per_mul + fadds * fp_per_add); gflops = 0.0; if ( iparam[IPARAM_WARMUP] ) { RunTest( iparam, dparam, &(t[0])); } sumgf = 0.0; sumgf2 = 0.0; sumt = 0.0; for (iter = 0; iter < niter; iter++) { if( iter == 0 ) { if ( iparam[IPARAM_TRACE] ) iparam[IPARAM_TRACE] = 2; if ( iparam[IPARAM_DAG] ) iparam[IPARAM_DAG] = 2; RunTest( iparam, dparam, &(t[iter])); iparam[IPARAM_TRACE] = 0; iparam[IPARAM_DAG] = 0; } else RunTest( iparam, dparam, &(t[iter])); gflops = flops / t[iter]; sumt += t[iter]; sumgf += gflops; sumgf2 += gflops*gflops; } gflops = sumgf / niter; sd = sqrt((sumgf2 - (sumgf*sumgf)/niter)/niter); if ( iparam[IPARAM_CHECK] ) printf( "%9.3f %9.2f %9.2f %8.5e %8.5e %8.5e %8.5e %8.5e\n", sumt/niter, gflops, sd, dparam[IPARAM_RES], dparam[IPARAM_ANORM], dparam[IPARAM_XNORM], dparam[IPARAM_BNORM], dparam[IPARAM_RES] / n / eps / (dparam[IPARAM_ANORM] * dparam[IPARAM_XNORM] + dparam[IPARAM_BNORM] )); else{ printf( "%9.3f %9.2f %9.2f\n", sumt/niter, gflops, sd ); } fflush( stdout ); free(t); return 0; } static int startswith(const char *s, const char *prefix) { size_t n = strlen( prefix ); if (strncmp( s, prefix, n )) return 0; return 1; } static int get_range(char *range, int *start_p, int *stop_p, int *step_p) { char *s, *s1, buf[21]; int colon_count, copy_len, nbuf=20, n; int start=1000, stop=10000, step=1000; colon_count = 0; for (s = strchr( range, ':'); s; s = strchr( s+1, ':')) colon_count++; if (colon_count == 0) { /* No colon in range. */ if (sscanf( range, "%d", &start ) < 1 || start < 1) return -1; step = start / 10; if (step < 1) step = 1; stop = start + 10 * step; } else if (colon_count == 1) { /* One colon in range.*/ /* First, get the second number (after colon): the stop value. */ s = strchr( range, ':' ); if (sscanf( s+1, "%d", &stop ) < 1 || stop < 1) return -1; /* Next, get the first number (before colon): the start value. */ n = s - range; copy_len = n > nbuf ? nbuf : n; strncpy( buf, range, copy_len ); buf[copy_len] = 0; if (sscanf( buf, "%d", &start ) < 1 || start > stop || start < 1) return -1; /* Let's have 10 steps or less. */ step = (stop - start) / 10; if (step < 1) step = 1; } else if (colon_count == 2) { /* Two colons in range. */ /* First, get the first number (before the first colon): the start value. */ s = strchr( range, ':' ); n = s - range; copy_len = n > nbuf ? nbuf : n; strncpy( buf, range, copy_len ); buf[copy_len] = 0; if (sscanf( buf, "%d", &start ) < 1 || start < 1) return -1; /* Next, get the second number (after the first colon): the stop value. */ s1 = strchr( s+1, ':' ); n = s1 - (s + 1); copy_len = n > nbuf ? nbuf : n; strncpy( buf, s+1, copy_len ); buf[copy_len] = 0; if (sscanf( buf, "%d", &stop ) < 1 || stop < start) return -1; /* Finally, get the third number (after the second colon): the step value. */ if (sscanf( s1+1, "%d", &step ) < 1 || step < 1) return -1; } else return -1; *start_p = start; *stop_p = stop; *step_p = step; return 0; } static void show_help(char *prog_name) { printf( "Usage:\n%s [options]\n\n", prog_name ); printf( "Options are:\n" " --help Show this help\n" "\n" " --threads=X Number of CPU workers (default: _SC_NPROCESSORS_ONLN)\n" "\n" " --[a]sync Enable/Disable synchronous calls in wrapper function such as POTRI. (default: async)\n" " --[no]check Check result (default: nocheck)\n" " --[no]inv Check on inverse (default: noinv)\n" " --[no]warmup Perform a warmup run to pre-load libraries (default: warmup)\n" #if defined(PLASMA_EZTRACE) " --[no]trace Enable/Disable trace generation (default: notrace)\n" #endif " --[no]dag Enable/Disable DAG generation (default: nodag)\n" " Generates a dot_dag_file.dot.\n" " --[no]atun Activate autotuning (default: noatun) [Deprecated]\n" " --inplace Enable layout conversion inplace for lapack interface timers (default: enable)\n" " --outplace Enable layout conversion out of place for lapack interface timers (default: disable)\n" "\n" " --n_range=R Range of N values\n" " with R=Start:Stop:Step (default: 500:5000:500)\n" " --m=X dimension (M) of the matrices (default: N)\n" " --k=X dimension (K) of the matrices (default: 1)\n" " --nrhs=X Number of right-hand size (default: 1)\n" " --nb=N Nb size. (default: 128)\n" " --ib=N IB size. (default: 32)\n" "\n" " --niter=N Number of iterations performed for each test (default: 1)\n" "\n" " --rhblk=N If N > 0, enable Householder mode for QR and LQ factorization\n" " N is the size of each subdomain (default: 0)\n" " --tntmode=x Factorization used to select the pivots in the tournament pivoting algorithm (default: 1)\n" " 1 - LU factorization with partial pivoting\n" " 2 - QR rank revealing factorization\n" " --tntsize=N If N > 0, number of tiles grouped together during the tournament (default=4)\n" "\n" " Options specific to the conversion format timings xgetri and xgecfi:\n" " --ifmt Input format. (default: 0)\n" " --ofmt Output format. (default: 1)\n" " The possible values are:\n" " 0 - PlasmaCM, Column major\n" " 1 - PlasmaCCRB, Column-Colum rectangular block\n" " 2 - PlasmaCRRB, Column-Row rectangular block\n" " 3 - PlasmaRCRB, Row-Colum rectangular block\n" " 4 - PlasmaRRRB, Row-Row rectangular block\n" " 5 - PlasmaRM, Row Major\n" " --thrdbypb Number of threads per subproblem for inplace transformation (default: 1)\n" "\n"); } static void print_header(char *prog_name, int * iparam) { _PREC eps = _LAMCH( 'e' ); printf( "#\n" "# PLASMA %d.%d.%d, %s\n" "# Nb threads: %d\n" "# NB: %d\n" "# IB: %d\n" "# eps: %e\n" "#\n", PLASMA_VERSION_MAJOR, PLASMA_VERSION_MINOR, PLASMA_VERSION_MICRO, prog_name, iparam[IPARAM_THRDNBR], iparam[IPARAM_NB], iparam[IPARAM_IB], eps ); if (iparam[IPARAM_CHECK] ) printf( "# M N K/NRHS seconds Gflop/s Deviation" " ||Ax-b|| ||A|| ||x|| ||b|| ||Ax-b||/N/eps/(||A||||x||+||b||)\n" ); else printf( "# M N K/NRHS seconds Gflop/s Deviation\n" ); return; } static void get_thread_count(int *thrdnbr) { #if defined WIN32 || defined WIN64 sscanf( getenv( "NUMBER_OF_PROCESSORS" ), "%d", thrdnbr ); #else *thrdnbr = sysconf(_SC_NPROCESSORS_ONLN); #endif } int main(int argc, char *argv[]) { int i, m, mx, nx; int start = 500; int stop = 5000; int step = 500; int iparam[IPARAM_SIZEOF]; memset(iparam, 0, IPARAM_SIZEOF*sizeof(int)); iparam[IPARAM_THRDNBR ] = 1; iparam[IPARAM_THRDNBR_SUBGRP] = 1; iparam[IPARAM_SCHEDULER ] = 1; iparam[IPARAM_RUNTIME ] = 2; iparam[IPARAM_M ] = -1; iparam[IPARAM_N ] = 500; iparam[IPARAM_K ] = 500; iparam[IPARAM_LDA ] = 500; iparam[IPARAM_LDB ] = 500; iparam[IPARAM_LDC ] = 500; iparam[IPARAM_MB ] = 128; iparam[IPARAM_NB ] = 128; iparam[IPARAM_IB ] = 32; iparam[IPARAM_NITER ] = 1; iparam[IPARAM_WARMUP ] = 1; iparam[IPARAM_CHECK ] = 1; iparam[IPARAM_VERBOSE ] = 1; iparam[IPARAM_AUTOTUNING ] = 1; iparam[IPARAM_INPUTFMT ] = 0; iparam[IPARAM_OUTPUTFMT ] = 0; iparam[IPARAM_TRACE ] = 0; iparam[IPARAM_DAG ] = 0; iparam[IPARAM_ASYNC ] = 1; iparam[IPARAM_MX ] = -1; iparam[IPARAM_NX ] = -1; iparam[IPARAM_RHBLK ] = 0; iparam[IPARAM_TNTPIV_MODE ] = PLASMA_TOURNAMENT_LU; iparam[IPARAM_TNTPIV_SIZE ] = 4; iparam[IPARAM_INPLACE ] = PLASMA_OUTOFPLACE; get_thread_count( &(iparam[IPARAM_THRDNBR]) ); for (i = 1; i < argc && argv[i]; ++i) { if (startswith( argv[i], "--help" )) { show_help( argv[0] ); return EXIT_SUCCESS; } else if (startswith( argv[i], "--threads=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%d", &(iparam[IPARAM_THRDNBR]) ); } else if (startswith( argv[i], "--check" )) { iparam[IPARAM_CHECK] = 1; } else if (startswith( argv[i], "--nocheck" )) { iparam[IPARAM_CHECK] = 0; } else if (startswith( argv[i], "--warmup" )) { iparam[IPARAM_WARMUP] = 1; } else if (startswith( argv[i], "--nowarmup" )) { iparam[IPARAM_WARMUP] = 0; } else if (startswith( argv[i], "--dyn" )) { iparam[IPARAM_SCHEDULER] = 1; } else if (startswith( argv[i], "--nodyn" )) { iparam[IPARAM_SCHEDULER] = 0; } else if (startswith( argv[i], "--quark" )) { iparam[IPARAM_RUNTIME] = 1; } else if (startswith( argv[i], "--ompss" )) { iparam[IPARAM_RUNTIME] = 2; /* } else if (startswith( argv[i], "--atun" )) { */ /* iparam[IPARAM_AUTOTUNING] = 1; */ /* } else if (startswith( argv[i], "--noatun" )) { */ /* iparam[IPARAM_AUTOTUNING] = 0; */ } else if (startswith( argv[i], "--trace" )) { iparam[IPARAM_TRACE] = 1; } else if (startswith( argv[i], "--notrace" )) { iparam[IPARAM_TRACE] = 0; } else if (startswith( argv[i], "--dag" )) { iparam[IPARAM_DAG] = 1; } else if (startswith( argv[i], "--nodag" )) { iparam[IPARAM_DAG] = 0; } else if (startswith( argv[i], "--sync" )) { iparam[IPARAM_ASYNC] = 0; } else if (startswith( argv[i], "--async" )) { iparam[IPARAM_ASYNC] = 1; } else if (startswith( argv[i], "--n_range=" )) { get_range( strchr( argv[i], '=' ) + 1, &start, &stop, &step ); } else if (startswith( argv[i], "--m=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%d", &(iparam[IPARAM_M]) ); } else if (startswith( argv[i], "--n=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%d", &(iparam[IPARAM_N]) ); start = iparam[IPARAM_N]; stop = iparam[IPARAM_N]; step = 1; } else if (startswith( argv[i], "--nb=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%d", &(iparam[IPARAM_NB]) ); iparam[IPARAM_MB] = iparam[IPARAM_NB]; } else if (startswith( argv[i], "--nrhs=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%d", &(iparam[IPARAM_K]) ); } else if (startswith( argv[i], "--k=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%d", &(iparam[IPARAM_K]) ); } else if (startswith( argv[i], "--ib=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%d", &(iparam[IPARAM_IB]) ); } else if (startswith( argv[i], "--ifmt=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%d", &(iparam[IPARAM_INPUTFMT]) ); } else if (startswith( argv[i], "--ofmt=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%d", &(iparam[IPARAM_OUTPUTFMT]) ); } else if (startswith( argv[i], "--thrdbypb=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%d", &(iparam[IPARAM_THRDNBR_SUBGRP]) ); } else if (startswith( argv[i], "--niter=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%d", &iparam[IPARAM_NITER] ); } else if (startswith( argv[i], "--mx=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%d", &(iparam[IPARAM_MX]) ); } else if (startswith( argv[i], "--nx=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%d", &(iparam[IPARAM_NX]) ); } else if (startswith( argv[i], "--rhblk=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%d", &(iparam[IPARAM_RHBLK]) ); } else if (startswith( argv[i], "--tntmode=" )) { int tmp; sscanf( strchr( argv[i], '=' ) + 1, "%d", &tmp ); iparam[IPARAM_TNTPIV_MODE] = (tmp == 1) ? PLASMA_TOURNAMENT_LU : PLASMA_TOURNAMENT_QR; } else if (startswith( argv[i], "--tntsize=" )) { sscanf( strchr( argv[i], '=' ) + 1, "%d", &(iparam[IPARAM_TNTPIV_SIZE]) ); } else if (startswith( argv[i], "--inplace" )) { iparam[IPARAM_INPLACE] = PLASMA_INPLACE; } else if (startswith( argv[i], "--outplace" )) { iparam[IPARAM_INPLACE] = PLASMA_OUTOFPLACE; } else { fprintf( stderr, "Unknown option: %s\n", argv[i] ); } } m = iparam[IPARAM_M]; mx = iparam[IPARAM_MX]; nx = iparam[IPARAM_NX]; /* Initialize Plasma */ if ( iparam[IPARAM_RUNTIME] == PLASMA_QUARK ) PLASMA_Runtime_Init(omp_get_num_threads(), PLASMA_QUARK); else PLASMA_Runtime_Init(omp_get_num_threads(), PLASMA_OMPSS); if ( iparam[IPARAM_SCHEDULER] ){ PLASMA_Set(PLASMA_SCHEDULING_MODE, PLASMA_DYNAMIC_SCHEDULING ); if ( iparam[IPARAM_RUNTIME] == PLASMA_QUARK ) PLASMA_Set(PLASMA_RUNTIME_MODE, PLASMA_QUARK ); else PLASMA_Set(PLASMA_RUNTIME_MODE, PLASMA_OMPSS ); } else PLASMA_Set(PLASMA_SCHEDULING_MODE, PLASMA_STATIC_SCHEDULING ); /* if ( !iparam[IPARAM_AUTOTUNING] ) { */ PLASMA_Disable(PLASMA_AUTOTUNING); PLASMA_Set(PLASMA_TILE_SIZE, iparam[IPARAM_NB] ); PLASMA_Set(PLASMA_INNER_BLOCK_SIZE, iparam[IPARAM_IB] ); /* } else { */ /* PLASMA_Get(PLASMA_TILE_SIZE, &iparam[IPARAM_NB] ); */ /* PLASMA_Get(PLASMA_INNER_BLOCK_SIZE, &iparam[IPARAM_IB] ); */ /* } */ /* Householder mode */ if (iparam[IPARAM_RHBLK] < 1) { PLASMA_Set(PLASMA_HOUSEHOLDER_MODE, PLASMA_FLAT_HOUSEHOLDER); } else { PLASMA_Set(PLASMA_HOUSEHOLDER_MODE, PLASMA_TREE_HOUSEHOLDER); PLASMA_Set(PLASMA_HOUSEHOLDER_SIZE, iparam[IPARAM_RHBLK]); } /* Tournament pivoting */ PLASMA_Set(PLASMA_TNTPIVOTING_MODE, iparam[IPARAM_TNTPIV_MODE]); PLASMA_Set(PLASMA_TNTPIVOTING_SIZE, iparam[IPARAM_TNTPIV_SIZE]); /* Layout conversion */ PLASMA_Set(PLASMA_TRANSLATION_MODE, iparam[IPARAM_INPLACE]); print_header( argv[0], iparam); if (step < 1) step = 1; Test( -1, iparam ); /* print header */ for (i = start; i <= stop; i += step) { if ( nx > 0 ) { iparam[IPARAM_M] = i; iparam[IPARAM_N] = max(1, i/nx); } else if ( mx > 0 ) { iparam[IPARAM_M] = max(1, i/mx); iparam[IPARAM_N] = i; } else { if ( m == -1 ) iparam[IPARAM_M] = i; iparam[IPARAM_N] = i; } Test( iparam[IPARAM_N], iparam ); } PLASMA_Finalize(); /* if (gnuplot) { */ /* printf( "%s\n%s\n", */ /* "e", */ /* gnuplot > 1 ? "" : "pause 10" ); */ /* } */ return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.5111185182, "avg_line_length": 34.8275290216, "ext": "c", "hexsha": "6b9e6ad663fb1b9c4e1ca302feeba16c5890442e", "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": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "timing/timing.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "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": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "timing/timing.c", "max_line_length": 125, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "timing/timing.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6448, "size": 21001 }
/* multifit/gsl_multifit.h * * Copyright (C) 2000, 2007 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_MULTIFIT_H__ #define __GSL_MULTIFIT_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_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.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 n; /* number of observations */ size_t p; /* number of parameters */ gsl_matrix * A; gsl_matrix * Q; gsl_matrix * QSI; gsl_vector * S; gsl_vector * t; gsl_vector * xt; gsl_vector * D; } gsl_multifit_linear_workspace; GSL_FUN gsl_multifit_linear_workspace * gsl_multifit_linear_alloc (size_t n, size_t p); GSL_FUN void gsl_multifit_linear_free (gsl_multifit_linear_workspace * work); GSL_FUN int gsl_multifit_linear (const gsl_matrix * X, const gsl_vector * y, gsl_vector * c, gsl_matrix * cov, double * chisq, gsl_multifit_linear_workspace * work); GSL_FUN int gsl_multifit_linear_svd (const gsl_matrix * X, const gsl_vector * y, double tol, size_t * rank, gsl_vector * c, gsl_matrix * cov, double *chisq, gsl_multifit_linear_workspace * work); GSL_FUN int gsl_multifit_wlinear (const gsl_matrix * X, const gsl_vector * w, const gsl_vector * y, gsl_vector * c, gsl_matrix * cov, double * chisq, gsl_multifit_linear_workspace * work); GSL_FUN int gsl_multifit_wlinear_svd (const gsl_matrix * X, const gsl_vector * w, const gsl_vector * y, double tol, size_t * rank, gsl_vector * c, gsl_matrix * cov, double *chisq, gsl_multifit_linear_workspace * work); GSL_FUN int gsl_multifit_linear_est (const gsl_vector * x, const gsl_vector * c, const gsl_matrix * cov, double *y, double *y_err); GSL_FUN int gsl_multifit_linear_residuals (const gsl_matrix *X, const gsl_vector *y, const gsl_vector *c, gsl_vector *r); __END_DECLS #endif /* __GSL_MULTIFIT_H__ */
{ "alphanum_fraction": 0.58585588, "avg_line_length": 31.1083333333, "ext": "h", "hexsha": "401c2cb0bcabead87f652cd28154e622679a71ea", "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": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_path": "deps/include/gsl/gsl_multifit.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "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": "berkus/music-cs", "max_issues_repo_path": "deps/include/gsl/gsl_multifit.h", "max_line_length": 82, "max_stars_count": null, "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_path": "deps/include/gsl/gsl_multifit.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 844, "size": 3733 }
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_histogram.h> #include"mpi.h" const double PI = 3.14159; double rz(double red); struct galaxy { double x, y, z, d, w; }; int main (int argc, char **argv) { FILE * DD; FILE * PP; FILE * RR; const int Nr = 150; const int Nm = 100; const double RMIN = 0.0; const double RMAX = 150.0; const double RSTEP = 1.0; const double MSTEP = 0.01; const int maxNgal = 40000000; int dummy; char DDname[400]; char PPname[400]; char RRname[400]; int i; int bit; int bittot; int *n; sprintf(DDname,argv[1]); sprintf(RRname,argv[2]); sprintf(PPname,argv[3]); struct galaxy * gald; struct galaxy * galr; double * DRcount; double * DRcount_in_place; gald = (struct galaxy*)malloc(maxNgal*sizeof(struct galaxy)); galr = (struct galaxy*)malloc(maxNgal*sizeof(struct galaxy)); DRcount = (double*)calloc(Nr*Nm,sizeof(double)); DRcount_in_place = (double*)calloc(Nr*Nm,sizeof(double)); struct galaxy * galpd, * galpr; galpd = gald; galpr = galr; DD = fopen(DDname,"r"); RR = fopen(RRname,"r"); double ra, dec, red, dist; double dd; int Nd = 0; double weight; double ddummy; int indexFKP; double weightFKP; double weight1, weight2, weight3, weight4; char line [2000]; int N = 0; double sumW = 0; double sumW_in_place = 0; for (int i = 0; i < 0; i ++) { fgets (line, 2000, DD); printf("%s\n", line); } while (fscanf(DD,"%lf %lf %lf\n",&ra,&dec,&red) != EOF) { ra *= PI/180.0; dec *= PI/180.0; dist = rz(red); galpd->x = dist*cos(dec)*cos(ra); galpd->y = dist*cos(dec)*sin(ra); galpd->z = dist*sin(dec); galpd->d = dist; // galpd->w = weight1 * weight2; galpd++; Nd++; } fclose(DD); N = 0; for (int i = 0; i < 0; i ++) { fgets (line, 2000, RR); printf("%s\n", line); } while (fscanf(RR,"%le %le %le\n",&ra,&dec,&red) != EOF) { ra *= PI/180.0; dec *= PI/180.0; dist = rz(red); galpr->x = dist*cos(dec)*cos(ra); galpr->y = dist*cos(dec)*sin(ra); galpr->z = dist*sin(dec); galpr->d = dist; // galpr->w = weight1 * weight2; galpr++; N++; } fclose(RR); MPI_Init (&argc, &argv); int numproc; int totproc; MPI_Comm_rank (MPI_COMM_WORLD, &numproc); MPI_Comm_size (MPI_COMM_WORLD, &totproc); n = (int *) calloc(totproc + 1, sizeof(int)); n[0] = 1; for (i = 1; i < totproc; i++) { n[i] = (int)floor(double(N)/totproc*i); } n[totproc] = N; bit = n[numproc]; bittot = n[numproc + 1]; sprintf(PPname, "%s.DR",PPname); double mu; double d1, d2, d3; double x1, y1, z1, x2, y2, z2, gd1, gd2, w1, w2; double r2, rat; double xb, yb, zb, db2; double rr; galpd = gald; int j; for (i = 0; i < Nd; i++) { x1 = galpd->x; y1 = galpd->y; z1 = galpd->z; gd1 = galpd->d; //w1 = galpd->w; galpr = galr + bit; for (j = bit; j < bittot; j++) { x2 = galpr->x; y2 = galpr->y; z2 = galpr->z; gd2 = galpr->d; //w2 = galpr->w; //sumW += w1*w2; sumW += 1.0; d1 = x1 - x2; d2 = y1 - y2; d3 = z1 - z2; r2 = d1*d1 + d2*d2 + d3*d3; if (r2 > RMAX*RMAX || r2 < RMIN*RMIN) { galpr++; continue; } rat = gd1/gd2; xb = x1 + x2*rat; yb = y1 + y2*rat; zb = z1 + z2*rat; db2 = xb*xb + yb*yb + zb*zb; mu = fabs((xb*d1 + yb*d2 + zb*d3)/sqrt(r2)/sqrt(db2)); rr = sqrt(r2); int binr = (int)((rr - RMIN)/RSTEP); int binm = (int)(mu/MSTEP); if (binr >= 0 && binm >= 0 && binr < Nr && binm < Nm){ int ind = binr + Nr*binm; // DRcount[ind] += w1*w2; DRcount[ind] += 1.0; } galpr++; } galpd++; } free(gald); free(galr); free(n); MPI_Reduce(DRcount, DRcount_in_place, Nr*Nm, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); MPI_Reduce(&sumW, &sumW_in_place, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); printf("weighted number = %le %d\n", sumW, numproc); if (numproc == 0) { PP = fopen(PPname,"w"); printf("%s\n", PPname); fprintf(PP,"# weighted number: %lf\n",sumW_in_place); fprintf(PP,"# RBINS: %d\n", Nr); fprintf(PP,"# MBINS: %d\n", Nm); int k, l; for (k = 0; k < Nm; k++) { for (l = 0; l < Nr; l++) { fprintf(PP,"%lf ",DRcount_in_place[k*Nr + l]); } fprintf(PP,"\n"); } fclose(PP); } free(DRcount); free(DRcount_in_place); MPI_Finalize (); return 0; } double f (double x, void * p) { double Om = 0.310; double ff = 2997.92458/sqrt(Om*(1.0 + x)*(1.0 + x)*(1.0 + x) + 1.0 - Om); return ff; } double rz (double red) { gsl_integration_workspace * w = gsl_integration_workspace_alloc(1000); double result, error; gsl_function F; F.function = &f; gsl_integration_qags(&F, 0, red, 0, 1e-7, 1000, w, &result, &error); gsl_integration_workspace_free (w); return result; }
{ "alphanum_fraction": 0.5510245078, "avg_line_length": 22.7305936073, "ext": "c", "hexsha": "073cde0737835744e8f1e0d067129369c3fc3f5b", "lang": "C", "max_forks_count": 13, "max_forks_repo_forks_event_max_datetime": "2022-02-22T09:24:38.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-26T17:30:10.000Z", "max_forks_repo_head_hexsha": "205ce48a288acacbd41358e6d0215f4aff355049", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "echaussidon/LSS", "max_forks_repo_path": "backup/DRpar.c", "max_issues_count": 13, "max_issues_repo_head_hexsha": "205ce48a288acacbd41358e6d0215f4aff355049", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:29:06.000Z", "max_issues_repo_issues_event_min_datetime": "2017-10-26T22:06:24.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "echaussidon/LSS", "max_issues_repo_path": "backup/DRpar.c", "max_line_length": 87, "max_stars_count": 8, "max_stars_repo_head_hexsha": "205ce48a288acacbd41358e6d0215f4aff355049", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "echaussidon/LSS", "max_stars_repo_path": "backup/DRpar.c", "max_stars_repo_stars_event_max_datetime": "2022-01-04T08:54:18.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-12T14:52:26.000Z", "num_tokens": 1859, "size": 4978 }
/* -*- coding: utf-8; mode: c++; tab-width: 2; -*- ------------------------- Interface/declaration file for GramSchmidt.cpp ------------------------------------------------------------------------- */ #ifndef GRAMSCHMIDT_H #define GRAMSCHMIDT_H #include <vector> #include <numeric> #include <algorithm> #include <cblas.h> #include <lapacke.h> #include <iostream> // TO DO: Improve performance with CBLAS/LAPACKE for large size x // std::vector<double> v; // double* a = &v[0]; // int GramSchmidt(size_t, size_t, void*, void*); int GramSchmidt(size_t, size_t, double*, double*); // int GramSchmidt(std::vector<std::vector<double>>, std::vector<std::vector<double>>); #endif
{ "alphanum_fraction": 0.5932452276, "avg_line_length": 28.375, "ext": "h", "hexsha": "db3caa6fb2c7e059b57529ea37df68e155fda95f", "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": "04b5278ff4d754d6e62f955d49bddf6509f86e73", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "pranjal-s/cpp17", "max_forks_repo_path": "Parallel-Cpp-MPI-OpenMP/chapter2GramSchmidt/src/GramSchmidt.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "04b5278ff4d754d6e62f955d49bddf6509f86e73", "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": "pranjal-s/cpp17", "max_issues_repo_path": "Parallel-Cpp-MPI-OpenMP/chapter2GramSchmidt/src/GramSchmidt.h", "max_line_length": 87, "max_stars_count": null, "max_stars_repo_head_hexsha": "04b5278ff4d754d6e62f955d49bddf6509f86e73", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "pranjal-s/cpp17", "max_stars_repo_path": "Parallel-Cpp-MPI-OpenMP/chapter2GramSchmidt/src/GramSchmidt.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 171, "size": 681 }
/***************************************************************************** * * Rokko: Integrated Interface for libraries of eigenvalue decomposition * * Copyright (C) 2012-2015 Rokko Developers https://github.com/t-sakashita/rokko * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) * *****************************************************************************/ #ifndef ROKKO_PBLAS_INTERFACE_H #define ROKKO_PBLAS_INTERFACE_H #include <lapacke.h> #undef I #include <rokko/mangling.h> /* PvCOPY */ #define PBLAS_PCOPY_DECL(NAMES, NAMEL, TYPE) \ void ROKKO_GLOBAL(NAMES, NAMEL) (const int* N, const TYPE * X, const int* IX, const int* JX, const int* DESCX, const int* INCX, TYPE * Y, const int* IY, int* JY, const int* DESCY, const int* INCY); #ifdef __cplusplus extern "C" { #endif PBLAS_PCOPY_DECL(pscopy, PSCOPY, float); PBLAS_PCOPY_DECL(pdcopy, PDCOPY, double); PBLAS_PCOPY_DECL(pccopy, PCCOPY, lapack_complex_float); PBLAS_PCOPY_DECL(pzcopy, PZCOPY, lapack_complex_double); #ifdef __cplusplus } #endif #undef PBLAS_PCOPY_DECL /* PvDOT, PvDOTU, PvDOTC */ #define PBLAS_PDOT_DECL(NAMES, NAMEL, TYPE) \ void ROKKO_GLOBAL(NAMES, NAMEL) (const int* N, TYPE * DOT, const TYPE * X, const int* IX, const int* JX, const int* DESCX, const int* INCX, const TYPE * Y, const int* IY, const int* JY, const int* DESCY, const int* INCY); #ifdef __cplusplus extern "C" { #endif PBLAS_PDOT_DECL(psdot, PSDOT, float); PBLAS_PDOT_DECL(pddot, PDDOT, double); PBLAS_PDOT_DECL(pcdotu, PCDOTU, lapack_complex_float); PBLAS_PDOT_DECL(pzdotu, PZDOTU, lapack_complex_double); PBLAS_PDOT_DECL(pcdotc, PCDOTC, lapack_complex_float); PBLAS_PDOT_DECL(pzdotc, PZDOTC, lapack_complex_double); #ifdef __cplusplus } #endif #undef PBLAS_PDOT_DECL /* PvGEMV */ #define PBLAS_PGEMV_DECL(NAMES, NAMEL, TYPE) \ void ROKKO_GLOBAL(NAMES, NAMEL) (const char* TRANS, const int* M, const int* N, const TYPE * ALPHA, const TYPE * A, const int* IA, const int* JA, const int* DESCA, const TYPE * X, const int* IX, const int* JX, const int* DESCX, const int* INCX, const TYPE * BETA, TYPE * Y, const int* IY, const int* JY, const int* DESCY, const int* INCY); #ifdef __cplusplus extern "C" { #endif PBLAS_PGEMV_DECL(psgemv, PSGEMV, float); PBLAS_PGEMV_DECL(pdgemv, PDGEMV, double); PBLAS_PGEMV_DECL(pcgemv, PCGEMV, lapack_complex_float); PBLAS_PGEMV_DECL(pzgemv, PZGEMV, lapack_complex_double); #ifdef __cplusplus } #endif #undef PBLAS_PGEMV_DECL /* PvGEMM */ #define PBLAS_PGEMM_DECL(NAMES, NAMEL, TYPE) \ void ROKKO_GLOBAL(NAMES, NAMEL) (const char* TRANSA, const char* TRANSB, const int* M, const int* N, const int* K, const TYPE * ALPHA, const TYPE * A, const int* IA, const int* JA, const int* DESCA, const TYPE * B, const int* IB, const int* JB, const int* DESCB, const TYPE * BETA, TYPE * C, const int* IC, const int* JC, const int* DESCC); #ifdef __cplusplus extern "C" { #endif PBLAS_PGEMM_DECL(psgemm, PSGEMM, float); PBLAS_PGEMM_DECL(pdgemm, PDGEMM, double); PBLAS_PGEMM_DECL(pcgemm, PCGEMM, lapack_complex_float); PBLAS_PGEMM_DECL(pzgemm, PZGEMM, lapack_complex_double); #ifdef __cplusplus } #endif #undef PBLAS_PGEMM_DECL #endif // ROKKO_PBLAS_INTERFACE_H
{ "alphanum_fraction": 0.7132330365, "avg_line_length": 31.931372549, "ext": "h", "hexsha": "e737325add76107da819b72ef69ac5ab1f311ad9", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-06-01T07:10:01.000Z", "max_forks_repo_forks_event_min_datetime": "2015-06-16T04:22:23.000Z", "max_forks_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "t-sakashita/rokko", "max_forks_repo_path": "rokko/pblas/pblas_interface.h", "max_issues_count": 514, "max_issues_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_issues_repo_issues_event_max_datetime": "2021-06-25T09:29:52.000Z", "max_issues_repo_issues_event_min_datetime": "2015-02-05T14:56:54.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "t-sakashita/rokko", "max_issues_repo_path": "rokko/pblas/pblas_interface.h", "max_line_length": 340, "max_stars_count": 16, "max_stars_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "t-sakashita/rokko", "max_stars_repo_path": "rokko/pblas/pblas_interface.h", "max_stars_repo_stars_event_max_datetime": "2022-03-18T19:04:49.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-31T18:57:48.000Z", "num_tokens": 1057, "size": 3257 }
#include <petsc.h> #undef __FUNCT__ #define __FUNCT__ "main" int main(int argc,char **args) { PetscErrorCode ierr; PetscInitialize(&argc,&args,(char*)0,(char*)0); ierr = PetscPrintf(PETSC_COMM_WORLD," === Hello from Petsc! ===\n");CHKERRQ(ierr); ierr = PetscFinalize(); return 0; }
{ "alphanum_fraction": 0.6666666667, "avg_line_length": 16.6666666667, "ext": "c", "hexsha": "3c59dc23a738a7c19c234989acabf10c3956e40f", "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": "64f4e067d173b1ad7d54bd1fa1a6ec2ba5c47eac", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lukaspospisil/hello_petsc", "max_forks_repo_path": "with_makefile/hellopetsc.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "64f4e067d173b1ad7d54bd1fa1a6ec2ba5c47eac", "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": "lukaspospisil/hello_petsc", "max_issues_repo_path": "with_makefile/hellopetsc.c", "max_line_length": 84, "max_stars_count": null, "max_stars_repo_head_hexsha": "64f4e067d173b1ad7d54bd1fa1a6ec2ba5c47eac", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lukaspospisil/hello_petsc", "max_stars_repo_path": "with_makefile/hellopetsc.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 86, "size": 300 }
#include <stdio.h> #include <stdarg.h> #include <string.h> #include <math.h> #include <gbpLib.h> #include <gbpRNG.h> #include <gbpMCMC.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_fit.h> #include <gsl/gsl_interp.h> void read_MCMC_configuration(MCMC_info *MCMC, char *filename_output_dir, int chain) { SID_log("Reading the configuration of chain #%d from {%s}...", SID_LOG_OPEN, chain); // Set the names of the files we have to read char filename_chain_dir[SID_MAX_FILENAME_LENGTH]; char filename_run[SID_MAX_FILENAME_LENGTH]; char filename_chain_config[SID_MAX_FILENAME_LENGTH]; sprintf(filename_chain_dir, "%s/chains/", filename_output_dir); sprintf(filename_run, "%s/run.dat", filename_output_dir); sprintf(filename_chain_config, "%s/chain_config_%06d.dat", filename_chain_dir, chain); // Read the run file to do some sanity checks int n_chains; int n_avg; int flag_autocor_on; int flag_no_map_write; int n_P; FILE *fp; fp = fopen(filename_run, "r"); SID_fread_verify(&n_chains, sizeof(int), 1, fp); SID_fread_verify(&n_avg, sizeof(int), 1, fp); SID_fread_verify(&flag_autocor_on, sizeof(int), 1, fp); SID_fread_verify(&flag_no_map_write, sizeof(int), 1, fp); SID_fread_verify(&n_P, sizeof(int), 1, fp); fclose(fp); if(n_P != MCMC->n_P) SID_exit_error("The number of parameters for the two runs does not match (ie. %d!=%d)", SID_ERROR_LOGIC, n_P, MCMC->n_P); if(chain >= n_chains) SID_exit_error("Invalid chain number (ie. %d>%d)", SID_ERROR_LOGIC, chain, n_chains); // Read the configuration file int n_iterations_file_total; int n_iterations_file_burn; double *V; double temperature; V = (double *)SID_malloc(sizeof(double) * n_P * n_P); fp = fopen(filename_chain_config, "r"); SID_fread_verify(&n_iterations_file_total, sizeof(int), 1, fp); SID_fread_verify(&n_iterations_file_burn, sizeof(int), 1, fp); SID_fread_verify(V, sizeof(double), n_P * n_P, fp); SID_fread_verify(&temperature, sizeof(double), 1, fp); fclose(fp); // Set the new state set_MCMC_covariance(MCMC, V); set_MCMC_temperature(MCMC, temperature); // Clean-up SID_free(SID_FARG V); SID_log("Done.", SID_LOG_CLOSE); }
{ "alphanum_fraction": 0.6835769561, "avg_line_length": 36.34375, "ext": "c", "hexsha": "da83c70c9aecee1af8cb1576898562aa76baf1db", "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/read_MCMC_configuration.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/read_MCMC_configuration.c", "max_line_length": 117, "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/read_MCMC_configuration.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": 659, "size": 2326 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include <gbpInterpolate.h> void init_interpolate(double *x, double *y, size_t n, const gsl_interp_type *T, interp_info **interp) { size_t i; (*interp) = (interp_info *)malloc(sizeof(interp_info)); (*interp)->n = n; (*interp)->x = (double *)malloc(sizeof(double) * n); (*interp)->y = (double *)malloc(sizeof(double) * n); (*interp)->T = T; // If the x-array is not in ascending order, switch it if(x[0] < x[n - 1]) { for(i = 0; i < n; i++) { (*interp)->x[i] = x[i]; (*interp)->y[i] = y[i]; } } else { for(i = 0; i < n; i++) { (*interp)->x[i] = x[n - 1 - i]; (*interp)->y[i] = y[n - 1 - i]; } } (*interp)->accel = gsl_interp_accel_alloc(); (*interp)->interp = gsl_interp_alloc(T, n); gsl_interp_init((*interp)->interp, (const double *)(*interp)->x, (const double *)(*interp)->y, (*interp)->n); }
{ "alphanum_fraction": 0.5287356322, "avg_line_length": 33.6774193548, "ext": "c", "hexsha": "62f2339c5f3cd4f03b7f7e4c3ccbed04604f5efb", "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/init_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/init_interpolate.c", "max_line_length": 113, "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/init_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": 318, "size": 1044 }
/** * * @file core_zlacpy.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.6.0 * @author Julien Langou * @author Henricus Bouwmeester * @author Mathieu Faverge * @date 2010-11-15 * @precisions normal z -> c d s * **/ #include <lapacke.h> #include "common.h" /***************************************************************************//** * * @ingroup CORE_PLASMA_Complex64_t * * CORE_PLASMA_zlacpycopies all or part of a two-dimensional matrix A to another * matrix B * ******************************************************************************* * * @param[in] uplo * Specifies the part of the matrix A to be copied to B. * = PlasmaUpperLower: All the matrix A * = PlasmaUpper: Upper triangular part * = PlasmaLower: Lower triangular part * * @param[in] M * The number of rows of the matrices A and B. M >= 0. * * @param[in] N * The number of columns of the matrices A and B. N >= 0. * * @param[in] A * The M-by-N matrix to copy. * * @param[in] LDA * The leading dimension of the array A. LDA >= max(1,M). * * @param[out] B * The M-by-N copy of the matrix A. * On exit, B = A ONLY in the locations specified by uplo. * * @param[in] LDB * The leading dimension of the array B. LDB >= max(1,M). * ******************************************************************************/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_zlacpy = PCORE_zlacpy #define CORE_zlacpy PCORE_zlacpy #endif void CORE_zlacpy(PLASMA_enum uplo, int M, int N, const PLASMA_Complex64_t *A, int LDA, PLASMA_Complex64_t *B, int LDB) { LAPACKE_zlacpy_work( LAPACK_COL_MAJOR, lapack_const(uplo), M, N, A, LDA, B, LDB); }
{ "alphanum_fraction": 0.5382231405, "avg_line_length": 28.4705882353, "ext": "c", "hexsha": "fbac2ef0f97244d018c0ed521c8826cfbd9aa0e7", "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": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "core_blas/core_zlacpy.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "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": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "core_blas/core_zlacpy.c", "max_line_length": 81, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas/core_zlacpy.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 517, "size": 1936 }
/* * The MIT License is a permissive free software license, which permits reuse * within both open source and proprietary software. The software is licensed * as is, and no warranty is given as to fitness for purpose or absence of * infringement of third parties' rights, such as patents. Generally use for * research activities is allowed regardless of any third party patents, but * commercial use may be subject to a separate license. * * * The MIT License (MIT) * * Copyright (c) 2015 Tuomo Raitio * * 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. * * * * * <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> * GlottHMM Speech Parameter Extractor * <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> * * This program reads a speech file and extracts speech * parameters using glottal inverse filtering. * * This program has been written in Aalto University, * Department of Signal Processign and Acoustics, Espoo, Finland * * Author: Tuomo Raitio * Acknowledgements: Antti Suni, Paavo Alku, Martti Vainio * * File AnalysisFunctions.c * Version: 1.1 * /***********************************************/ /* INCLUDE */ /***********************************************/ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <sndfile.h> /* Read and write wav */ #include <gsl/gsl_vector.h> /* GNU, Vector */ #include <gsl/gsl_matrix.h> /* GNU, Matrix */ #include <gsl/gsl_fft_real.h> /* GSL, FFT */ #include <gsl/gsl_permutation.h> /* GSL, Permutations */ #include <gsl/gsl_linalg.h> /* GSL, Linear algebra */ #include <gsl/gsl_spline.h> /* GSL, Interpolation */ #include <gsl/gsl_errno.h> /* GSL, Error handling */ #include <gsl/gsl_poly.h> /* GSL, Polynomials */ #include <gsl/gsl_sort_double.h> /* GSL, Sort double */ #include <gsl/gsl_sort_vector.h> /* GSL, Sort vector */ #include <gsl/gsl_complex.h> /* GSL, Complex numbers */ #include <gsl/gsl_complex_math.h> /* GSL, Arithmetic operations for complex numbers */ #include <gsl/gsl_fft_halfcomplex.h>/* GSL, FFT halfcomplex */ #include <gsl/gsl_fft_complex.h> #include <gsl/gsl_fit.h> /* GSL, Linear regression */ #include <gsl/gsl_multifit.h> /* GSL, Higher order linear fitting */ #include <libconfig.h> /* Configuration file */ #include "AnalysisFunctions.h" /** * Function Check_command_line * * Check command line format and print instructions * * @param argc number of input arguments */ int Check_command_line(int argc) { /* Check command line format */ if (argc < 3 || argc > 4) { printf("\n<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>\n"); printf(" GlottHMM - Speech Parameter Extractor (%s)\n",VERSION); printf("<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>\n\n"); printf("Description:\n\n"); printf(" Extraction of speech signal into vocal tract filter and voice\n"); printf(" source parameters using glottal inverse filtering.\n\n"); printf("Usage:\n\n"); printf(" Analysis wav_file config_default config_user\n\n"); printf(" wav_file - Name of the audio file to be analysed\n"); printf(" config_default - Name of the default config file\n"); printf(" config_user - Name of the user config file (OPTIONAL) \n\n"); printf("Version:\n\n"); printf(" %s (%s)\n\n",VERSION,DATE); return EXIT_FAILURE; } else { /* Print program description */ printf("\n<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>\n"); printf(" Speech Parameter Extractor (%s)\n",VERSION); printf("<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>\n\n"); return EXIT_SUCCESS; } } /** * Function Read_config * * Read configuration file * * @param filename name of the configuration file * @return conf pointer to configuration structure */ struct config_t *Read_config(char *filename) { struct config_t *conf = (struct config_t *)malloc(sizeof(struct config_t)); config_init(conf); if(config_read_file(conf,filename) != CONFIG_TRUE) { printf("\nError reading configuration file \"%s\", line %i\n",filename,config_error_line(conf)); printf("%s\n",config_error_text(conf)); return NULL; } return conf; } /** * Function Assign_config_parameters * * Assign configuration parameters to variables. Destroy and free config file. * * @param conf config file * @param params parameter structure * @conf_type type of config file (def/usr) */ int Assign_config_parameters(struct config_t *conf, PARAM *params, int conf_type) { long int ival; double fval; const char *charval; int bool; /* Assign config parameters */ if (config_lookup(conf, SAMPLING_FREQUENCY) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", SAMPLING_FREQUENCY); return EXIT_FAILURE; } else if (config_lookup(conf, SAMPLING_FREQUENCY) != NULL) { config_lookup_int(conf, SAMPLING_FREQUENCY,&ival); params->FS = (int)ival; } if (config_lookup(conf, FRAME_LENGTH) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", FRAME_LENGTH); return EXIT_FAILURE; } else if (config_lookup(conf, FRAME_LENGTH) != NULL) { config_lookup_float(conf, FRAME_LENGTH,&fval); params->frame_length_ms = fval; } if (config_lookup(conf, UNVOICED_FRAME_LENGTH) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", UNVOICED_FRAME_LENGTH); return EXIT_FAILURE; } else if (config_lookup(conf, UNVOICED_FRAME_LENGTH) != NULL) { config_lookup_float(conf, UNVOICED_FRAME_LENGTH,&fval); params->unvoiced_frame_length_ms = fval; } if (config_lookup(conf, FRAME_SHIFT) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", FRAME_SHIFT); return EXIT_FAILURE; } else if (config_lookup(conf, FRAME_SHIFT) != NULL) { config_lookup_float(conf, FRAME_SHIFT,&fval); params->shift_ms = fval; } if (config_lookup(conf, LPC_ORDER) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", LPC_ORDER); return EXIT_FAILURE; } else if (config_lookup(conf, LPC_ORDER) != NULL) { config_lookup_int(conf, LPC_ORDER,&ival); params->lpc_order_vt = (int)ival; } if (config_lookup(conf, LPC_ORDER_SOURCE) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", LPC_ORDER_SOURCE); return EXIT_FAILURE; } else if (config_lookup(conf, LPC_ORDER_SOURCE) != NULL) { config_lookup_int(conf, LPC_ORDER_SOURCE,&ival); params->lpc_order_gl = (int)ival; } if (config_lookup(conf, DIFFERENTIAL_LSF) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", DIFFERENTIAL_LSF); return EXIT_FAILURE; } else if (config_lookup(conf, DIFFERENTIAL_LSF) != NULL) { config_lookup_bool(conf, DIFFERENTIAL_LSF,&bool); params->differential_lsf = bool; } if (config_lookup(conf, WARPING_VT) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", WARPING_VT); return EXIT_FAILURE; } else if (config_lookup(conf, WARPING_VT) != NULL) { config_lookup_float(conf, WARPING_VT,&fval); params->lambda_vt = fval; } if (config_lookup(conf, WARPING_GL) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", WARPING_GL); return EXIT_FAILURE; } else if (config_lookup(conf, WARPING_GL) != NULL) { config_lookup_float(conf, WARPING_GL,&fval); params->lambda_gl = fval; } if (config_lookup(conf, VOICING_THRESHOLD) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", VOICING_THRESHOLD); return EXIT_FAILURE; } else if (config_lookup(conf, VOICING_THRESHOLD) != NULL) { config_lookup_float(conf, VOICING_THRESHOLD,&fval); params->voicing_threshold = fval; } if (config_lookup(conf, ZCR_THRESHOLD) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", ZCR_THRESHOLD); return EXIT_FAILURE; } else if (config_lookup(conf, ZCR_THRESHOLD) != NULL) { config_lookup_float(conf, ZCR_THRESHOLD,&fval); params->ZCR = fval; } if (config_lookup(conf, F0_MIN) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", F0_MIN); return EXIT_FAILURE; } else if (config_lookup(conf, F0_MIN) != NULL) { config_lookup_float(conf, F0_MIN,&fval); params->fmin = fval; } if (config_lookup(conf, F0_MAX) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", F0_MAX); return EXIT_FAILURE; } else if (config_lookup(conf, F0_MAX) != NULL) { config_lookup_float(conf, F0_MAX,&fval); params->fmax = fval; } if (config_lookup(conf, USE_F0_POSTPROCESSING) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", USE_F0_POSTPROCESSING); return EXIT_FAILURE; } else if (config_lookup(conf, USE_F0_POSTPROCESSING) != NULL) { config_lookup_bool(conf, USE_F0_POSTPROCESSING,&bool); params->f0_postprocessing = bool; } if (config_lookup(conf, MAX_NUMBER_OF_PULSES) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", MAX_NUMBER_OF_PULSES); return EXIT_FAILURE; } else if (config_lookup(conf, MAX_NUMBER_OF_PULSES) != NULL) { config_lookup_int(conf, MAX_NUMBER_OF_PULSES,&ival); params->maxnumberofpulses = (int)ival; } if (config_lookup(conf, PULSEMAXLEN) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", PULSEMAXLEN); return EXIT_FAILURE; } else if (config_lookup(conf, PULSEMAXLEN) != NULL) { config_lookup_float(conf, PULSEMAXLEN,&fval); params->pulsemaxlen_ms = fval; } if (config_lookup(conf, RESAMPLED_PULSELEN) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", RESAMPLED_PULSELEN); return EXIT_FAILURE; } else if (config_lookup(conf, RESAMPLED_PULSELEN) != NULL) { config_lookup_float(conf, RESAMPLED_PULSELEN,&fval); params->rspulsemaxlen_ms = fval; } if (config_lookup(conf, WAVEFORM_SAMPLES) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", WAVEFORM_SAMPLES); return EXIT_FAILURE; } else if (config_lookup(conf, WAVEFORM_SAMPLES) != NULL) { config_lookup_int(conf, WAVEFORM_SAMPLES,&ival); params->waveform_samples = (int)ival; } if (config_lookup(conf, MAX_PULSE_LEN_DIFF) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", MAX_PULSE_LEN_DIFF); return EXIT_FAILURE; } else if (config_lookup(conf, MAX_PULSE_LEN_DIFF) != NULL) { config_lookup_float(conf, MAX_PULSE_LEN_DIFF,&fval); params->max_pulse_len_diff = fval; } if (config_lookup(conf, INVERT_SIGNAL) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", INVERT_SIGNAL); return EXIT_FAILURE; } else if (config_lookup(conf, INVERT_SIGNAL) != NULL) { config_lookup_bool(conf, INVERT_SIGNAL,&bool); params->invert_signal = bool; } if (config_lookup(conf, EXTRACT_PULSELIB) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", EXTRACT_PULSELIB); return EXIT_FAILURE; } else if (config_lookup(conf, EXTRACT_PULSELIB) != NULL) { config_lookup_bool(conf, EXTRACT_PULSELIB,&bool); params->extract_pulselib_params = bool; } if (config_lookup(conf, PITCH_SYNCHRONOUS_ANALYSIS) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", PITCH_SYNCHRONOUS_ANALYSIS); return EXIT_FAILURE; } else if (config_lookup(conf, PITCH_SYNCHRONOUS_ANALYSIS) != NULL) { config_lookup_bool(conf, PITCH_SYNCHRONOUS_ANALYSIS,&bool); params->pitch_synchronous_analysis = bool; } if (config_lookup(conf, F0_CHECK_RANGE) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", F0_CHECK_RANGE); return EXIT_FAILURE; } else if (config_lookup(conf, F0_CHECK_RANGE) != NULL) { config_lookup_int(conf, F0_CHECK_RANGE,&ival); params->f0_check_range = (int)ival; } if (config_lookup(conf, RELATIVE_F0_THRESHOLD) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", RELATIVE_F0_THRESHOLD); return EXIT_FAILURE; } else if (config_lookup(conf, RELATIVE_F0_THRESHOLD) != NULL) { config_lookup_float(conf, RELATIVE_F0_THRESHOLD,&fval); params->relative_f0_threshold = fval; } if (config_lookup(conf, F0_FRAME_LENGTH) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", F0_FRAME_LENGTH); return EXIT_FAILURE; } else if (config_lookup(conf, F0_FRAME_LENGTH) != NULL) { config_lookup_float(conf, F0_FRAME_LENGTH,&fval); params->f0_frame_length_ms = fval; } if (config_lookup(conf, LP_STABILIZED) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", LP_STABILIZED); return EXIT_FAILURE; } else if (config_lookup(conf, LP_STABILIZED) != NULL) { config_lookup_bool(conf, LP_STABILIZED,&bool); params->lp_stabilized = bool; } if (config_lookup(conf, USE_IAIF) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", USE_IAIF); return EXIT_FAILURE; } else if (config_lookup(conf, USE_IAIF) != NULL) { config_lookup_bool(conf, USE_IAIF,&bool); params->use_iaif = bool; } if (config_lookup(conf, LPC_ORDER_GL_IAIF) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", LPC_ORDER_GL_IAIF); return EXIT_FAILURE; } else if (config_lookup(conf, LPC_ORDER_GL_IAIF) != NULL) { config_lookup_int(conf, LPC_ORDER_GL_IAIF,&ival); params->lpc_order_gl_iaif = (int)ival; } if (config_lookup(conf, USE_MOD_IAIF) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", USE_MOD_IAIF); return EXIT_FAILURE; } else if (config_lookup(conf, USE_MOD_IAIF) != NULL) { config_lookup_bool(conf, USE_MOD_IAIF,&bool); params->use_mod_iaif = bool; } if (config_lookup(conf, HNR_CHANNELS) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", HNR_CHANNELS); return EXIT_FAILURE; } else if (config_lookup(conf, HNR_CHANNELS) != NULL) { config_lookup_int(conf, HNR_CHANNELS,&ival); params->hnr_channels = (int)ival; } if (config_lookup(conf, NUMBER_OF_HARMONICS) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", NUMBER_OF_HARMONICS); return EXIT_FAILURE; } else if (config_lookup(conf, NUMBER_OF_HARMONICS) != NULL) { config_lookup_int(conf, NUMBER_OF_HARMONICS,&ival); params->number_of_harmonics = (int)ival; } if (config_lookup(conf, FORMANT_PRE_ENH_LPC_DELTA) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", FORMANT_PRE_ENH_LPC_DELTA); return EXIT_FAILURE; } else if (config_lookup(conf, FORMANT_PRE_ENH_LPC_DELTA) != NULL) { config_lookup_float(conf, FORMANT_PRE_ENH_LPC_DELTA,&fval); params->formant_enh_lpc_delta = fval; } if (config_lookup(conf, FORMANT_PRE_ENH_COEFF) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", FORMANT_PRE_ENH_COEFF); return EXIT_FAILURE; } else if (config_lookup(conf, FORMANT_PRE_ENH_COEFF) != NULL) { config_lookup_float(conf, FORMANT_PRE_ENH_COEFF,&fval); params->formant_enh_coeff = fval; } if (config_lookup(conf, SEPARATE_VOICED_UNVOICED_SPECTRUM) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", SEPARATE_VOICED_UNVOICED_SPECTRUM); return EXIT_FAILURE; } else if (config_lookup(conf, SEPARATE_VOICED_UNVOICED_SPECTRUM) != NULL) { config_lookup_bool(conf, SEPARATE_VOICED_UNVOICED_SPECTRUM,&bool); params->sep_vuv_spectrum = bool; } if (config_lookup(conf, EXTRACT_SOURCE) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", EXTRACT_SOURCE); return EXIT_FAILURE; } else if (config_lookup(conf, EXTRACT_SOURCE) != NULL) { config_lookup_bool(conf, EXTRACT_SOURCE,&bool); params->extract_source = bool; } if (config_lookup(conf, HP_FILTERING) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", HP_FILTERING); return EXIT_FAILURE; } else if (config_lookup(conf, HP_FILTERING) != NULL) { config_lookup_bool(conf, HP_FILTERING,&bool); params->hp_filtering = bool; } if (config_lookup(conf, EXTRACT_F0) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", EXTRACT_F0); return EXIT_FAILURE; } else if (config_lookup(conf, EXTRACT_F0) != NULL) { config_lookup_bool(conf, EXTRACT_F0,&bool); params->extract_f0 = bool; } if (config_lookup(conf, EXTRACT_GAIN) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", EXTRACT_GAIN); return EXIT_FAILURE; } else if (config_lookup(conf, EXTRACT_GAIN) != NULL) { config_lookup_bool(conf, EXTRACT_GAIN,&bool); params->extract_gain = bool; } if (config_lookup(conf, EXTRACT_LSF) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", EXTRACT_LSF); return EXIT_FAILURE; } else if (config_lookup(conf, EXTRACT_LSF) != NULL) { config_lookup_bool(conf, EXTRACT_LSF,&bool); params->extract_lsf = bool; } if (config_lookup(conf, EXTRACT_LSFSOURCE) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", EXTRACT_LSFSOURCE); return EXIT_FAILURE; } else if (config_lookup(conf, EXTRACT_LSFSOURCE) != NULL) { config_lookup_bool(conf, EXTRACT_LSFSOURCE,&bool); params->extract_tilt = bool; } if (config_lookup(conf, EXTRACT_HNR) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", EXTRACT_HNR); return EXIT_FAILURE; } else if (config_lookup(conf, EXTRACT_HNR) != NULL) { config_lookup_bool(conf, EXTRACT_HNR,&bool); params->extract_hnr = bool; } if (config_lookup(conf, EXTRACT_HARMONICS) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", EXTRACT_HARMONICS); return EXIT_FAILURE; } else if (config_lookup(conf, EXTRACT_HARMONICS) != NULL) { config_lookup_bool(conf, EXTRACT_HARMONICS,&bool); params->extract_harmonics = bool; } if (config_lookup(conf, EXTRACT_H1H2) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", EXTRACT_H1H2); return EXIT_FAILURE; } else if (config_lookup(conf, EXTRACT_H1H2) != NULL) { config_lookup_bool(conf, EXTRACT_H1H2,&bool); params->extract_h1h2 = bool; } if (config_lookup(conf, EXTRACT_NAQ) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", EXTRACT_NAQ); return EXIT_FAILURE; } else if (config_lookup(conf, EXTRACT_NAQ) != NULL) { config_lookup_bool(conf, EXTRACT_NAQ,&bool); params->extract_naq = bool; } if (config_lookup(conf, EXTRACT_WAVEFORM) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", EXTRACT_WAVEFORM); return EXIT_FAILURE; } else if (config_lookup(conf, EXTRACT_WAVEFORM) != NULL) { config_lookup_bool(conf, EXTRACT_WAVEFORM,&bool); params->extract_waveform = bool; } if (config_lookup(conf, EXTRACT_INFOFILE) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", EXTRACT_INFOFILE); return EXIT_FAILURE; } else if (config_lookup(conf, EXTRACT_INFOFILE) != NULL) { config_lookup_bool(conf, EXTRACT_INFOFILE,&bool); params->extract_info = bool; } if (config_lookup(conf, USE_EXTERNAL_F0) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", USE_EXTERNAL_F0); return EXIT_FAILURE; } else if (config_lookup(conf, USE_EXTERNAL_F0) != NULL) { config_lookup_bool(conf, USE_EXTERNAL_F0,&bool); params->use_external_f0 = bool; } if (config_lookup(conf, NOISE_REDUCTION_ANALYSIS) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", NOISE_REDUCTION_ANALYSIS); return EXIT_FAILURE; } else if (config_lookup(conf, NOISE_REDUCTION_ANALYSIS) != NULL) { config_lookup_bool(conf, NOISE_REDUCTION_ANALYSIS,&bool); params->noise_reduction_analysis = bool; } if (config_lookup(conf, NOISE_REDUCTION_LIMIT_DB) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", NOISE_REDUCTION_LIMIT_DB); return EXIT_FAILURE; } else if (config_lookup(conf, NOISE_REDUCTION_LIMIT_DB) != NULL) { config_lookup_float(conf, NOISE_REDUCTION_LIMIT_DB,&fval); params->noise_reduction_limit_db = fval; } if (config_lookup(conf, NOISE_REDUCTION_DB) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", NOISE_REDUCTION_DB); return EXIT_FAILURE; } else if (config_lookup(conf, NOISE_REDUCTION_DB) != NULL) { config_lookup_float(conf, NOISE_REDUCTION_DB,&fval); params->noise_reduction_db = fval; } if (config_lookup(conf, LOG_F0) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", LOG_F0); return EXIT_FAILURE; } else if (config_lookup(conf, LOG_F0) != NULL) { config_lookup_bool(conf, LOG_F0,&bool); params->logf0 = bool; } if (config_lookup(conf, EXTRACT_ONLY_UNIQUE_PULSES) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", EXTRACT_ONLY_UNIQUE_PULSES); return EXIT_FAILURE; } else if (config_lookup(conf, EXTRACT_ONLY_UNIQUE_PULSES) != NULL) { config_lookup_bool(conf, EXTRACT_ONLY_UNIQUE_PULSES,&bool); params->extract_only_unique_pulses = bool; } if (config_lookup(conf, EXTRACT_ONE_PULSE_PER_FRAME) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", EXTRACT_ONE_PULSE_PER_FRAME); return EXIT_FAILURE; } else if (config_lookup(conf, EXTRACT_ONE_PULSE_PER_FRAME) != NULL) { config_lookup_bool(conf, EXTRACT_ONE_PULSE_PER_FRAME,&bool); params->extract_one_pulse_per_frame = bool; } if (config_lookup(conf, EXTRACT_FFT_SPECTRA) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", EXTRACT_FFT_SPECTRA); return EXIT_FAILURE; } else if (config_lookup(conf, EXTRACT_FFT_SPECTRA) != NULL) { config_lookup_bool(conf, EXTRACT_FFT_SPECTRA,&bool); params->write_fftspectra_to_file = bool; } if (config_lookup(conf, UNVOICED_PRE_EMPHASIS) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", UNVOICED_PRE_EMPHASIS); return EXIT_FAILURE; } else if (config_lookup(conf, UNVOICED_PRE_EMPHASIS) != NULL) { config_lookup_bool(conf, UNVOICED_PRE_EMPHASIS,&bool); params->unvoiced_pre_emphasis = bool; } /* Data format */ if (config_lookup(conf, DATA_FORMAT) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n",DATA_FORMAT); return EXIT_FAILURE; } else if (config_lookup(conf, DATA_FORMAT) != NULL) { config_lookup_string(conf,DATA_FORMAT,&charval); if(strcmp(charval,DATA_FORMAT_ASCII) == 0) params->data_format = DATA_FORMAT_ID_ASCII; else if(strcmp(charval,DATA_FORMAT_BINARY) == 0) params->data_format = DATA_FORMAT_ID_BINARY; else { printf("\nError: Invalid configuration value \"%s\".\n", DATA_FORMAT); return EXIT_FAILURE; } } /* LP method */ if (config_lookup(conf, LP_METHOD) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n",LP_METHOD); return EXIT_FAILURE; } else if (config_lookup(conf, LP_METHOD) != NULL) { config_lookup_string(conf,LP_METHOD,&charval); if(strcmp(charval,LP_METHOD_LPC) == 0) params->lp_method = LP_METHOD_ID_LPC; else if(strcmp(charval,LP_METHOD_WLP) == 0) params->lp_method = LP_METHOD_ID_WLP; else if(strcmp(charval,LP_METHOD_XLP) == 0) params->lp_method = LP_METHOD_ID_XLP; else { printf("\nError: Invalid configuration value \"%s\".\n", LP_METHOD); return EXIT_FAILURE; } } /* LP weighting method */ if (config_lookup(conf, LP_WEIGHTING) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n",LP_WEIGHTING); return EXIT_FAILURE; } else if (config_lookup(conf, LP_WEIGHTING) != NULL) { config_lookup_string(conf,LP_WEIGHTING,&charval); if(strcmp(charval,LP_WEIGHTING_STE) == 0) params->lp_weighting = LP_WEIGHTING_ID_STE; else if(strcmp(charval,LP_WEIGHTING_GCI) == 0) params->lp_weighting = LP_WEIGHTING_ID_GCI; else { printf("\nError: Invalid configuration value \"%s\".\n", LP_WEIGHTING); return EXIT_FAILURE; } } /* Formant enhancement method */ if (config_lookup(conf, FORMANT_PRE_ENH_METHOD) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n",FORMANT_PRE_ENH_METHOD); return EXIT_FAILURE; } else if (config_lookup(conf, FORMANT_PRE_ENH_METHOD) != NULL) { config_lookup_string(conf,FORMANT_PRE_ENH_METHOD,&charval); if(strcmp(charval,FORMANT_ENH_LSF) == 0) params->formant_enh_method = FORMANT_ENH_ID_LSF; else if(strcmp(charval,FORMANT_ENH_LPC) == 0) params->formant_enh_method = FORMANT_ENH_ID_LPC; else if(strcmp(charval,FORMANT_ENH_NONE) == 0) params->formant_enh_method = FORMANT_ENH_ID_NONE; else { printf("\nError: Invalid configuration value \"%s\".\n", FORMANT_PRE_ENH_METHOD); return EXIT_FAILURE; } } /* High-pass filter filename */ if (config_lookup(conf, HPFILTER_FILENAME) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n",HPFILTER_FILENAME); return EXIT_FAILURE; } else if (config_lookup(conf, HPFILTER_FILENAME) != NULL) { if(conf_type == USR_CONF) // Free default free(params->hpfilter_filename); config_lookup_string(conf,HPFILTER_FILENAME,&charval); params->hpfilter_filename = (char *)malloc((strlen(charval)+1)*sizeof(char)); strcpy(params->hpfilter_filename,charval); } /* External F0 filename */ if (config_lookup(conf, EXTERNAL_F0_FILENAME) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n",EXTERNAL_F0_FILENAME); return EXIT_FAILURE; } else if (config_lookup(conf, EXTERNAL_F0_FILENAME) != NULL) { if(conf_type == USR_CONF) // Free default free(params->external_f0_filename); config_lookup_string(conf,EXTERNAL_F0_FILENAME,&charval); params->external_f0_filename = (char *)malloc((strlen(charval)+1)*sizeof(char)); strcpy(params->external_f0_filename,charval); } /* Convert milliseconds to samples */ params->frame_length = rint(params->FS*params->frame_length_ms/1000); params->shift = rint(params->FS*params->shift_ms/1000); params->pulsemaxlen = rint(params->FS*params->pulsemaxlen_ms/1000); params->rspulsemaxlen = rint(params->FS*params->rspulsemaxlen_ms/1000); params->f0_frame_length = rint(params->FS*params->f0_frame_length_ms/1000); params->unvoiced_frame_length = rint(params->FS*params->unvoiced_frame_length_ms/1000); /* Free memory */ config_destroy(conf); free(conf); return EXIT_SUCCESS; } /** * Function Check_parameter_validity * * Check the validity of parameters * * @param filename name of the configuration file */ int Check_parameter_validity(PARAM *params) { if(params->lpc_order_gl < 3) { printf("\nError: The degree of the source spectral model is too low!\n\n");return EXIT_FAILURE;} if(params->f0_frame_length_ms < 1000/params->fmin) { printf("\nError: F0 frame length is too short with respect to the lowest F0 value!\n\n");return EXIT_FAILURE;} if(params->lambda_vt < -1 || params->lambda_vt > 1) { printf("\nError: Vocal tract warping coefficient must be a value in the range [-1,1]!\n\n");return EXIT_FAILURE;} if(params->lambda_gl < -1 || params->lambda_gl > 1) { printf("\nError: Voice source warping coefficient must be a value in the range [-1,1]!\n\n");return EXIT_FAILURE;} if(params->f0_frame_length_ms/1000*params->FS > FFT_LENGTH_LONG) { printf("\nError: F0 frame length greater than FFT length!\n\n");return EXIT_FAILURE;} if(params->frame_length_ms/1000*params->FS > FFT_LENGTH) { printf("\nError: Frame length greater than FFT length!\n\n");return EXIT_FAILURE;} if(params->unvoiced_frame_length > params->frame_length) { printf("\nError: Unvoiced frame length is greater than overall frame length!\n\n");return EXIT_FAILURE;} return EXIT_SUCCESS; } /** * Function Read_soundfile * * Read soundfile to vector. Also specify sampling frequency, number of frames, and signal length. * Invert signal if required. * * @param filename * @return signal */ gsl_vector *Read_soundfile(char *filename, PARAM *params) { /* Initialize */ int i; SNDFILE *soundfile; SF_INFO sfinfo; sfinfo.frames = 0; sfinfo.samplerate = 0; sfinfo.channels = 0; sfinfo.format = 0; sfinfo.sections = 0; sfinfo.seekable = 0; /* Open soundfile */ soundfile = sf_open(filename, SFM_READ, &sfinfo); if(soundfile == NULL) { fprintf(stderr, "\nError: Cannot open file \"%s\".\n", filename); return NULL; } /* Check sampling frequency */ if(params->FS != sfinfo.samplerate) { printf("\nError: Sampling frequency of the sound file is different than indicated in config file (%i Hz vs %i Hz)\n\n",(int)sfinfo.samplerate,params->FS); return NULL; } /* Count the number of frames that fits to the signal (round to next integer) */ params->n_frames = ceil(sfinfo.frames/(double)params->shift-(double)params->frame_length/(double)params->shift)+1; params->signal_length = (params->n_frames + params->frame_length/(double)params->shift - 1)*(double)params->shift; /* Read sound file into vector */ gsl_vector *signal = gsl_vector_calloc(params->signal_length); double *temp = (double *)calloc(sfinfo.frames, sizeof(double)); sf_read_double(soundfile, temp, sfinfo.frames); for(i=0; i<sfinfo.frames; i++) gsl_vector_set(signal, i, temp[i]); sf_close(soundfile); free(temp); /* Invert signal if required */ if(params->invert_signal == 1) { for(i=0;i<signal->size;i++) gsl_vector_set(signal,i,-gsl_vector_get(signal,i)); } /* Return signal vector */ return signal; } /** * Function HP_Filter * * High-pass filter signal * * @param signal pointer to the samples */ int HighPassFilter(gsl_vector *signal, PARAM *params) { /* Do not filter if not requested */ if(params->hp_filtering == 0) { free(params->hpfilter_filename); return EXIT_SUCCESS; } /* Evaluate filter coefficient file length */ int n = EvalFileLength(params->hpfilter_filename); if(n == -1) return EXIT_FAILURE; /* Open file */ FILE *filter = fopen(params->hpfilter_filename, "r"); if(!filter) { printf("Error opening file \"%s\": %s\n", params->hpfilter_filename, strerror(errno)); return EXIT_FAILURE; } /* Initialize */ int i,j; double sum; gsl_vector *temp = gsl_vector_calloc(signal->size); gsl_vector *coeffs = gsl_vector_alloc(n); /* Read coefficients from file */ gsl_vector_fscanf(filter,coeffs); /* Filter signal */ for(i=0; i<signal->size; i++) { sum = 0; for(j=0; j<=GSL_MIN(i, n-1); j++) { sum += gsl_vector_get(signal,i-j)*gsl_vector_get(coeffs,j); } gsl_vector_set(temp, GSL_MAX(i-(n-1)/2,0), sum); } /* Copy "temp" samples to "signal" */ for(i=0; i<signal->size; i++) { gsl_vector_set(signal, i, gsl_vector_get(temp, i)); } /* Free memory */ gsl_vector_free(temp); gsl_vector_free(coeffs); fclose(filter); free(params->hpfilter_filename); return EXIT_SUCCESS; } /** * Function Read_external_f0 * * Read external F0 file. * * -Interpolate if required. * -Remove some samples in the beginning and in the end of the vector * due to the windowing scheme used in Analysis. * * @param fundf pointer to f0 vector * @param params */ int Read_external_f0(gsl_vector **fundf, PARAM *params) { /* Do not read if not requested, allocate normal f0 vector */ if(params->use_external_f0 == 0) { *(fundf) = gsl_vector_alloc(params->n_frames); free(params->external_f0_filename); return EXIT_SUCCESS; } /* Evaluate external f0 file length */ int n = EvalFileLength(params->external_f0_filename); if(n == -1) return EXIT_FAILURE; /* Open file */ FILE *f0_file = fopen(params->external_f0_filename, "r"); if(!f0_file) { printf("Error opening file \"%s\": %s\n", params->external_f0_filename, strerror(errno)); return EXIT_FAILURE; } /* Read f0 from file */ gsl_vector *f0_raw = gsl_vector_alloc(n); gsl_vector_fscanf(f0_file,f0_raw); /* Interpolate to a specific length (n_frames + 2*empty_frames */ int empty_frames = rint((params->frame_length/(double)params->shift - 1)/2); gsl_vector *f0_new = gsl_vector_alloc(params->n_frames + 2*empty_frames); if(n != params->n_frames + 2*empty_frames) { printf("External F0 is not the same length (%i) as required (%i).\n",n,params->n_frames + 2*empty_frames); printf("Apply interpolation to get correct length!\n\n"); Interpolate(f0_raw,f0_new); int i; for(i=0;i<f0_new->size;i++) // Remove possible bad values if(gsl_vector_get(f0_new,i) < params->fmin) gsl_vector_set(f0_new,i,0); } else { gsl_vector_memcpy(f0_new,f0_raw); } /* Remove "empty frames" in the beginning and in the end of the vector */ gsl_vector *f0 = gsl_vector_alloc(params->n_frames); int i; for(i=0;i<f0->size;i++) gsl_vector_set(f0,i,gsl_vector_get(f0_new,i+empty_frames)); /* Set pointer */ *(fundf) = f0; /* Free memory */ fclose(f0_file); free(params->external_f0_filename); gsl_vector_free(f0_raw); gsl_vector_free(f0_new); return EXIT_SUCCESS; } /** * Function EvalFileLength * * Read file and count the number of lines * * @param name filename * @return number of parameters or -1 if file could not be opened */ int EvalFileLength(const char *name) { FILE *file; char s[DEF_STRING_LEN]; int ind; /* Open file */ file = fopen(name, "r"); if(!file) { printf("Error opening file \"%s\": %s\n", name, strerror(errno)); return -1; } /* Read lines until EOF */ ind = 0; while(fscanf(file,"%s",s) != EOF) ind++; fclose(file); return ind; } /** * Function Print_progress * * Print progress of the analysis * * @param index time index * @param n_frames total number of frames * @param audio file name * @param FS sampling frequency */ void Print_progress(int index, int n_frames, char *filename, int FS) { int idx = 0; if(index == 0) printf("Extracting parameters from \"%s\" (%i Hz)\n\n", filename, FS); if(index % GSL_MAX((n_frames-1)/PROGRESS_UPDATE_INTERVAL,1) == 0) { idx = rint(100.0*index/(double)(n_frames-1)); if(idx != 100) printf("%i %%\n", idx); } if(index == n_frames-1) printf("100 %%\n"); } /** * Function Allocate_variables * * Allocate memory for variables * * @param ... */ void Allocate_variables(gsl_vector **frame, gsl_vector **frame0, gsl_vector **glottal, gsl_vector **gain, gsl_vector **uvgain, gsl_vector **f0_frame, gsl_vector **glottal_f0, gsl_vector **f0_frame0, gsl_vector **glottsig, gsl_vector **glottsig_f0, gsl_vector **source_signal, gsl_matrix **fundf_candidates, gsl_matrix **LSF, gsl_matrix **LSF2, gsl_matrix **bp_gain, gsl_matrix **spectral_tilt, gsl_matrix **HNR, gsl_matrix **waveform, gsl_matrix **harmonics, gsl_vector **h1h2, gsl_vector **naq, gsl_matrix **fftmatrix_vt, gsl_matrix **fftmatrix_src, gsl_matrix **fftmatrix_uv, PARAM *params) { /* Allocate vector */ *(source_signal) = gsl_vector_calloc(params->signal_length); *(frame) = gsl_vector_alloc(params->frame_length); *(frame0) = gsl_vector_calloc(params->lpc_order_vt); *(glottal) = gsl_vector_alloc(params->frame_length); *(glottsig) = gsl_vector_alloc(params->frame_length); *(glottsig_f0) = gsl_vector_alloc(params->f0_frame_length); *(gain) = gsl_vector_alloc(params->n_frames); *(uvgain) = gsl_vector_alloc(params->n_frames); *(h1h2) = gsl_vector_calloc(params->n_frames); *(naq) = gsl_vector_calloc(params->n_frames); *(f0_frame) = gsl_vector_calloc(params->f0_frame_length); *(f0_frame0) = gsl_vector_calloc(params->lpc_order_vt); *(glottal_f0) = gsl_vector_alloc(params->f0_frame_length); /* Allocate matrices */ *(fundf_candidates) = gsl_matrix_calloc(params->n_frames, NUMBER_OF_F0_CANDIDATES); *(spectral_tilt) = gsl_matrix_calloc(params->n_frames, params->lpc_order_gl); *(LSF) = gsl_matrix_calloc(params->n_frames, params->lpc_order_vt); *(LSF2) = gsl_matrix_calloc(params->n_frames, params->lpc_order_vt); *(HNR) = gsl_matrix_calloc(params->n_frames, params->hnr_channels); *(bp_gain) = gsl_matrix_calloc(params->n_frames, GAIN_FREQUENCY_BANDS); *(waveform) = gsl_matrix_calloc(params->n_frames,params->waveform_samples); *(harmonics) = gsl_matrix_calloc(params->n_frames,params->number_of_harmonics); *(fftmatrix_vt) = gsl_matrix_calloc(params->n_frames,OUTPUT_FFT_LENGTH/2); *(fftmatrix_src) = gsl_matrix_calloc(params->n_frames,OUTPUT_FFT_LENGTH/2); *(fftmatrix_uv) = gsl_matrix_calloc(params->n_frames,OUTPUT_FFT_LENGTH/2); } /** * Function Allocate_pulselib_variables * * Allocate memory for pulse library variables * * @param ... */ void Allocate_pulselib_variables(gsl_matrix **gpulses, gsl_matrix **gpulses_rs, gsl_vector **pulse_inds, gsl_vector **pulse_pos, gsl_vector **pulse_lengths, gsl_matrix **plsf, gsl_matrix **ptilt, gsl_matrix **pharm, gsl_matrix **phnr, gsl_matrix **pwaveform, gsl_vector **pgain, gsl_vector **ph1h2, gsl_vector **pnaq, PARAM *params) { /* Allocate parameters if used */ if(params->extract_pulselib_params == 1) { /* If pulse library parameters are used, allocate memory */ *(gpulses) = gsl_matrix_calloc(params->maxnumberofpulses,params->pulsemaxlen); *(gpulses_rs) = gsl_matrix_calloc(params->maxnumberofpulses,params->rspulsemaxlen); *(pulse_inds) = gsl_vector_calloc(params->maxnumberofpulses); *(pulse_pos) = gsl_vector_calloc(params->maxnumberofpulses); *(pulse_lengths) = gsl_vector_calloc(params->maxnumberofpulses); *(plsf) = gsl_matrix_calloc(params->maxnumberofpulses,params->lpc_order_vt); *(ptilt) = gsl_matrix_calloc(params->maxnumberofpulses,params->lpc_order_gl); *(pharm) = gsl_matrix_calloc(params->maxnumberofpulses,params->number_of_harmonics); *(phnr) = gsl_matrix_calloc(params->maxnumberofpulses,params->hnr_channels); *(pwaveform) = gsl_matrix_calloc(params->maxnumberofpulses,params->waveform_samples); *(pgain) = gsl_vector_calloc(params->maxnumberofpulses); *(ph1h2) = gsl_vector_calloc(params->maxnumberofpulses); *(pnaq) = gsl_vector_calloc(params->maxnumberofpulses); params->number_of_pulses = 0; } else { /* Set NULL if not used */ params->number_of_pulses = 0; *(gpulses) = NULL; *(gpulses_rs) = NULL; *(pulse_inds) = NULL; *(pulse_pos) = NULL; *(pulse_lengths) = NULL; *(plsf) = NULL; *(ptilt) = NULL; *(pharm) = NULL; *(phnr) = NULL; *(pwaveform) = NULL; *(pgain) = NULL; *(ph1h2) = NULL; *(pnaq) = NULL; } } /** * Function Get_samples_to_frames * * Get samples to frames * * @param frame pointer to signal vector * @param frame pointer to main frame * @param frame0 pointer to pre-frame * @param frame pointer to f0 frame * @param frame0 pointer to f0 pre-frame * @param shift size * @parame index time */ void Get_samples_to_frames(gsl_vector *signal, gsl_vector *frame, gsl_vector *frame0, gsl_vector *f0_frame, gsl_vector *f0_frame0, int shift, int index) { /* Initialize */ int i; int frame_length = frame->size; int f0_frame_length = f0_frame->size; int lpc_order_vt = frame0->size; int signal_length = signal->size; /* Get samples to frame */ for(i=0; i<frame_length; i++) gsl_vector_set(frame, i, gsl_vector_get(signal, index*shift+i)); /* Get pre-frame samples for smooth filtering */ for(i=0; i<lpc_order_vt; i++) { if(index*shift+i-lpc_order_vt >= 0) gsl_vector_set(frame0, i, gsl_vector_get(signal, index*shift+i-lpc_order_vt)); else gsl_vector_set(frame0, i, 0); } /* Get f0_frame and f0_frame0 (longer frame) */ /* In the beginning of the signal */ if(index*shift - ceil(f0_frame_length/2.0) + ceil(frame_length/2.0) < 0) { for(i=0; i<f0_frame_length; i++) gsl_vector_set(f0_frame, i, gsl_vector_get(signal, i)); gsl_vector_set_zero(f0_frame0); /* In the end of the signal */ } else if(index*shift + ceil(f0_frame_length/2.0) + ceil(frame_length/2.0) > signal_length-1) { for(i=0; i<f0_frame_length; i++) gsl_vector_set(f0_frame, i, gsl_vector_get(signal, signal->size-f0_frame_length+i)); for(i=0; i<lpc_order_vt; i++) gsl_vector_set(f0_frame0, i, gsl_vector_get(signal, signal->size-f0_frame_length+i-lpc_order_vt)); /* Between */ } else { for(i=0; i<f0_frame_length; i++) gsl_vector_set(f0_frame, i, gsl_vector_get(signal, index*shift-ceil(f0_frame_length/2.0)+ceil(frame_length/2.0)+i)); for(i=0; i<lpc_order_vt; i++) gsl_vector_set(f0_frame0, i, gsl_vector_get(signal, GSL_MAX(index*shift-ceil(f0_frame_length/2.0)+ceil(frame_length/2.0)+i-lpc_order_vt,0))); } } /** * Function Gain * * Calculate energy * * @param frame pointer to the samples * @param gain vector for results * @param index time index * @param windowing switch for using windowing */ void Gain(gsl_vector *frame, gsl_vector *gain, int index, int windowing) { int i; double sum; /* Windowing switch */ if(windowing == 1) { /* Windowing */ gsl_vector *wframe = gsl_vector_alloc(frame->size); for(i=0;i<frame->size;i++) gsl_vector_set(wframe,i,gsl_vector_get(frame,i)*HANN(i,frame->size)); /* Evaluate gain of frame, normalize energy per sample basis */ sum = 0; for(i=0;i<frame->size;i++) { sum = sum + gsl_vector_get(wframe,i)*gsl_vector_get(wframe,i); } gsl_vector_set(gain, index, 10.0*log10((8.0/3.0)*sum/E_REF/((double)(frame->size)))); /* Free memory */ gsl_vector_free(wframe); } else { /* Evaluate gain of frame, normalize energy per sample basis */ sum = 0; for(i=0;i<frame->size;i++) { sum = sum + gsl_vector_get(frame,i)*gsl_vector_get(frame,i); } gsl_vector_set(gain, index, 10.0*log10(sum/E_REF/((double)(frame->size)))); } /* Ensure non-infinity values */ if(isinf(gsl_vector_get(gain,index)) != 0) gsl_vector_set(gain,index,MIN_LOG_POWER); } /** * Function UnvoicedGain * * Calculate energy from potentially unvoiced frames (shorter window) * * @param frame pointer to the samples * @param gain vector for results * @param index time index * @param windowing switch for using windowing * @param unvoiced_frame_length */ void UnvoicedGain(gsl_vector *frame, gsl_vector *gain, int index, int windowing, int unvoiced_frame_length) { int i,cntr; double sum; gsl_vector *uvframe = gsl_vector_alloc(unvoiced_frame_length); /* Take shorter frame for unvoiced analysis */ cntr = rint((frame->size-unvoiced_frame_length)/2.0); for(i=0;i<unvoiced_frame_length;i++) gsl_vector_set(uvframe,i,gsl_vector_get(frame,i+cntr)); /* Windowing switch */ if(windowing == 1) { /* Windowing */ for(i=0;i<uvframe->size;i++) gsl_vector_set(uvframe,i,gsl_vector_get(uvframe,i)*HANN(i,uvframe->size)); /* Evaluate gain of uvframe, normalize energy per sample basis */ sum = 0; for(i=0;i<uvframe->size;i++) { sum = sum + gsl_vector_get(uvframe,i)*gsl_vector_get(uvframe,i); } gsl_vector_set(gain, index, 10.0*log10((8.0/3.0)*sum/E_REF/((double)(uvframe->size)))); } else { /* Evaluate gain of frame, normalize energy per sample basis */ sum = 0; for(i=0;i<uvframe->size;i++) { sum = sum + gsl_vector_get(uvframe,i)*gsl_vector_get(uvframe,i); } gsl_vector_set(gain, index, 10.0*log10(sum/E_REF/((double)(uvframe->size)))); } /* Ensure non-infinity values */ if(isinf(gsl_vector_get(gain,index)) != 0) gsl_vector_set(gain,index,MIN_LOG_POWER); /* Free memory */ gsl_vector_free(uvframe); } /** * Function BandPassGain * * Calculate bandpass gains from Fourier transform * * @param frame pointer to samples * @param bp_gain values to be saved * @param params parameter structure * @param index frame index * */ void BandPassGain(gsl_vector *frame, gsl_matrix *bp_gain, PARAM *params, int index) { int i; double data[FFT_LENGTH] = {0}; gsl_vector *fft = gsl_vector_calloc(FFT_LENGTH/2); /* FFT */ for (i=0; i<frame->size; i++) { data[i] = gsl_vector_get(frame,i); // No windowing here } gsl_fft_real_radix2_transform(data, 1, FFT_LENGTH); for(i=1; i<FFT_LENGTH/2; i++) { gsl_vector_set(fft, i, sqrt(pow(data[i], 2) + pow(data[FFT_LENGTH-i], 2))); } gsl_vector_set(fft, 0, data[0]); /* Calculate gain for each band: 0--1, 1--2, 2--4, 4--6, 6--FS/2 kHz */ int k,freq_lims[6] = {0,GSL_MIN(1000,params->FS/2),GSL_MIN(2000,params->FS/2),GSL_MIN(4000,params->FS/2),GSL_MIN(6000,params->FS/2),params->FS/2}; double weights[5] = {1,1,0.5,0.5,1000/(double)(params->FS/2-freq_lims[4])}; for(k=0; k<5; k++) { for(i=rint(freq_lims[k]/(double)params->FS*(double)FFT_LENGTH); i<rint(freq_lims[k+1]/(double)params->FS*(double)FFT_LENGTH); i++) gsl_matrix_set(bp_gain, index, k, gsl_matrix_get(bp_gain, index, k) + gsl_vector_get(fft, i)); gsl_matrix_set(bp_gain,index,k,weights[k]*gsl_matrix_get(bp_gain,index,k)); } gsl_vector_free(fft); } /** * Function InverseFiltering * * Glottal inverse filtering: * Estimate source signal and parametrize spectrum * Iterative Adaptive Inverse Filtering (IAIF) * * @param frame pointer to the samples * @param frame0 pointer to pre-frame samples * @param glottal pointer to the glottal source signal * @param LSF pointer to the voiced LSFs (glottal inverse filtered) * @param LSF2 pointer to the unvoiced LSFs (normal LPC) * @param spectral_tilt spectral tilt vector * @param index time index * @param lpc_order_vt LPC degree 1 * @param LPC_g LPC degree 2 * @param rho leaky integrator constant * @param lpc_order_gl spectral tilt degree */ void InverseFiltering(gsl_vector *frame, gsl_vector *frame0, gsl_vector *glottal, gsl_matrix *LSF, gsl_matrix *LSF2, gsl_matrix *spectral_tilt, gsl_vector *fundf, gsl_vector *glottsig, gsl_matrix *fftmatrix_vt, gsl_matrix *fftmatrix_src, gsl_matrix *fftmatrix_uv, int index, PARAM *params) { gsl_vector *a_l = gsl_vector_calloc(2); gsl_vector *a_p = gsl_vector_calloc(params->lpc_order_vt+1); gsl_vector *a_g = gsl_vector_calloc(params->lpc_order_gl+1); gsl_vector *a_g_iaif = gsl_vector_calloc(params->lpc_order_gl_iaif+1); gsl_vector *a_tilt = gsl_vector_calloc(params->lpc_order_gl+1); gsl_vector *frame_concat = gsl_vector_alloc(params->lpc_order_vt+frame->size); gsl_vector *B = gsl_vector_alloc(1); gsl_vector_set(B,0,1); int i; /* Concatenate frame and frame0 */ for(i=0; i<params->lpc_order_vt; i++) gsl_vector_set(frame_concat, i, gsl_vector_get(frame0, i)); for(i=params->lpc_order_vt; i<frame->size+params->lpc_order_vt; i++) gsl_vector_set(frame_concat, i, gsl_vector_get(frame, i-params->lpc_order_vt)); /* Use glottal inverse filtering */ if(params->use_iaif == 1) { /* 2. LPC-analysis (order l = 1) */ /* 3. Inverse filtering */ WLPC(frame, a_l, params->lambda_gl); WFilter(frame_concat, glottal, a_l, B, params->lambda_gl); Remove_mean(glottal); /* FFT of first VT estimate */ EvalFFTSpectrum(glottal, fftmatrix_vt, index, params); /* 4. Spectral analysis, select (W)LPC/(S)WLP/(S)XLP */ /* 5. Inverse filtering, warped only if WLPS is used */ if(params->lp_method == LP_METHOD_ID_WLP) { // SWLP-analysis (order p, M = p, lag = 1) SWLP(glottal,a_p,params->lpc_order_vt,1,params->lp_weighting,fundf,params->FS,index,glottsig,params->lp_stabilized); Filter(frame_concat,glottal,a_p); } else if(params->lp_method == LP_METHOD_ID_XLP) { // SXLP-analysis (order p, w = p) SXLP(glottal,a_p,params->lpc_order_vt,params->lp_stabilized); Filter(frame_concat,glottal,a_p); } else { // LPC-analysis (order p) WLPC(glottal,a_p,params->lambda_vt); WFilter(frame_concat,glottal,a_p,B,params->lambda_vt); } /* Convert LPC to LSF */ if(params->use_mod_iaif == 1) Convert_matrix_to_LSF(LSF, a_p, index); /* If full IAIF is used */ if(params->use_mod_iaif == 0) { /* 6. Integration */ Integrator(glottal, LIP_RADIATION); Remove_mean(glottal); /* 7. WLPC-analysis (order g = lpc_order_gl_iaif) */ /* 8. Inverse filtering */ /* 9. Integration */ WLPC(glottal, a_g_iaif, params->lambda_gl); WFilter(frame_concat, glottal, a_g_iaif, B, params->lambda_gl); Integrator(glottal, LIP_RADIATION); Remove_mean(glottal); /* FFT of final VT estimate */ EvalFFTSpectrum(glottal, fftmatrix_vt, index, params); /* 10. Spectral analysis, select (W)LPC/(S)WLP/(S)XLP */ /* 11. Inverse filtering, warped only if WLPC is used */ if(params->lp_method == LP_METHOD_ID_WLP) { // SWLP-analysis (order p, M = p, lag = 1) SWLP(glottal,a_p,params->lpc_order_vt,1,params->lp_weighting,fundf,params->FS,index,glottsig,params->lp_stabilized); Filter(frame_concat,glottal,a_p); } else if(params->lp_method == LP_METHOD_ID_XLP) { // SXLP-analysis (order p, w = p) SXLP(glottal,a_p,params->lpc_order_vt,1); Filter(frame_concat,glottal,a_p); } else { // LPC-analysis (order r = p), WLPC WLPC(glottal,a_p,params->lambda_vt); WFilter(frame_concat,glottal,a_p,B,params->lambda_vt); } /* Convert LPC to LSF */ Convert_matrix_to_LSF(LSF, a_p, index); } /* 12. Integration */ /* No integration if pre-emphasis is used */ if(USE_PRE_EMPH == 0) Integrator(glottal, LIP_RADIATION); Remove_mean(glottal); } else { /* Pre-emphasis */ Differentiate(frame,LIP_RADIATION); /* FFT of VT estimate */ EvalFFTSpectrum(frame, fftmatrix_vt, index, params); /* If glottal inverse filtering is not used, use (W)LPC/(S)WLP/(S)XLP only once */ if(params->lp_method == LP_METHOD_ID_WLP) { SWLP(frame,a_p,params->lpc_order_vt,1,params->lp_weighting,fundf,params->FS,index,glottsig,params->lp_stabilized); Filter(frame_concat,glottal,a_p); } else if(params->lp_method == LP_METHOD_ID_XLP) { SXLP(frame,a_p,params->lpc_order_vt,1); Filter(frame_concat,glottal,a_p); } else { WLPC(frame, a_p, params->lambda_vt); WFilter(frame_concat,glottal,a_p,B,params->lambda_vt); } /* De-emphasis */ Integrator(frame, LIP_RADIATION); /* Convert LPC to LSF */ Convert_matrix_to_LSF(LSF, a_p, index); } /* Define frame for unvoiced segments */ gsl_vector *uvframe = gsl_vector_alloc(params->unvoiced_frame_length); int cntr = rint((frame->size-params->unvoiced_frame_length)/2.0); for(i=0;i<params->unvoiced_frame_length;i++) gsl_vector_set(uvframe,i,gsl_vector_get(frame,i+cntr)); /* LPC for unvoiced segments, LPC/WLPC (possibility to use pre-emphasis, might make unvoiced * excitation too high-pass and must be consistent with synthesis settings) */ if(params->unvoiced_pre_emphasis == 1) Differentiate(uvframe,LIP_RADIATION); WLPC(uvframe, a_p, params->lambda_vt); if(params->unvoiced_pre_emphasis == 1) Integrator(uvframe, LIP_RADIATION); Convert_matrix_to_LSF(LSF2, a_p, index); /* Evaluate spectral tilt, LPC/WLPC */ WLPC(glottal, a_tilt, params->lambda_gl); Convert_matrix_to_LSF(spectral_tilt, a_tilt, index); /* FFT of final SRC estimate and unvoiced frame */ EvalFFTSpectrum(glottal, fftmatrix_src, index, params); EvalFFTSpectrum(uvframe, fftmatrix_uv, index, params); /* Free memory */ gsl_vector_free(uvframe); gsl_vector_free(a_l); gsl_vector_free(a_p); gsl_vector_free(a_g); gsl_vector_free(a_g_iaif); gsl_vector_free(a_tilt); gsl_vector_free(frame_concat); gsl_vector_free(B); } /** * Function InverseFiltering_long * * Glottal inverse filtering for long frame: * Estimate source signal with Iterative Adaptive Inverse Filtering (IAIF) * * @param frame pointer to the samples * @param frame0 pointer to pre-frame samples * @param glottal pointer to the glottal source signal * @param lpc_order_vt LPC degree 1 * @param LPC_g LPC degree 2 * @param rho leaky integrator constant */ void InverseFiltering_long(gsl_vector *frame, gsl_vector *frame0, gsl_vector *glottal, gsl_vector *fundf, gsl_vector *glottsig, int index, PARAM *params) { // TODO: /* Parameters for this function will discard PARAMS below */ int lp_method = 0; int lp_weighting = 0; /* Initialize */ gsl_vector *a_l = gsl_vector_calloc(2); gsl_vector *a_p = gsl_vector_calloc(params->lpc_order_vt+1); gsl_vector *a_g = gsl_vector_calloc(params->lpc_order_gl+1); gsl_vector *a_g_iaif = gsl_vector_calloc(params->lpc_order_gl_iaif+1); gsl_vector *frame_concat = gsl_vector_alloc(params->lpc_order_vt+frame->size); gsl_vector *B = gsl_vector_alloc(1); gsl_vector_set(B,0,1); int i; /* Concatenate frame and frame0 */ for(i=0; i<params->lpc_order_vt; i++) gsl_vector_set(frame_concat, i, gsl_vector_get(frame0, i)); for(i=params->lpc_order_vt; i<frame->size+params->lpc_order_vt; i++) gsl_vector_set(frame_concat, i, gsl_vector_get(frame, i-params->lpc_order_vt)); /* Use glottal inverse filtering */ if(params->use_iaif == 1) { /* 2. WLPC-analysis (order 1) */ /* 3. Inverse filtering */ WLPC(frame, a_l, params->lambda_gl); WFilter(frame_concat, glottal, a_l, B, params->lambda_gl); Remove_mean(glottal); /* 4. Spectral analysis, select (W)LPC/(S)WLP/(S)XLP */ /* 5. Inverse filtering, warped only if WLPC is used */ if(lp_method == 1) { // SWLP-analysis (order p, M = p, lag = 1) SWLP(glottal,a_p,params->lpc_order_vt,1,lp_weighting,fundf,params->FS,index,glottsig,params->lp_stabilized); Filter(frame_concat, glottal, a_p); } else if(lp_method == 2) { // SXLP-analysis (oder p, w = p) SXLP(glottal,a_p,params->lpc_order_vt,params->lp_stabilized); Filter(frame_concat, glottal, a_p); } else { // WLPC-analysis (order p) WLPC(glottal, a_p, params->lambda_vt); WFilter(frame_concat, glottal, a_p,B,params->lambda_vt); } /* 6. Integration */ Integrator(glottal, LIP_RADIATION); /* If full IAIF is used */ if(params->use_mod_iaif == 0) { /* 7. WLPC-analysis (order g) */ /* 8. Inverse filtering */ /* 9. Integration */ WLPC(glottal, a_g_iaif, params->lambda_gl); WFilter(frame_concat, glottal, a_g_iaif, B, params->lambda_gl); Integrator(glottal, LIP_RADIATION); /* 10. Spectral analysis, select (W)LPC/(S)WLP/(S)XLP, * 11. Inverse filtering, warped only if WLPC is used */ if(lp_method == 1) { // SWLP-analysis (order p, M = p, lag = 1) SWLP(glottal,a_p,params->lpc_order_vt,1,lp_weighting,fundf,params->FS,index,glottsig,params->lp_stabilized); Filter(frame_concat, glottal, a_p); } else if(lp_method == 2) { // SXLP-analysis (oder p, w = p) SXLP(glottal,a_p,params->lpc_order_vt,params->lp_stabilized); Filter(frame_concat, glottal, a_p); } else { // LPC-analysis (order p), warping can be used WLPC(glottal, a_p, params->lambda_vt); WFilter(frame_concat, glottal, a_p, B, params->lambda_vt); } /* 12. Integration */ Integrator(glottal, LIP_RADIATION); } /* If glottal inverse filtering is not used */ } else { /* Pre-emphasis */ Differentiate(frame,LIP_RADIATION); /* LPC */ WLPC(frame, a_p, params->lambda_vt); WFilter(frame_concat, glottal, a_p, B, params->lambda_vt); Integrator(glottal, LIP_RADIATION); /* De-emphasis */ Integrator(frame, LIP_RADIATION); } /* Free memory */ gsl_vector_free(a_l); gsl_vector_free(a_p); gsl_vector_free(a_g); gsl_vector_free(a_g_iaif); gsl_vector_free(frame_concat); gsl_vector_free(B); } /** * Function Define_current_f0 * * Define current f0 value: If index is zero, use default value. If f0 is zero, use previous non-zero value * * @param fundf f0 vector * @param f0 previous f0 value * @param index */ double Define_current_f0(gsl_vector *fundf, double f0, int index) { if(index == 0) f0 = DEFAULT_F0; if(gsl_vector_get(fundf, index) != 0) f0 = gsl_vector_get(fundf, index); return f0; } /** * Function Differentiate * * Differentiate signal with leak * * @param signal signal to be differentiated * @param leak leaky parameter (e.g. 0.99) * */ void Differentiate(gsl_vector *signal, double leak) { int i,j; double coeffs[2] = {1,-leak}; double sum; gsl_vector *temp = gsl_vector_alloc(signal->size); gsl_vector_memcpy(temp, signal); for(i=0; i<signal->size; i++) { sum = 0; for(j=0; j<=GSL_MIN(i, 1); j++) { sum += gsl_vector_get(signal, i-j)*coeffs[j]; } gsl_vector_set(temp, i, sum); } for(i=0; i<signal->size; i++) { gsl_vector_set(signal, i, gsl_vector_get(temp, i)); } gsl_vector_free(temp); } /** * Function Differentiate_noleak * * Differentiate signal (no leakage) * * @param signal signal to be differentiated * */ void Differentiate_noleak(gsl_vector *signal) { int i,j; double coeffs[2] = {1,-1}; double sum; gsl_vector *temp = gsl_vector_alloc(signal->size); gsl_vector_memcpy(temp, signal); for(i=0; i<signal->size; i++) { sum = 0; for(j=0; j<=GSL_MIN(i, 1); j++) { sum += gsl_vector_get(signal, i-j)*coeffs[j]; } gsl_vector_set(temp, i, sum); } for(i=0; i<signal->size; i++) { gsl_vector_set(signal, i, gsl_vector_get(temp, i)); } gsl_vector_free(temp); } /** * Function Differentiate_matrix_plus_dpi_sqrt * * Differentiate matrix and add one value that is the distance of the last LSF to PI. Convert to SQRT. * * @param m1 matrix to be processed * */ void Differentiate_LSFs(gsl_matrix **m1) { /* Initialize, allocate new matrix (size+1) */ int i,k; gsl_matrix *m2 = gsl_matrix_calloc((*m1)->size1,(*m1)->size2+1); /* Process: 1:orig 2-N:diff N+1:diff-pi */ for(k=0;k<(*m1)->size1;k++) { /* Set first LSF as is */ gsl_matrix_set(m2,k,0,gsl_matrix_get(*m1,k,0)); /* Set the following differentials */ for(i=1;i<(*m1)->size2;i++) gsl_matrix_set(m2,k,i,gsl_matrix_get((*m1),k,i)-gsl_matrix_get((*m1),k,i-1)); /* Set the distance to PI */ gsl_matrix_set(m2,k,m2->size2-1,M_PI-gsl_matrix_get((*m1),k,(*m1)->size2-1)); } /* Take square root */ for(k=0;k<m2->size1;k++) for(i=0;i<m2->size2;i++) gsl_matrix_set(m2,k,i,sqrt(gsl_matrix_get(m2,k,i))); /* Free old matrix and set pointer to new matrix */ gsl_matrix_free(*(m1)); *(m1) = m2; } /** * Function Extract_pulses * * Extract pulses for pulse library * * @param ... * */ void Extract_pulses(gsl_vector *speech_frame, gsl_vector *frame_orig, gsl_vector *fundf, gsl_vector *naq, gsl_matrix *gpulses, gsl_matrix *gpulses_rs, gsl_vector *pulse_pos, gsl_vector *pulse_inds, gsl_vector *pulse_lengths, gsl_matrix *plsf, gsl_matrix *ptilt, gsl_matrix *pharm, gsl_matrix *phnr, gsl_vector *pgain, gsl_vector *ph1h2, gsl_vector *pnaq, gsl_matrix *lsf, gsl_matrix *spectral_tilt, gsl_matrix *harmonics, gsl_vector *h1h2, gsl_matrix *hnr_i,gsl_vector *gain, gsl_matrix *pwaveform, gsl_matrix *waveform, int index, PARAM *params) { /* Stop if unvoiced */ if(gsl_vector_get(fundf,index) == 0) return; /* Find glottal closure instants (GCIs). Stop if not found */ gsl_vector *indices = Find_GCIs(frame_orig,fundf,params->FS,index); if(indices == NULL) return; /* Initialize */ int i,j,original_pulse_ind,t0,n_added_pulses = 0,p = lsf->size2,pg = spectral_tilt->size2; int wav_start_ind = floor(params->waveform_samples/2.0); int wav_end_ind = wav_start_ind + params->waveform_samples; double temp; gsl_vector *pulse_rs = gsl_vector_alloc(params->rspulsemaxlen); gsl_vector *pulse_wf = gsl_vector_alloc(2*waveform->size2); gsl_matrix *frame_lsf = gsl_matrix_calloc(MAX_NUMBER_OF_PULSES_IN_FRAME,lsf->size2); gsl_matrix *frame_source_lsf = gsl_matrix_calloc(MAX_NUMBER_OF_PULSES_IN_FRAME,spectral_tilt->size2); gsl_vector *frame = gsl_vector_calloc(frame_orig->size); gsl_vector_memcpy(frame,frame_orig); gsl_vector *pulse_temp; gsl_vector *pulse_nowin; gsl_vector *t0frame,*t0frame_vt,*t0frame_concat,*lsf_tmp1,*lsf_tmp2,*lsf_g1,*lsf_g2,*a,*ag,*a1,*B; if(params->pitch_synchronous_analysis == 1) { lsf_tmp1 = gsl_vector_calloc(p); lsf_tmp2 = gsl_vector_calloc(p); lsf_g1 = gsl_vector_calloc(pg); lsf_g2 = gsl_vector_calloc(pg); ag = gsl_vector_calloc(pg+1); a = gsl_vector_calloc(p+1); a1 = gsl_vector_calloc(2); B = gsl_vector_alloc(1); gsl_vector_set(B,0,1); } else { lsf_tmp1 = NULL; lsf_tmp2 = NULL; lsf_g1 = NULL; lsf_g2 = NULL; ag = NULL; a1 = NULL; a = NULL; B = NULL; } /* Differentiate speech frame */ Differentiate(frame,LEAK); /* Extract each complete two-period glottal flow waveform */ i = 0; while(indices != NULL && i<indices->size) { original_pulse_ind = GSL_MAX(index*params->shift-ceil(params->f0_frame_length/2.0)+ceil(params->frame_length/2.0),0) + gsl_vector_get(indices,i); if(gsl_vector_get(indices,i) != 0) { if(i+2 > indices->size-1) break; if(gsl_vector_get(indices,i+2) > frame->size-2) break; pulse_temp = gsl_vector_alloc(gsl_vector_get(indices,i+2)-gsl_vector_get(indices,i)+1); pulse_nowin = gsl_vector_alloc(pulse_temp->size); /* Get samples and windowing */ for(j=0;j<pulse_temp->size;j++) { gsl_vector_set(pulse_temp,j,gsl_vector_get(frame,gsl_vector_get(indices,i)+j)*HANN(j,pulse_temp->size)); gsl_vector_set(pulse_nowin,j,gsl_vector_get(frame,gsl_vector_get(indices,i)+j)); } /* If f0 is significantly different from the pulse period, the pulse may not be correctly estimated -> discard */ if(fabs(pulse_temp->size-rint(2.0*params->FS/gsl_vector_get(fundf,index)))/rint(2.0*params->FS/gsl_vector_get(fundf,index)) > params->max_pulse_len_diff) { gsl_vector_free(pulse_temp); gsl_vector_free(pulse_nowin); i++; continue; } /* Give warning if pulses do not fit to the matrix */ if(pulse_temp->size > params->pulsemaxlen) printf("ERROR: The pulse is longer (%i) than PULSEMAXLEN (%i).\n",(int)pulse_temp->size,(int)gpulses->size2); /******************************/ /* Pitch-synchronous analysis */ if(params->pitch_synchronous_analysis == 1) { /* Initialize pulse inverse filtering */ t0 = pulse_temp->size; t0frame = gsl_vector_alloc(t0); t0frame_vt = gsl_vector_alloc(t0); t0frame_concat = gsl_vector_calloc(p+t0); /* Copy T0 segment from speech frame */ for(j=0;j<t0;j++) gsl_vector_set(t0frame,j,gsl_vector_get(speech_frame,gsl_vector_get(indices,i)+j)); /* Copy frame0 from speech frame */ for(j=0; j<p; j++) if(gsl_vector_get(indices,i)+j-p >= 0) gsl_vector_set(t0frame_concat, j, gsl_vector_get(speech_frame, gsl_vector_get(indices,i)+j-p)); for(j=p; j<t0+p; j++) gsl_vector_set(t0frame_concat, j, gsl_vector_get(t0frame, j-p)); /**********************************/ /* IAIF glottal inverse filtering */ /* If IAIF is used */ if(params->use_iaif == 1) { /* Evaluate glottal spectrum */ Remove_mean(t0frame); WLPC(t0frame,a1,params->lambda_gl); /* Filter out glottal spectrum */ WFilter(t0frame_concat, t0frame_vt, a1, B, params->lambda_gl); /* Evaluate VT spectrum */ Remove_mean(t0frame_vt); WLPC(t0frame_vt,a,params->lambda_vt); /* Filter VT out */ WFilter(t0frame_concat,t0frame_vt,a,B,params->lambda_vt); Remove_mean(t0frame_vt); /* If full IAIF is used */ if(params->use_mod_iaif == 0) { /* Evaluate glottal spectrum with higher order */ WLPC(t0frame_vt,ag,params->lambda_gl); /* Filter out glottal spectrum */ WFilter(t0frame_concat, t0frame_vt, ag, B, params->lambda_gl); /* Evaluate VT spectrum */ Remove_mean(t0frame_vt); WLPC(t0frame_vt,a,params->lambda_vt); /* Filter VT out */ WFilter(t0frame_concat,t0frame_vt,a,B,params->lambda_vt); Remove_mean(t0frame_vt); } } else { /* Use basic LPC-based inverse filtering */ WLPC(t0frame,a,params->lambda_vt); WFilter(t0frame_concat,t0frame_vt,a,B,params->lambda_vt); Remove_mean(t0frame_vt); } /* Evaluate glottal spectrum */ WLPC(t0frame_vt,ag,params->lambda_gl); /* Convert to LSF, and copy LSFs to vector for averaging */ Convert_vector_to_LSF(a, lsf_tmp1); Convert_vector_to_LSF(ag, lsf_g1); /* Set vocal tract and glottal spectrum */ for(j=0;j<lsf_tmp2->size;j++) gsl_vector_set(lsf_tmp2,j,gsl_vector_get(lsf_tmp2,j) + gsl_vector_get(lsf_tmp1,j)); for(j=0;j<lsf_g1->size;j++) gsl_vector_set(lsf_g2,j,gsl_vector_get(lsf_g2,j) + gsl_vector_get(lsf_g1,j)); /* Set new pulse to pulse_temp (windowing) and to pulse_nowin */ for(j=0;j<t0;j++) { gsl_vector_set(pulse_temp,j,gsl_vector_get(t0frame_vt,j)*HANN(j,t0)); gsl_vector_set(pulse_nowin,j,gsl_vector_get(t0frame_vt,j)); } /* Free memory */ gsl_vector_free(t0frame_concat); gsl_vector_free(t0frame); gsl_vector_free(t0frame_vt); } /* Evaluate normalized amplitude quotient (NAQ) */ double dpeak = BIG_POS_NUMBER; for(j=rint(pulse_nowin->size/4.0);j<rint(3.0*pulse_temp->size/4.0);j++) if(gsl_vector_get(pulse_nowin,j) < dpeak) dpeak = gsl_vector_get(pulse_nowin,j); dpeak = fabs(dpeak); Integrator(pulse_nowin,LEAK); double fac = BIG_NEG_NUMBER; for(j=rint(pulse_nowin->size/5.0);j<rint(4.0*pulse_temp->size/5.0);j++) if(gsl_vector_get(pulse_nowin,j) > fac) fac = gsl_vector_get(pulse_nowin,j); fac = fabs(fac); gsl_vector_set(naq,index,fac/dpeak/(pulse_nowin->size/2.0)); /* Interpolate (rs) */ Interpolate(pulse_temp,pulse_rs); /* Normalize the energy of the pulse */ double e = 0; for(j=0;j<pulse_rs->size;j++) e += gsl_vector_get(pulse_rs,j)*gsl_vector_get(pulse_rs,j); e = sqrt(e); for(j=0;j<pulse_rs->size;j++) gsl_vector_set(pulse_rs,j,gsl_vector_get(pulse_rs,j)/e); /* Interpolate waveform to twice the number of samples in waveform, * but take only half of the later in the center of the pulse */ Interpolate(pulse_temp,pulse_wf); /* Normalize pulse waveform minimum to -1 */ temp = 1; for(j=0;j<pulse_wf->size;j++) if(gsl_vector_get(pulse_wf,j) < temp) temp = gsl_vector_get(pulse_wf,j); temp = fabs(temp); if(temp >= 0) temp = 1; for(j=0;j<pulse_wf->size;j++) gsl_vector_set(pulse_wf,j,gsl_vector_get(pulse_wf,j)/temp); for(j=wav_start_ind;j<wav_end_ind;j++) gsl_matrix_set(waveform,index,j-wav_start_ind,gsl_matrix_get(waveform,index,j-wav_start_ind) + gsl_vector_get(pulse_wf,j)); // Sum pulses and divide by N in the end /* Set pulse parameters for pulse library */ if(params->extract_pulselib_params == 1 && params->number_of_pulses < params->maxnumberofpulses) { /* Add gpulses */ for(j=0;j<pulse_temp->size;j++) gsl_matrix_set(gpulses,params->number_of_pulses,j,gsl_vector_get(pulse_temp,j)); /* Add gpulses_rs */ for(j=0;j<pulse_rs->size;j++) gsl_matrix_set(gpulses_rs,params->number_of_pulses,j,gsl_vector_get(pulse_rs,j)); /* Set length, position, and pulse index */ gsl_vector_set(pulse_lengths,params->number_of_pulses,pulse_temp->size); gsl_vector_set(pulse_pos,params->number_of_pulses,index); gsl_vector_set(pulse_inds,params->number_of_pulses,original_pulse_ind); /* Set frame-wise pulse parameters */ for(j=0;j<harmonics->size2;j++) gsl_matrix_set(pharm,params->number_of_pulses,j,gsl_matrix_get(harmonics,index,j)); for(j=0;j<hnr_i->size2;j++) gsl_matrix_set(phnr,params->number_of_pulses,j,gsl_matrix_get(hnr_i,index,j)); gsl_vector_set(pgain,params->number_of_pulses,gsl_vector_get(gain,index)); gsl_vector_set(ph1h2,params->number_of_pulses,gsl_vector_get(h1h2,index)); /* Set individual pulse parameters */ for(j=wav_start_ind;j<wav_end_ind;j++) gsl_matrix_set(pwaveform,params->number_of_pulses,j-wav_start_ind,gsl_vector_get(pulse_wf,j)); gsl_vector_set(pnaq,params->number_of_pulses,gsl_vector_get(naq,index)); /* Set either individual or frame-wise parameters */ if(params->pitch_synchronous_analysis == 1) { for(j=0;j<lsf->size2;j++) gsl_matrix_set(plsf,params->number_of_pulses,j,gsl_vector_get(lsf_tmp1,j)); for(j=0;j<spectral_tilt->size2;j++) gsl_matrix_set(ptilt,params->number_of_pulses,j,gsl_vector_get(lsf_g1,j)); } else { for(j=0;j<lsf->size2;j++) gsl_matrix_set(plsf,params->number_of_pulses,j,gsl_matrix_get(lsf,index,j)); for(j=0;j<spectral_tilt->size2;j++) gsl_matrix_set(ptilt,params->number_of_pulses,j,gsl_matrix_get(spectral_tilt,index,j)); } } /* Save vocal tract and source LSFs of each pulse (from which the closest to the average is selected). * This is only used in pitch-synchronous analysis. */ if(params->pitch_synchronous_analysis == 1) { for(j=0;j<lsf->size2;j++) gsl_matrix_set(frame_lsf,n_added_pulses,j,gsl_vector_get(lsf_tmp1,j)); for(j=0;j<spectral_tilt->size2;j++) gsl_matrix_set(frame_source_lsf,n_added_pulses,j,gsl_vector_get(lsf_g1,j)); } /* Increment pulse index */ params->number_of_pulses++; n_added_pulses++; /* Give warning if pulses do not fit to the matrix (if pulses are stored) */ if(params->extract_pulselib_params == 1 && params->number_of_pulses > params->maxnumberofpulses) printf("WARNING: The number of pulses has exceeded the value MAX_NUMBER_OF_PULSES (%i).\n",params->maxnumberofpulses); /* Free memory */ gsl_vector_free(pulse_temp); gsl_vector_free(pulse_nowin); } i++; } /* Replace vocal tract and source LSFs from pulse library closest to the average of the frame */ if(params->pitch_synchronous_analysis == 1 && n_added_pulses > 0) { gsl_vector *error = gsl_vector_calloc(n_added_pulses); for(i=0;i<n_added_pulses;i++) for(j=0;j<lsf->size2;j++) gsl_vector_set(error,i, gsl_vector_get(error,i) + fabs(gsl_vector_get(lsf_tmp2,j)/n_added_pulses - gsl_matrix_get(frame_lsf,i,j))); int minind = gsl_vector_min_index(error); for(j=0;j<lsf->size2;j++) gsl_matrix_set(lsf,index,j,gsl_matrix_get(frame_lsf,minind,j)); for(j=0;j<spectral_tilt->size2;j++) gsl_matrix_set(spectral_tilt,index,j,gsl_matrix_get(frame_source_lsf,minind,j)); gsl_vector_free(error); } /* Normalize the averaged pulse waveform so that the minimum is scaled to -1 */ if(n_added_pulses > 0) { temp = 1; for(j=0;j<waveform->size2;j++) { if(gsl_matrix_get(waveform,index,j) < temp) temp = gsl_matrix_get(waveform,index,j); } temp = fabs(temp); for(j=0;j<waveform->size2;j++) gsl_matrix_set(waveform,index,j,gsl_matrix_get(waveform,index,j)/temp); } /* Free memory */ gsl_matrix_free(frame_lsf); gsl_matrix_free(frame_source_lsf); gsl_vector_free(indices); gsl_vector_free(pulse_rs); gsl_vector_free(pulse_wf); gsl_vector_free(frame); if(params->pitch_synchronous_analysis == 1) { gsl_vector_free(lsf_tmp1); gsl_vector_free(lsf_tmp2); gsl_vector_free(lsf_g1); gsl_vector_free(lsf_g2); gsl_vector_free(a); gsl_vector_free(ag); gsl_vector_free(a1); gsl_vector_free(B); } } /** * Function Find_GCIs * * Find glottal closure instants (GCIs) * * @param ... * */ gsl_vector *Find_GCIs(gsl_vector *frame_orig, gsl_vector *fundf, int FS, int index) { int i,j,min_ind,ind_ind,t0_tmp; double t0,min_val,temp; gsl_vector *indices = gsl_vector_calloc(100); gsl_vector *final_inds; gsl_vector *frame = gsl_vector_calloc(frame_orig->size); /* Differentiate frame */ gsl_vector_memcpy(frame,frame_orig); Differentiate(frame,LEAK); /* Find t0 minima of the glottal waveform in order to find GCIs, * start evaluating from the mimina, first backward, then forward */ min_ind = gsl_vector_min_index(frame); t0 = FS/gsl_vector_get(fundf,index); gsl_vector_set(indices,50,min_ind); t0_tmp = min_ind; ind_ind = 51; /* Backward */ temp = 0; ind_ind = 51; while(1) { t0_tmp = rint(gsl_vector_get(indices,ind_ind-1) - t0 - temp); if(t0_tmp < 0) break; min_val = BIG_POS_NUMBER; for(i=-20;i<21;i++) { if(gsl_vector_get(frame,GSL_MIN(GSL_MAX(t0_tmp + i,0),frame->size-1)) < min_val) { min_val = gsl_vector_get(frame,GSL_MIN(GSL_MAX(t0_tmp + i,0),frame->size-1)); gsl_vector_set(indices,ind_ind,GSL_MIN(GSL_MAX(t0_tmp + i,0),frame->size-1)); } } if(gsl_vector_get(indices,ind_ind-1)-gsl_vector_get(indices,ind_ind) < t0/2.0) { temp = temp + t0; } else { ind_ind++; temp = 0; } } /* Forward */ temp = 0; ind_ind = 49; while(1) { t0_tmp = rint(gsl_vector_get(indices,ind_ind+1) + t0 + temp); if(t0_tmp > frame->size-1) break; min_val = BIG_POS_NUMBER; for(i=-20;i<21;i++) { if(gsl_vector_get(frame,GSL_MIN(GSL_MAX(t0_tmp + i,0),frame->size-1)) < min_val) { min_val = gsl_vector_get(frame,GSL_MIN(GSL_MAX(t0_tmp + i,0),frame->size-1)); gsl_vector_set(indices,ind_ind,GSL_MIN(GSL_MAX(t0_tmp + i,0),frame->size-1)); } } if(gsl_vector_get(indices,ind_ind)-gsl_vector_get(indices,ind_ind+1) < t0/2.0) { temp = temp + t0; } else { ind_ind--; temp = 0; } } /* Sort indices */ gsl_sort_vector(indices); /* Allocate vector for non-zero indices and return */ i = 0; while(gsl_vector_get(indices,indices->size-1-i) > 0) i++; if(i < 2) { gsl_vector_free(indices); gsl_vector_free(frame); return NULL; } else { final_inds = gsl_vector_alloc(i); for(j=0;j<i;j++) gsl_vector_set(final_inds,j,gsl_vector_get(indices,indices->size-i+j)); gsl_vector_free(indices); gsl_vector_free(frame); return final_inds; } } /** * Function WFilter * * Warped FIR/IIR filter. * * This function is more or less adapted from WarpTB (MATLAB toolbox for frequency-warped signal processing) * authored by Aki H\E4rm\E4 and Matti Karjalainen. * * @param signal signal vector * @param A filter numerator * @param B filter denominator * @param lambda warping parameter * */ void WFilter(gsl_vector *signal, gsl_vector *result, gsl_vector *A, gsl_vector *B, double lambda) { int i,q,mlen; long int o; double xr,x,ffr,tmpr,Bb; double *sigma; long int len = signal->size; int adim = A->size; int bdim = B->size; double *Ar = (double *)calloc(adim,sizeof(double)); double *Br = (double *)calloc(bdim,sizeof(double)); double *ynr = (double *)calloc(signal->size,sizeof(double)); double *rsignal = (double *)calloc(signal->size,sizeof(double)); double *rmem = (double *)calloc(GSL_MAX(adim,bdim)+2,sizeof(double)); /* Set signal to array */ for(i=0;i<len;i++) { rsignal[i] = gsl_vector_get(signal,i); } /* Set A and B to arrays */ for(i=0;i<adim;i++) { Ar[i] = gsl_vector_get(A,i); } for(i=0;i<bdim;i++) { Br[i] = gsl_vector_get(B,i); } /* Initialize */ sigma = NFArray(bdim+2); alphas2sigmas(Br,sigma,lambda,bdim-1); if(adim >= bdim) mlen = adim; else mlen = bdim + 1; Bb = 1/Br[0]; /* Warped filtering */ for(o=0;o<len;o++) { xr = rsignal[o]*Bb; /* Update feedbackward sum */ for(q=0;q<bdim;q++) { xr -= sigma[q]*rmem[q]; } xr = xr/sigma[bdim]; x = xr*Ar[0]; /* Update inner states */ for(q=0;q<mlen;q++) { tmpr = rmem[q] + lambda*(rmem[q+1] - xr); rmem[q] = xr; xr = tmpr; } /* Update feedforward sum */ for(q=0,ffr=0.0;q<adim-1;q++) { ffr += Ar[q+1]*rmem[q+1]; } /* Update output */ ynr[o] = x + ffr; } /* Set output to result */ int order = signal->size-result->size; for(i=order;i<signal->size;i++) { gsl_vector_set(result,i-order,ynr[i]); } /* Free memory */ free(ynr); free(rsignal); free(Ar); free(Br); free(rmem); free(sigma); } /** * Function alphas2sigmas * * Convert alhas to sigmas. * * @param alp alphas * @param sigm sigmas * @param lambda warping coefficient * @param dim dimension * */ void alphas2sigmas(double *alp, double *sigm, double lambda, int dim) { int q; double S=0,Sp; sigm[dim] = lambda*alp[dim]/alp[0]; Sp = alp[dim]/alp[0]; for(q=dim;q>1;q--) { S = alp[q-1]/alp[0] - lambda*Sp; sigm[q-1] = lambda*S + Sp; Sp = S; } sigm[0] = S; sigm[dim+1] = 1 - lambda*S; } /** * Function NFArray * * Create array. * * @param size * @return pointer to array * */ double *NFArray(int size) { double *p; p = (double *)calloc(sizeof(*p),size); return p; } /** * Function FundF * * Estimate fundamental frequency of a frame * * @param ... */ void FundF(gsl_vector *frame, gsl_vector *signal, gsl_matrix *fundf_candidates, gsl_vector *fundf, gsl_matrix *bp_gain, int index, PARAM *params) { /* Exit if external F0 file is used */ if(params->use_external_f0 == 1) return; int i,n,zero_crossings,ind; double r_max; gsl_vector *max_inds = gsl_vector_calloc(NUMBER_OF_F0_CANDIDATES); gsl_vector *max_inds_interp = gsl_vector_calloc(NUMBER_OF_F0_CANDIDATES); gsl_vector *r = gsl_vector_calloc(frame->size); gsl_vector *r_copy = gsl_vector_calloc(frame->size); gsl_vector *r_norm = gsl_vector_alloc(frame->size); /* Count the number of zero crossings */ zero_crossings = 0; for(i=0; i<signal->size-1; i++) if(GSL_SIGN(gsl_vector_get(signal, i)) != GSL_SIGN(gsl_vector_get(signal, i+1))) zero_crossings++; /* Autocorrelation sequence */ for(i=0; i<frame->size; i++) for(n=i; n<frame->size; n++) gsl_vector_set(r, i, gsl_vector_get(r, i)+gsl_vector_get(frame, n)*gsl_vector_get(frame, n-i)); /* Normalize r */ r_max = gsl_vector_max(r); for(i=0; i<frame->size; i++) gsl_vector_set(r_norm,i,gsl_vector_get(r,i)/r_max); /* Copy vector r for interpolation */ gsl_vector_memcpy(r_copy,r); /* Clear samples when the index exceeds the fundamental frequency limits */ for(i=0; i<rint(params->FS/params->fmax); i++) gsl_vector_set(r,i,NOTMAX); for(i=rint(params->FS/params->fmin); i<r->size; i++) gsl_vector_set(r,i,NOTMAX); /* Clear samples descending from the end-points */ ind = rint(params->FS/params->fmax); while(gsl_vector_get(r,ind)-gsl_vector_get(r,ind+1) > 0) { gsl_vector_set(r,ind,NOTMAX); ind++; if(ind+1>r->size-1) break; } ind = rint(params->FS/params->fmin)-1; while(gsl_vector_get(r,ind)-gsl_vector_get(r,ind-1) > 0) { gsl_vector_set(r,ind,NOTMAX); ind--; if(ind-1<0) { break; } } /* Get T0 and F0 candidates */ for(i=0;i<NUMBER_OF_F0_CANDIDATES;i++) { /* Get the i:th T0 index estimate */ gsl_vector_set(max_inds,i,gsl_vector_max_index(r)); /* Fit quadratic function to the peak of ACF to cancel the effect of the sampling period * (i.e. parabolic interpolation) */ gsl_vector_set(max_inds_interp,i,Parabolic_interpolation(r_copy,gsl_vector_get(max_inds,i),params)); /* Set the F0 candidate */ if(gsl_vector_get(max_inds_interp,i) <= 0) { gsl_matrix_set(fundf_candidates,index,i,0); break; } else { gsl_matrix_set(fundf_candidates,index,i,params->FS/gsl_vector_get(max_inds_interp,i)); if(gsl_matrix_get(fundf_candidates,index,i) > params->fmax || gsl_matrix_get(fundf_candidates,index,i) < params->fmin || gsl_matrix_get(bp_gain, index, 0) < params->voicing_threshold/2.0 || zero_crossings > params->ZCR*2.0) gsl_matrix_set(fundf_candidates,index,i,0); } /* Clear the descending samples from the i:th maximum */ ind = rint(gsl_vector_get(max_inds,i)); while(gsl_vector_get(r,ind)-gsl_vector_get(r,ind+1) > 0) { gsl_vector_set(r,ind,NOTMAX); ind++; if(ind+1>r->size-1) { break; } } ind = GSL_MAX(rint(gsl_vector_get(max_inds,i)-1),1); while(gsl_vector_get(r,ind)-gsl_vector_get(r,ind-1) > 0) { gsl_vector_set(r,ind,NOTMAX); ind--; if(ind-1<0) { break; } } } /* Decide voiced/unvoiced. If voiced, set F0, otherwise set zero */ if(gsl_matrix_get(bp_gain, index, 0) < params->voicing_threshold || zero_crossings > params->ZCR || gsl_vector_get(max_inds_interp,0) == 0) gsl_vector_set(fundf, index, 0); else gsl_vector_set(fundf, index, params->FS/gsl_vector_get(max_inds_interp,0)); /* Free memory */ gsl_vector_free(r); gsl_vector_free(r_copy); gsl_vector_free(max_inds); gsl_vector_free(max_inds_interp); gsl_vector_free(r_norm); } /** * Function Parabolic_interpolation * * Fit quadratic function to the peak of autocorrelation function (ACF) to cancel the effect of the sampling period * (i.e. parabolic interpolation) * * @param r ACF * @param maxind index at maximum value * @param params * @return T0 value */ double Parabolic_interpolation(gsl_vector *r, int maxind, PARAM *params) { /* Allocate variables */ int i; double xi, chisq, T0; gsl_matrix *X, *cov; gsl_vector *y, *w, *c; gsl_multifit_linear_workspace *work; X = gsl_matrix_alloc(F0_INTERP_SAMPLES, 3); y = gsl_vector_alloc(F0_INTERP_SAMPLES); w = gsl_vector_alloc(F0_INTERP_SAMPLES); c = gsl_vector_alloc(3); cov = gsl_matrix_alloc(3, 3); work = gsl_multifit_linear_alloc(F0_INTERP_SAMPLES, 3); /* Set data */ for(i=0;i<F0_INTERP_SAMPLES;i++) { xi = maxind-(F0_INTERP_SAMPLES-1)/2 + i; gsl_matrix_set(X, i, 0, 1.0); gsl_matrix_set(X, i, 1, xi); gsl_matrix_set(X, i, 2, xi*xi); gsl_vector_set(y, i, gsl_vector_get(r, GSL_MIN(GSL_MAX(maxind-(F0_INTERP_SAMPLES-1)/2 + i,0),r->size-1))); gsl_vector_set(w, i, 1.0); } /* Quadratic fitting */ /* Evaluate the value of the function at the zero of the derivative. * This is the interpolated length of the fundamental period in samples. */ gsl_multifit_wlinear(X, w, y, c, cov, &chisq, work); T0 = -gsl_vector_get(c,1)/(2.0*gsl_vector_get(c,2)); /* Free memory */ gsl_matrix_free(X); gsl_matrix_free(cov); gsl_vector_free(y); gsl_vector_free(w); gsl_vector_free(c); gsl_multifit_linear_free(work); /* Make sure the parabolic interpolation did perform succesfully */ if(isnan(T0) == 0 && params->FS/T0 < params->fmax && params->FS/T0 > params->fmin) return T0; else return 0; } /** * Function F0_postprocess * * Various postprocessing for F0: * -Median filtering * -Filling small gaps * -Tajectory estimation for discontinuities * * @param fundf F0 * @param fundf_candidates candidate F0 values * @param params */ void F0_postprocess(gsl_vector *fundf, gsl_matrix *fundf_candidates, PARAM *params) { /* Exit if external F0 file is used */ if(params->use_external_f0 == 1) return; /* Copy original F0 */ gsl_vector *fundf_orig = gsl_vector_alloc(fundf->size); gsl_vector_memcpy(fundf_orig,fundf); /* Process */ MedFilt3(fundf); Fill_f0_gaps(fundf, params); Fundf_postprocessing(fundf, fundf_orig, fundf_candidates, params); MedFilt3(fundf); Fill_f0_gaps(fundf, params); Fundf_postprocessing(fundf, fundf_orig, fundf_candidates, params); MedFilt3(fundf); /* Free memory */ gsl_vector_free(fundf_orig); } /** * Fill_f0_gaps * * Fill small gaps in F0 * * @param fundf F0 */ void Fill_f0_gaps(gsl_vector *fundf, PARAM *params) { int i,j,voiced; double fundf_est,mu,std,sum,n,lim,ave; double f0jump01,f0jump45,f0jump02,f0jump03,f0jump12,f0jump13,f0jump42,f0jump43,f0jump52,f0jump53,f0jump05,f0jump14; gsl_vector *fundf_fill = gsl_vector_alloc(F0_FILL_RANGE); /* Estimate mean (mu) and standard deviation (std) of voiced parts */ sum = 0; n = 0; for(i=0;i<fundf->size;i++) { if(gsl_vector_get(fundf,i) != 0) { sum += gsl_vector_get(fundf,i); n++; } } mu = sum/n; sum = 0; n = 0; for(i=0;i<fundf->size;i++) { if(gsl_vector_get(fundf,i) != 0) { sum += pow(mu-gsl_vector_get(fundf,i),2); n++; } } std = sqrt(sum/(n-1)); /* Go throught all F0 values and fill small gaps (even if voiced) */ for(i=0;i<fundf->size-F0_FILL_RANGE;i++) { fundf_est = 0; voiced = 0; for(j=0;j<F0_FILL_RANGE;j++) { gsl_vector_set(fundf_fill,j,gsl_vector_get(fundf,i+j)); if(gsl_vector_get(fundf_fill,j) > 0) { voiced++; fundf_est += gsl_vector_get(fundf_fill,j); } } if(gsl_vector_get(fundf_fill,0) > 0 && gsl_vector_get(fundf_fill,1) > 0 && gsl_vector_get(fundf_fill,5) > 0 && gsl_vector_get(fundf_fill,4) > 0) { if(gsl_vector_get(fundf_fill,2) == 0 && gsl_vector_get(fundf_fill,3) == 0) { gsl_vector_set(fundf,i+2,fundf_est/4.0); gsl_vector_set(fundf,i+3,fundf_est/4.0); } else if(gsl_vector_get(fundf_fill,2) == 0) { gsl_vector_set(fundf,i+2,fundf_est/5.0); } else if(gsl_vector_get(fundf_fill,3) == 0) { gsl_vector_set(fundf,i+3,fundf_est/5.0); } } /* If all values are voiced, replace gaps of size two of which values differ significantly from average value */ if(voiced == F0_FILL_RANGE) { f0jump01 = fabs(gsl_vector_get(fundf_fill,0)-gsl_vector_get(fundf_fill,1)); f0jump45 = fabs(gsl_vector_get(fundf_fill,4)-gsl_vector_get(fundf_fill,5)); f0jump02 = fabs(gsl_vector_get(fundf_fill,0)-gsl_vector_get(fundf_fill,2)); f0jump03 = fabs(gsl_vector_get(fundf_fill,0)-gsl_vector_get(fundf_fill,3)); f0jump12 = fabs(gsl_vector_get(fundf_fill,1)-gsl_vector_get(fundf_fill,2)); f0jump13 = fabs(gsl_vector_get(fundf_fill,1)-gsl_vector_get(fundf_fill,3)); f0jump42 = fabs(gsl_vector_get(fundf_fill,4)-gsl_vector_get(fundf_fill,2)); f0jump43 = fabs(gsl_vector_get(fundf_fill,4)-gsl_vector_get(fundf_fill,3)); f0jump52 = fabs(gsl_vector_get(fundf_fill,5)-gsl_vector_get(fundf_fill,2)); f0jump53 = fabs(gsl_vector_get(fundf_fill,5)-gsl_vector_get(fundf_fill,3)); f0jump05 = fabs(gsl_vector_get(fundf_fill,0)-gsl_vector_get(fundf_fill,5)); f0jump14 = fabs(gsl_vector_get(fundf_fill,1)-gsl_vector_get(fundf_fill,4)); lim = params->relative_f0_threshold*std; ave = (gsl_vector_get(fundf_fill,0) + gsl_vector_get(fundf_fill,1) + gsl_vector_get(fundf_fill,4) + gsl_vector_get(fundf_fill,5))/4.0; if(f0jump01 < lim && f0jump45 < lim && f0jump02 > lim && f0jump03 > lim && f0jump12 > lim && f0jump13 > lim && f0jump42 > lim && f0jump43 > lim && f0jump52 > lim && f0jump53 > lim && f0jump05 < lim && f0jump14 < lim) { gsl_vector_set(fundf,i+2,ave); gsl_vector_set(fundf,i+3,ave); } } } /* Go throught all F0 values and eliminate small voiced regions */ for(i=0;i<fundf->size-F0_FILL_RANGE;i++) { for(j=0;j<F0_FILL_RANGE;j++) { gsl_vector_set(fundf_fill,j,gsl_vector_get(fundf,i+j)); } if(gsl_vector_get(fundf_fill,0) == 0 && gsl_vector_get(fundf_fill,1) == 0 && gsl_vector_get(fundf_fill,5) == 0 && gsl_vector_get(fundf_fill,4) == 0) { if(gsl_vector_get(fundf_fill,2) > 0 || gsl_vector_get(fundf_fill,3) > 0) { gsl_vector_set(fundf,i+2,0); gsl_vector_set(fundf,i+3,0); } } } gsl_vector_free(fundf_fill); } /** * Fundf_postprocessing * * Refine f0-trajectory * * @param fundf fundamental frequency values * @param fundf_orig original fundamental frequency values * @param fundf_candidates candidates for F0 * @param params parameter structure */ void Fundf_postprocessing(gsl_vector *fundf, gsl_vector *fundf_orig, gsl_matrix *fundf_candidates, PARAM *params) { int i,j,ind,voiced_ind_b,voiced_ind_f,unvoiced_ind,n; double f0_forward,f0_backward,x[params->f0_check_range],y[params->f0_check_range],w[params->f0_check_range],f0jump_b,f0jump_f; double c0,c1,cov00,cov01,cov11,chisq_f,chisq_b,mu,std,sum; /* Estimate mean (mu) and standard deviation (std) of voiced parts */ sum = 0; n = 0; for(i=0;i<fundf->size;i++) { if(gsl_vector_get(fundf,i) != 0) { sum += gsl_vector_get(fundf,i); n++; } } mu = sum/n; sum = 0; n = 0; for(i=0;i<fundf->size;i++) { if(gsl_vector_get(fundf,i) != 0) { sum += pow(mu-gsl_vector_get(fundf,i),2); n++; } } std = sqrt(sum/(n-1)); /* Go throught all F0 values and create weighted linear estimates for all F0 samples both from backward and forward */ // TODO: Nonlinear fitting! if(params->f0_postprocessing == 1) { /* Start looping F0 */ for(i=params->f0_check_range;i<fundf->size-params->f0_check_range;i++) { /* Check values backward (left to right) */ ind = 0; voiced_ind_b = 0; unvoiced_ind = 0; for(j=params->f0_check_range;j>0;j--) { if(gsl_vector_get(fundf,i-j) == 0) { w[ind] = 0; unvoiced_ind++; } else { w[ind] = 1; voiced_ind_b++; } x[ind] = ind; y[ind] = gsl_vector_get(fundf,i-j); ind++; } if(unvoiced_ind == params->f0_check_range || voiced_ind_b < 3) { f0_backward = 0; } else { /* Weighted linear fitting, estimate new value */ gsl_fit_wlinear(x,1,w,1,y,1,(double)params->f0_check_range,&c0,&c1,&cov00,&cov01,&cov11,&chisq_b); f0_backward = c0 + c1*(double)params->f0_check_range; } /* Check values forward (right to left) */ ind = 0; voiced_ind_f = 0; unvoiced_ind = 0; for(j=1;j<params->f0_check_range+1;j++) { if(gsl_vector_get(fundf,i+j) == 0) { w[ind] = 0; unvoiced_ind++; } else { w[ind] = 1; voiced_ind_f++; } x[ind] = ind; y[ind] = gsl_vector_get(fundf,i+j); ind++; } if(unvoiced_ind == params->f0_check_range || voiced_ind_f < 3) { f0_forward = 0; } else { /* Weighted linear fitting, estimate new value */ gsl_fit_wlinear(x,1,w,1,y,1,(double)params->f0_check_range,&c0,&c1,&cov00,&cov01,&cov11,&chisq_f); f0_forward = c0 - c1; } /* Evaluate relative jump in F0 from both directions */ if(gsl_vector_get(fundf,i) != 0) { f0jump_b = fabs(gsl_vector_get(fundf,i)-gsl_vector_get(fundf,i-1))/gsl_vector_get(fundf,i); f0jump_f = fabs(gsl_vector_get(fundf,i)-gsl_vector_get(fundf,i+1))/gsl_vector_get(fundf,i); } else { f0jump_b = 0; f0jump_f = 0; } /* Set estimate if the relative jump is high enough, * take into account the number of used voiced values * in the fitting (voiced_ind) and the magnitude of the residual (chisq) */ if(gsl_vector_get(fundf,i) != 0) { double new_f0 = gsl_vector_get(fundf,i); double f0jump = 0; if(voiced_ind_b > voiced_ind_f) { // Compare number of voiced frames if(f0_backward > params->fmin && f0_backward < params->fmax && f0jump_b >= params->relative_f0_threshold) { new_f0 = f0_backward; f0jump = f0jump_b; } } else if(voiced_ind_b < voiced_ind_f) { if(f0_forward > params->fmin && f0_forward < params->fmax && f0jump_f >= params->relative_f0_threshold) { new_f0 = f0_forward; f0jump = f0jump_f; } } else { if(chisq_b < chisq_f) { // Compare goodness of fit if(f0_backward > params->fmin && f0_backward < params->fmax && f0jump_b >= params->relative_f0_threshold) { new_f0 = f0_backward; f0jump = f0jump_b; } } else { if(f0_forward > params->fmin && f0_forward < params->fmax && f0jump_f >= params->relative_f0_threshold) { new_f0 = f0_forward; f0jump = f0jump_f; } } } /* Check if second F0 candidate is close. If so, set that value instead if estimated value */ if(f0jump > params->relative_f0_threshold*std) { if(fabs(gsl_matrix_get(fundf_candidates,i,1) - new_f0) < f0jump) gsl_vector_set(fundf,i,gsl_matrix_get(fundf_candidates,i,1)); else gsl_vector_set(fundf,i,new_f0); } } /* Make sure the correction does not lead the F0 trajectory to a wrong tract by estimating * the cumulative difference between the original and new F0 curves. * This is just a precaution, leading to a wrong F0 track should not normally happen */ double cum_error = 0; for(j=GSL_MAX(i-F0_CUM_ERROR_RANGE,0);j<i;j++) cum_error += fabs(gsl_vector_get(fundf_orig,j)-gsl_vector_get(fundf,j))/mu; if(cum_error > F0_CUM_ERROR_LIM) gsl_vector_set(fundf,i,gsl_vector_get(fundf_orig,i)); } } } /** * Function Integrator * * Leaky integrator * * @param frame pointer to the samples * @param rho leaky integrator constant */ void Integrator(gsl_vector *frame, double leak) { int i; double temp = 0; for(i=0;i<frame->size;i++) { gsl_vector_set(frame, i, gsl_vector_get(frame, i)+leak*temp); temp = gsl_vector_get(frame, i); } } /** * Function Add_missing_frames * * Add missing frames to the beginning and the end of parameters. * This is due to the analysis scheme, where the analysis starts * and ends with whole frames instead of zero-padding. * */ void Add_missing_frames(gsl_vector **pfundf,gsl_matrix **pfundf_candidates,gsl_vector **pgain,gsl_vector **puvgain,gsl_matrix **phnr, gsl_matrix **pspectral_tilt,gsl_matrix **pLSF,gsl_matrix **pLSF2,gsl_matrix **pharmonics,gsl_matrix **pwaveform, gsl_vector **ph1h2,gsl_vector **pnaq, gsl_matrix **pfftmatrix_vt, gsl_matrix **pfftmatrix_src, gsl_matrix **pfftmatrix_uv, PARAM *params) { int i,j; int empty_frames = rint((params->frame_length/(double)params->shift - 1)/2); int n_frames = (*(pfundf))->size; int n_frames_new = n_frames + 2*empty_frames; /* Set pointers */ gsl_vector *fundf = *pfundf; gsl_vector *gain = *pgain; gsl_vector *uvgain = *puvgain; gsl_vector *h1h2 = *ph1h2; gsl_vector *naq = *pnaq; gsl_matrix *hnr = *phnr; gsl_matrix *spectral_tilt = *pspectral_tilt; gsl_matrix *LSF = *pLSF; gsl_matrix *LSF2 = *pLSF2; gsl_matrix *harmonics = *pharmonics; gsl_matrix *waveform = *pwaveform; gsl_matrix *fundf_candidates = *pfundf_candidates; gsl_matrix *fftmatrix_vt = *pfftmatrix_vt; gsl_matrix *fftmatrix_src = *pfftmatrix_src; gsl_matrix *fftmatrix_uv = *pfftmatrix_uv; /* Allocate new variables */ gsl_vector *fundf_new = gsl_vector_alloc(n_frames_new); gsl_vector *gain_new = gsl_vector_alloc(n_frames_new); gsl_vector *uvgain_new = gsl_vector_alloc(n_frames_new); gsl_vector *h1h2_new = gsl_vector_alloc(n_frames_new); gsl_vector *naq_new = gsl_vector_alloc(n_frames_new); gsl_matrix *hnr_new = gsl_matrix_alloc(n_frames_new,hnr->size2); gsl_matrix *spectral_tilt_new = gsl_matrix_alloc(n_frames_new,spectral_tilt->size2); gsl_matrix *LSF_new = gsl_matrix_alloc(n_frames_new,LSF->size2); gsl_matrix *LSF2_new = gsl_matrix_alloc(n_frames_new,LSF2->size2); gsl_matrix *harmonics_new = gsl_matrix_alloc(n_frames_new,harmonics->size2); gsl_matrix *waveform_new = gsl_matrix_alloc(n_frames_new,waveform->size2); gsl_matrix *fundf_candidates_new = gsl_matrix_alloc(n_frames_new,fundf_candidates->size2); gsl_matrix *fftmatrix_vt_new = gsl_matrix_alloc(n_frames_new,fftmatrix_vt->size2); gsl_matrix *fftmatrix_src_new = gsl_matrix_alloc(n_frames_new,fftmatrix_src->size2); gsl_matrix *fftmatrix_uv_new = gsl_matrix_alloc(n_frames_new,fftmatrix_uv->size2); /* Fill in values */ for(i=0;i<n_frames;i++) { gsl_vector_set(fundf_new,i+empty_frames,gsl_vector_get(fundf,i)); gsl_vector_set(gain_new,i+empty_frames,gsl_vector_get(gain,i)); gsl_vector_set(uvgain_new,i+empty_frames,gsl_vector_get(uvgain,i)); gsl_vector_set(h1h2_new,i+empty_frames,gsl_vector_get(h1h2,i)); gsl_vector_set(naq_new,i+empty_frames,gsl_vector_get(naq,i)); for(j=0;j<hnr->size2;j++) gsl_matrix_set(hnr_new,i+empty_frames,j,gsl_matrix_get(hnr,i,j)); for(j=0;j<spectral_tilt->size2;j++) gsl_matrix_set(spectral_tilt_new,i+empty_frames,j,gsl_matrix_get(spectral_tilt,i,j)); for(j=0;j<LSF->size2;j++) { gsl_matrix_set(LSF_new,i+empty_frames,j,gsl_matrix_get(LSF,i,j)); gsl_matrix_set(LSF2_new,i+empty_frames,j,gsl_matrix_get(LSF2,i,j)); } for(j=0;j<harmonics->size2;j++) gsl_matrix_set(harmonics_new,i+empty_frames,j,gsl_matrix_get(harmonics,i,j)); for(j=0;j<waveform->size2;j++) gsl_matrix_set(waveform_new,i+empty_frames,j,gsl_matrix_get(waveform,i,j)); for(j=0;j<fundf_candidates->size2;j++) gsl_matrix_set(fundf_candidates_new,i+empty_frames,j,gsl_matrix_get(fundf_candidates,i,j)); for(j=0;j<fftmatrix_vt->size2;j++) { gsl_matrix_set(fftmatrix_vt_new,i+empty_frames,j,gsl_matrix_get(fftmatrix_vt,i,j)); gsl_matrix_set(fftmatrix_src_new,i+empty_frames,j,gsl_matrix_get(fftmatrix_src,i,j)); gsl_matrix_set(fftmatrix_uv_new,i+empty_frames,j,gsl_matrix_get(fftmatrix_uv,i,j)); } } /* Add empty values at the beginning */ for(i=0;i<empty_frames;i++) { gsl_vector_set(fundf_new,i,gsl_vector_get(fundf,empty_frames)); gsl_vector_set(gain_new,i,gsl_vector_get(gain,empty_frames)); gsl_vector_set(uvgain_new,i,gsl_vector_get(uvgain,empty_frames)); gsl_vector_set(h1h2_new,i,gsl_vector_get(h1h2,empty_frames)); gsl_vector_set(naq_new,i,gsl_vector_get(naq,empty_frames)); for(j=0;j<hnr->size2;j++) gsl_matrix_set(hnr_new,i,j,gsl_matrix_get(hnr,empty_frames,j)); for(j=0;j<spectral_tilt->size2;j++) gsl_matrix_set(spectral_tilt_new,i,j,gsl_matrix_get(spectral_tilt,empty_frames,j)); for(j=0;j<LSF->size2;j++) { gsl_matrix_set(LSF_new,i,j,gsl_matrix_get(LSF,empty_frames,j)); gsl_matrix_set(LSF2_new,i,j,gsl_matrix_get(LSF2,empty_frames,j)); } for(j=0;j<harmonics->size2;j++) gsl_matrix_set(harmonics_new,i,j,gsl_matrix_get(harmonics,empty_frames,j)); for(j=0;j<waveform->size2;j++) gsl_matrix_set(waveform_new,i,j,gsl_matrix_get(waveform,empty_frames,j)); for(j=0;j<fundf_candidates->size2;j++) gsl_matrix_set(fundf_candidates_new,i,j,gsl_matrix_get(fundf_candidates,empty_frames,j)); for(j=0;j<fftmatrix_vt->size2;j++) { gsl_matrix_set(fftmatrix_vt_new,i,j,gsl_matrix_get(fftmatrix_vt,empty_frames,j)); gsl_matrix_set(fftmatrix_src_new,i,j,gsl_matrix_get(fftmatrix_src,empty_frames,j)); gsl_matrix_set(fftmatrix_uv_new,i,j,gsl_matrix_get(fftmatrix_uv,empty_frames,j)); } } /* Add empty values in the end */ for(i=n_frames_new-empty_frames-1;i<n_frames_new;i++) { gsl_vector_set(fundf_new,i,gsl_vector_get(fundf,n_frames-1)); gsl_vector_set(gain_new,i,gsl_vector_get(gain,n_frames-1)); gsl_vector_set(uvgain_new,i,gsl_vector_get(uvgain,n_frames-1)); gsl_vector_set(h1h2_new,i,gsl_vector_get(h1h2,n_frames-1)); gsl_vector_set(naq_new,i,gsl_vector_get(naq,n_frames-1)); for(j=0;j<hnr->size2;j++) gsl_matrix_set(hnr_new,i,j,gsl_matrix_get(hnr,n_frames-1,j)); for(j=0;j<spectral_tilt->size2;j++) gsl_matrix_set(spectral_tilt_new,i,j,gsl_matrix_get(spectral_tilt,n_frames-1,j)); for(j=0;j<LSF->size2;j++) { gsl_matrix_set(LSF_new,i,j,gsl_matrix_get(LSF,n_frames-1,j)); gsl_matrix_set(LSF2_new,i,j,gsl_matrix_get(LSF2,n_frames-1,j)); } for(j=0;j<harmonics->size2;j++) gsl_matrix_set(harmonics_new,i,j,gsl_matrix_get(harmonics,n_frames-1,j)); for(j=0;j<waveform->size2;j++) gsl_matrix_set(waveform_new,i,j,gsl_matrix_get(waveform,n_frames-1,j)); for(j=0;j<fundf_candidates->size2;j++) gsl_matrix_set(fundf_candidates_new,i,j,gsl_matrix_get(fundf_candidates,n_frames-1,j)); for(j=0;j<fftmatrix_vt->size2;j++) { gsl_matrix_set(fftmatrix_vt_new,i,j,gsl_matrix_get(fftmatrix_vt,n_frames-1,j)); gsl_matrix_set(fftmatrix_src_new,i,j,gsl_matrix_get(fftmatrix_src,n_frames-1,j)); gsl_matrix_set(fftmatrix_uv_new,i,j,gsl_matrix_get(fftmatrix_uv,n_frames-1,j)); } } /* Free old variables */ gsl_vector_free(fundf); gsl_vector_free(gain); gsl_vector_free(uvgain); gsl_vector_free(h1h2); gsl_vector_free(naq); gsl_matrix_free(hnr); gsl_matrix_free(spectral_tilt); gsl_matrix_free(LSF); gsl_matrix_free(LSF2); gsl_matrix_free(harmonics); gsl_matrix_free(waveform); gsl_matrix_free(fundf_candidates); gsl_matrix_free(fftmatrix_vt); gsl_matrix_free(fftmatrix_src); gsl_matrix_free(fftmatrix_uv); /* Set new variables to pointers */ *(pfundf) = fundf_new; *(pgain) = gain_new; *(puvgain) = uvgain_new; *(ph1h2) = h1h2_new; *(pnaq) = naq_new; *(phnr) = hnr_new; *(pspectral_tilt) = spectral_tilt_new; *(pLSF) = LSF_new; *(pLSF2) = LSF2_new; *(pharmonics) = harmonics_new; *(pwaveform) = waveform_new; *(pfundf_candidates) = fundf_candidates_new; *(pfftmatrix_vt) = fftmatrix_vt_new; *(pfftmatrix_src) = fftmatrix_src_new; *(pfftmatrix_uv) = fftmatrix_uv_new; } /** * Function LPC * * Calculate Linear Prediction (LP) coefficients using * autocorrelation method. * * @param frame pointer to the samples * @param a pointer to LPC coefficient vector */ void LPC(gsl_vector *frame, gsl_vector *a) { int i,j,n,s,p = a->size-1; double win = 0,sum = 0; gsl_vector *wframe = gsl_vector_alloc(frame->size); gsl_vector *a_temp = gsl_vector_calloc(p); gsl_vector *r = gsl_vector_calloc(p+1); gsl_vector *b = gsl_vector_alloc(p); gsl_matrix *R = gsl_matrix_alloc (p, p); gsl_permutation *perm = gsl_permutation_alloc(p); /* Windowing (choose window) */ for(i=0; i<frame->size; i++) { if (WIN_TYPE == HANN_WIN) win = HANN(i,frame->size); else if (WIN_TYPE == BLACKMAN_WIN) win = BLACKMAN(i,frame->size); else if (WIN_TYPE == HAMMING_WIN) win = HAMMING(i,frame->size); else win = 1.0; gsl_vector_set(wframe, i, gsl_vector_get(frame, i)*win); } /* Autocorrelation sequence */ for(i=0; i<p+1;i++) { for(n=i; n<wframe->size; n++) { gsl_vector_set(r, i, gsl_vector_get(r, i)+gsl_vector_get(wframe, n)*gsl_vector_get(wframe, n-i)); } } /* Autocorrelation matrix (Toeplitz) */ for(i=0; i<p;i++) { for(j=0; j<p; j++) { gsl_matrix_set(R, i, j, gsl_vector_get(r, abs(i-j))); sum += gsl_vector_get(r, abs(i-j)); } } /* Vector b */ for(i=1; i<p+1; i++) { gsl_vector_set(b, i-1, gsl_vector_get(r, i)); sum += gsl_vector_get(r, i); } /* Ra=r solver (LU-decomposition) (Do not evaluate LU if sum = 0) */ if(sum != 0) { gsl_linalg_LU_decomp(R, perm, &s); gsl_linalg_LU_solve(R, perm, b, a_temp); } /* Set LP-coefficients to vector "a" */ for(i=1; i<a->size; i++) { gsl_vector_set(a, i, (-1)*gsl_vector_get(a_temp, i-1)); } gsl_vector_set(a, 0, 1); /* Remove real roots */ if(ROOT_SCALING == 1) { if(a->size > ROOT_SCALE_MIN_DEGREE) { RealRootScale(a); } } /* Replace NaN-values with zeros in case of all-zero frames */ for(i=0;i<a->size;i++) { if(gsl_isnan(gsl_vector_get(a,i))) gsl_vector_set(a,i,0); } /* Free memory */ gsl_vector_free(wframe); gsl_vector_free(a_temp); gsl_vector_free(r); gsl_vector_free(b); gsl_matrix_free(R); gsl_permutation_free(perm); } /** * Function LPC_Postfilter * * Enhance Formants by modifying the re-evaluated the LPC power spectrum, * and evaluating the LPC-coefficients again * * @param LSF pointer to the LSF matrix * @param params parameter structure */ void LPC_Postfilter(gsl_matrix *LSF, PARAM *params) { int i,j,fi,s,nf,p = LSF->size2,n = POWER_SPECTRUM_FRAME_LEN; double A[n]; double B[n]; double data[n]; gsl_vector *a = gsl_vector_alloc(p+1); gsl_vector *a_temp = gsl_vector_calloc(p); gsl_vector *r = gsl_vector_alloc(p+1); gsl_vector *rr = gsl_vector_alloc(n); gsl_vector *S = gsl_vector_alloc(n); gsl_vector *b = gsl_vector_alloc(p); gsl_matrix *R = gsl_matrix_alloc (p, p); gsl_vector *formants = gsl_vector_calloc(100); gsl_permutation *perm = gsl_permutation_alloc(p); gsl_complex ca; gsl_complex cb; gsl_fft_real_wavetable *wreal = gsl_fft_real_wavetable_alloc(n); gsl_fft_real_workspace *work = gsl_fft_real_workspace_alloc(n); gsl_fft_complex_wavetable *cwt = gsl_fft_complex_wavetable_alloc(n); gsl_fft_complex_workspace *cwork = gsl_fft_complex_workspace_alloc(n); double xa[2*n]; double xb[2*n]; /* Initialize B */ B[0] = 1; for(i=1;i<n;i++) B[i] = 0; gsl_fft_real_transform(B,1,n,wreal,work); gsl_complex_packed_array complex_coefficients_b = xb; gsl_fft_halfcomplex_unpack(B,complex_coefficients_b,1,n); /* Loop for every index */ for(fi=0;fi<LSF->size1;fi++) { /* Convert LSF to LPC */ lsf2poly(LSF,a,fi,1); /* Evaluate power spectrum S, this assumes an all-pole model (B = 1) */ for(i=0;i<p+1;i++) A[i] = gsl_vector_get(a,i); for(i=p+1;i<n;i++) A[i] = 0; gsl_fft_real_transform(A,1,n,wreal,work); gsl_complex_packed_array complex_coefficients_a = xa; gsl_fft_halfcomplex_unpack(A,complex_coefficients_a,1,n); for(i=0;i<n;i++) { GSL_SET_COMPLEX(&ca, REAL(complex_coefficients_a,i), IMAG(complex_coefficients_a,i)); GSL_SET_COMPLEX(&cb, REAL(complex_coefficients_b,i), IMAG(complex_coefficients_b,i)); ca = gsl_complex_div(cb, ca); gsl_vector_set(S,i,gsl_complex_abs2(ca)); } /* Modification of the power spectrum S */ GetFormants(S,formants,&nf); ModPowerSpectrum(S,formants,nf,params->formant_enh_coeff,params->formant_enh_lpc_delta); /* Construct autocorrelation r */ for(i=0;i<n;i++) data[i] = gsl_vector_get(S,i); gsl_fft_real_unpack(data, complex_coefficients_a, 1, n); gsl_fft_complex_inverse(complex_coefficients_a, 1, n, cwt, cwork); for(i=0;i<2*n;i = i + 2) gsl_vector_set(rr,i/2,xa[i]); for(i=0;i<p+1;i++) gsl_vector_set(r,i,gsl_vector_get(rr,i)); /* Construct LPC */ for(i=0; i<p;i++) for(j=0; j<p; j++) gsl_matrix_set(R, i, j, gsl_vector_get(r, abs(i-j))); for(i=1; i<p+1; i++) gsl_vector_set(b, i-1, gsl_vector_get(r, i)); gsl_linalg_LU_decomp(R, perm, &s); gsl_linalg_LU_solve(R, perm, b, a_temp); for(i=1; i<a->size; i++) gsl_vector_set(a, i, (-1.0)*gsl_vector_get(a_temp, i-1)); gsl_vector_set(a, 0, 1); for(i=0;i<a->size;i++) if(gsl_isnan(gsl_vector_get(a,i))) gsl_vector_set(a,i,0); /* Convert LPC back to LSF */ Convert_matrix_to_LSF(LSF, a, fi); } /* Free memory */ gsl_vector_free(formants); gsl_vector_free(a); gsl_vector_free(a_temp); gsl_vector_free(r); gsl_vector_free(rr); gsl_vector_free(S); gsl_vector_free(b); gsl_matrix_free(R); gsl_permutation_free(perm); gsl_fft_real_wavetable_free(wreal); gsl_fft_real_workspace_free(work); gsl_fft_complex_wavetable_free(cwt); gsl_fft_complex_workspace_free(cwork); } /** * Function ModPowerSpectrum * * Modify power spectrum in order to enhance formants * * @param s pointer to power spectrum vector * @param gamma enhancement coefficient */ void ModPowerSpectrum(gsl_vector *s, gsl_vector *formants, int n, double gamma, double delta) { int i,j; /* Modify spectrum at frequencies 0 and fs/2 within a constant number of bins from the formant peak */ for(i=0;i<gsl_vector_get(formants,0) - delta;i++) gsl_vector_set(s,i,gsl_vector_get(s,i)*gamma); for(i=gsl_vector_get(formants,n-1) + delta+1;i<s->size/2+1;i++) gsl_vector_set(s,i,gsl_vector_get(s,i)*gamma); /* Modify spectrum within a constant number of bins from the formant peaks */ for(i=0;i<n-1;i++) { for(j=gsl_vector_get(formants,i) + delta+1;j<gsl_vector_get(formants,i+1) - delta;j++) gsl_vector_set(s,j,gsl_vector_get(s,j)*gamma); } /* Reconstruct image spectrum */ if((s->size)%2 == 0) for(i=1;i<s->size/2;i++) gsl_vector_set(s,s->size-i,gsl_vector_get(s,i)); else for(i=1;i<ceil(s->size/2)+1;i++) gsl_vector_set(s,s->size-i,gsl_vector_get(s,i)); } /** * Function GetFormants * * Get formant positions from smooth power spectrum * * @param s pointer to power spectrum vector * @param formants pointer to forman position vector */ void GetFormants(gsl_vector *s, gsl_vector *formants, int *n) { int i,ind; gsl_vector *sd = gsl_vector_alloc(s->size); /* Differentiate s */ gsl_vector_memcpy(sd,s); Differentiate_noleak(sd); /* Find formant peaks */ ind = 0; for(i=0;i<round(s->size/2)+1;i++) { if(gsl_vector_get(sd,i) >= 0 && gsl_vector_get(sd,i+1) <= 0) { gsl_vector_set(formants,ind,i); ind++; } } /* Set the number of formants */ (*n) = ind; /* Free memory */ gsl_vector_free(sd); } /** * Function WLPC * * Calculate Warped Linear Prediction (Warped LP) coefficients using * autocorrelation method. * * @param frame pointer to the samples * @param a pointer to coefficiets * @param p LPC degree * @param lambda warping coefficient */ void WLPC(gsl_vector *frame, gsl_vector *a, double lambda) { int i,j,s,p = a->size-1; double win = 0,sum = 0; gsl_vector *wframe = gsl_vector_alloc(frame->size); gsl_vector *a_temp = gsl_vector_calloc(p); gsl_vector *r = gsl_vector_calloc(p+1); gsl_vector *b = gsl_vector_alloc(p); gsl_matrix *R = gsl_matrix_alloc (p, p); gsl_permutation *perm = gsl_permutation_alloc(p); /* Windowing (choose window) */ for(i=0; i<frame->size; i++) { if (WIN_TYPE == HANN_WIN) win = HANN(i,frame->size); else if (WIN_TYPE == BLACKMAN_WIN) win = BLACKMAN(i,frame->size); else if (WIN_TYPE == HAMMING_WIN) win = HAMMING(i,frame->size); else win = 1.0; gsl_vector_set(wframe, i, gsl_vector_get(frame, i)*win); } /* Copy warped frame */ gsl_vector *wframe_w = gsl_vector_alloc(wframe->size); gsl_vector_memcpy(wframe_w,wframe); /* Set r(0) */ for(i=0;i<wframe->size;i++) { gsl_vector_set(r, 0, gsl_vector_get(r,0) + gsl_vector_get(wframe,i)*gsl_vector_get(wframe,i)); } /* Evaluate r */ for(i=1;i<p+1;i++) { AllPassDelay(wframe_w,lambda); for(j=0;j<wframe->size;j++) { gsl_vector_set(r, i, gsl_vector_get(r,i) + gsl_vector_get(wframe,j)*gsl_vector_get(wframe_w,j)); } } /* Autocorrelation matrix (Toeplitz) */ for(i=0; i<p;i++) { for(j=0; j<p; j++) { gsl_matrix_set(R, i, j, gsl_vector_get(r, abs(i-j))); sum += gsl_vector_get(r, abs(i-j)); } } /* Vector b */ for(i=1; i<p+1; i++) { gsl_vector_set(b, i-1, gsl_vector_get(r, i)); sum += gsl_vector_get(r, i); } /* Ra=r solver (LU-decomposition) (Do not evaluate LU if sum = 0) */ if(sum != 0) { gsl_linalg_LU_decomp(R, perm, &s); gsl_linalg_LU_solve(R, perm, b, a_temp); } /* Set LP-coefficients to vector "a" */ for(i=1; i<a->size; i++) { gsl_vector_set(a, i, (-1)*gsl_vector_get(a_temp, i-1)); } gsl_vector_set(a, 0, 1); /* Remove real roots */ if(ROOT_SCALING == 1) { if(a->size > ROOT_SCALE_MIN_DEGREE) { RealRootScale(a); } } /* Replace NaN-values with zeros in case of all-zero frames */ for(i=0;i<a->size;i++) { if(gsl_isnan(gsl_vector_get(a,i))) gsl_vector_set(a,i,0); } /* Free memory */ gsl_vector_free(wframe); gsl_vector_free(wframe_w); gsl_vector_free(a_temp); gsl_vector_free(r); gsl_vector_free(b); gsl_matrix_free(R); gsl_permutation_free(perm); } /** * Function SWLP * * Calculate Stabilized Weighted Linear Prediction (SWLP) coefficients * (unstabilized can be evaluated by switching "stabilized" to zero) * * @param frame pointer to the samples * @param a pointer to coefficiets * @param p LPC degree * @param M weighting window length * @param lag lag of the weighting window */ void SWLP(gsl_vector *frame, gsl_vector *a, int M, int lag, int weighting, gsl_vector *fundf, int FS, int index, gsl_vector *glottsig, int stabilized) { int i,j,k,s,p = a->size-1; double win = 0,sum = 0; gsl_vector *wframe = gsl_vector_alloc(frame->size); gsl_vector *weight = gsl_vector_calloc(frame->size+p); /* Windowing (choose window) */ for(i=0; i<frame->size; i++) { if (WIN_TYPE == HANN_WIN) win = HANN(i,frame->size); else if (WIN_TYPE == BLACKMAN_WIN) win = BLACKMAN(i,frame->size); else if (WIN_TYPE == HAMMING_WIN) win = HAMMING(i,frame->size); else win = 1.0; gsl_vector_set(wframe, i, gsl_vector_get(frame, i)*win); } /* Evaluate weighting function */ if(weighting == LP_WEIGHTING_ID_STE) Eval_STE_weight(wframe,weight,M,lag); else if(weighting == LP_WEIGHTING_ID_GCI) { //Eval_GCI_weight1(glottsig,weight,fundf,FS,index); // Original Eval_GCI_weight2(glottsig,weight,fundf,FS,index); // Manu's work //Eval_GCI_weight3(glottsig,weight,fundf,FS,index); // Manu's work with F0 adaptation } /* Make sure weights are positive */ for(i=0;i<weight->size;i++) if(gsl_vector_get(weight,i) <= 0) gsl_vector_set(weight,i,0.0001); /* Create partial weights */ gsl_matrix *Z = gsl_matrix_calloc(wframe->size+p,p+1); // Partial weights gsl_matrix *Y = gsl_matrix_calloc(wframe->size+p,p+1); // Delayed and weighted versions of the signal for(i=0;i<weight->size;i++) gsl_matrix_set(Z,i,0,sqrt(gsl_vector_get(weight,i))); for(i=0;i<wframe->size;i++) gsl_matrix_set(Y,i,0,gsl_vector_get(wframe,i)*sqrt(gsl_vector_get(weight,i))); for(i=0;i<p;i++) { if(stabilized == 1) { for(j=i+1;j<Z->size1;j++) { gsl_matrix_set(Z,j,i+1,GSL_MAX(sqrt(gsl_vector_get(weight,j)/gsl_vector_get(weight,j-1)),1)*gsl_matrix_get(Z,j-1,i)); } } else { for(j=i+1;j<Z->size1;j++) { gsl_matrix_set(Z,j,i+1,sqrt(gsl_vector_get(weight,j))); } } for(j=0;j<wframe->size;j++) { gsl_matrix_set(Y,j+i+1,i+1,gsl_matrix_get(Z,j+i+1,i+1)*gsl_vector_get(wframe,j)); } } /* Autocorrelation matrix R (R = (YT*Y)/N, size p*p) and vector b (size p) */ gsl_matrix *R = gsl_matrix_calloc(p,p); gsl_vector *b = gsl_vector_calloc(p); for(i=0;i<Y->size2;i++) { for(j=0;j<Y->size2;j++) { if(i > 0 && j > 0) { for(k=0;k<Y->size1;k++) { gsl_matrix_set(R,i-1,j-1,gsl_matrix_get(R,i-1,j-1) + gsl_matrix_get(Y,k,i)*gsl_matrix_get(Y,k,j)); } gsl_matrix_set(R,i-1,j-1,gsl_matrix_get(R,i-1,j-1)/wframe->size); } if(i > 0 && j == 0) { for(k=0;k<Y->size1;k++) gsl_vector_set(b,i-1,gsl_vector_get(b,i-1) + gsl_matrix_get(Y,k,i)*gsl_matrix_get(Y,k,j)); gsl_vector_set(b,i-1,gsl_vector_get(b,i-1)/wframe->size); sum += gsl_vector_get(b,i-1); } } } /* Ra=r solver (LU-decomposition) (Do not evaluate LU if sum = 0) */ gsl_vector *a_temp = gsl_vector_calloc(p); gsl_permutation *perm = gsl_permutation_alloc(p); if(sum != 0) { gsl_linalg_LU_decomp(R, perm, &s); gsl_linalg_LU_solve(R, perm, b, a_temp); } /* Set LP-coefficients to vector "a" */ for(i=1; i<a->size; i++) { gsl_vector_set(a, i, (-1)*gsl_vector_get(a_temp, i-1)); } gsl_vector_set(a, 0, 1); /* Stabilize unstable filter by scaling the poles along the unit circle */ if(stabilized == 0) Pole_stabilize(a); /* Free memory */ gsl_vector_free(weight); gsl_vector_free(wframe); gsl_matrix_free(Z); gsl_matrix_free(Y); gsl_matrix_free(R); gsl_vector_free(b); gsl_vector_free(a_temp); gsl_permutation_free(perm); } /** * Function Eval_STE_weight * * Evaluate short time energy (STE) function for SWLP weighting * * @param frame pointer to the frame * @param ste pointer to the STE function * @param M weighting window length * @param lag time lag of estimating the STE */ void Eval_STE_weight(gsl_vector *frame, gsl_vector *ste, int M, int lag) { int i,j; for(i=0;i<ste->size;i++) { for(j=GSL_MAX(i-lag-M+1,0);j<GSL_MIN(i-lag+1,(int)frame->size);j++) { gsl_vector_set(ste,i,gsl_vector_get(ste,i) + gsl_vector_get(frame,j)*gsl_vector_get(frame,j)); } gsl_vector_set(ste,i,gsl_vector_get(ste,i) + DBL_EPSILON); } } /** * Function Eval_GCI_weight1 * * Find GCIs (Glottal Closure Instants) and construct weighting for de-emphasizing GCIs in (S)WLP * * @param ... * */ void Eval_GCI_weight1(gsl_vector *glottsig, gsl_vector *weight, gsl_vector *fundf, int FS, int index) { /* Estimate glottal closure instants */ gsl_vector *inds = Find_GCIs(glottsig, fundf, FS, index); /* If unvoiced or GCIs not found, simply set weight to 1 */ if(inds == NULL || gsl_vector_get(fundf,index) == 0) { if(inds != NULL) gsl_vector_free(inds); gsl_vector_set_all(weight,1); return; } /* Algorithm parameters */ double closed_time = 0.4; double gci_pos = 0.8; double deemph = 0.01; /* Initialize */ int i,j; int csamples = rint(closed_time*FS/gsl_vector_get(fundf,index)); /* Set weight according to GCIs */ gsl_vector_set_all(weight,1); for(i=0;i<inds->size;i++) { for(j=0;j<csamples;j++) { gsl_vector_set(weight,GSL_MIN(GSL_MAX(gsl_vector_get(inds,i)-rint(csamples*gci_pos)+j,0),weight->size-1),deemph); } } /* Free memory */ gsl_vector_free(inds); } /** * Function Eval_GCI_weight2 * * Find GCIs (Glottal Closure Instants) and construct weighting for de-emphasizing GCIs in (S)WLP * * @param ... * */ void Eval_GCI_weight2(gsl_vector *glottsig, gsl_vector *weight, gsl_vector *fundf, int FS, int index) { /* Estimate glottal closure instants */ gsl_vector *inds = Find_GCIs(glottsig, fundf, FS, index); /* If unvoiced or GCIs not found, simply set weight to 1 */ if(inds == NULL || gsl_vector_get(fundf,index) == 0) { if(inds != NULL) gsl_vector_free(inds); gsl_vector_set_all(weight,1); return; } /* Algorithm parameters */ double pq = 0.05; double dq = 0.7; double d = 0.00001; int nramp = DEFAULT_NRAMP; /* Sanity check */ if(dq + pq > 1.0) dq = 1.0 - pq; /* Initialize */ int i,j,t,t1 = 0,t2 = 0; /* Set weight according to GCIs */ gsl_vector_set_all(weight,d); for(i=0;i<inds->size-1;i++) { t = gsl_vector_get(inds,i+1)-gsl_vector_get(inds,i); t1 = round(dq*t); t2 = round(pq*t); while(t1+t2 > t) t1 = t1-1; for(j=gsl_vector_get(inds,i)+t2;j<gsl_vector_get(inds,i)+t2+t1;j++) gsl_vector_set(weight,j,1); if(nramp > 0) { for(j=gsl_vector_get(inds,i)+t2;j<gsl_vector_get(inds,i)+t2+nramp;j++) gsl_vector_set(weight,j,(j-gsl_vector_get(inds,i)-t2+1)/(nramp+1)); if(gsl_vector_get(inds,i)+t2+t1-nramp >= 0) for(j=gsl_vector_get(inds,i)+t2+t1-nramp;j<gsl_vector_get(inds,i)+t2+t1;j++) gsl_vector_set(weight,j,1.0-(j-gsl_vector_get(inds,i)-t2-t1+nramp+1)/(nramp+1)); } } /* Set last weighting */ i = i-1; int Nend = glottsig->size-(t2+gsl_vector_get(inds,i+1)); if(t2+gsl_vector_get(inds,i+1) < glottsig->size) { if(t1+t2 < Nend) { for(j=gsl_vector_get(inds,i+1)+t2;j<gsl_vector_get(inds,i+1)+t2+t1;j++) gsl_vector_set(weight,j,1); if(nramp > 0) { for(j=gsl_vector_get(inds,i+1)+t2;j<gsl_vector_get(inds,i+1)+t2+nramp;j++) gsl_vector_set(weight,j,(j-gsl_vector_get(inds,i+1)-t2+1)/(nramp+1)); for(j=gsl_vector_get(inds,i+1)+t2+t1-nramp;j<gsl_vector_get(inds,i+1)+t2+t1;j++) gsl_vector_set(weight,j,1.0-(j-gsl_vector_get(inds,i+1)-t2-t1+nramp+1)/(nramp+1)); } } else { t1 = Nend-t2; for(j=gsl_vector_get(inds,i+1)+t2;j<gsl_vector_get(inds,i+1)+t2+t1-1;j++) gsl_vector_set(weight,j,1); if(nramp > 0) for(j=gsl_vector_get(inds,i+1)+t2;j<gsl_vector_get(inds,i+1)+t2+nramp;j++) gsl_vector_set(weight,j,(j-gsl_vector_get(inds,i+1)-t2+1)/(nramp+1)); } } /* Free memory */ gsl_vector_free(inds); } /** * Function Eval_GCI_weight3 * * Find GCIs (Glottal Closure Instants) and construct weighting for de-emphasizing GCIs in (S)WLP * * @param ... * */ void Eval_GCI_weight3(gsl_vector *glottsig, gsl_vector *weight, gsl_vector *fundf, int FS, int index) { /* Estimate glottal closure instants */ gsl_vector *inds = Find_GCIs(glottsig, fundf, FS, index); /* If unvoiced or GCIs not found, simply set weight to 1 */ if(inds == NULL || gsl_vector_get(fundf,index) == 0) { if(inds != NULL) gsl_vector_free(inds); gsl_vector_set_all(weight,1); return; } /* Algorithm parameters */ double dq = 0.7; double pq = 0.05; double f0cut1 = 190; double f0cut2 = 320; double f0 = gsl_vector_get(fundf,index); if(f0 <= f0cut1) { dq = 0.9; pq = 0.05; } else if(f0 < f0cut2) { dq = 0.55; pq = 0.05; } else { dq = 0.7; pq = 0.05; } double d = 0.00001; int nramp = DEFAULT_NRAMP; /* Sanity check */ if(dq + pq > 1.0) dq = 1.0 - pq; /* Initialize */ int i,j,t,t1 = 0,t2 = 0; /* Set weight according to GCIs */ gsl_vector_set_all(weight,d); for(i=0;i<inds->size-1;i++) { t = gsl_vector_get(inds,i+1)-gsl_vector_get(inds,i); t1 = round(dq*t); t2 = round(pq*t); while(t1+t2 > t) t1 = t1-1; for(j=gsl_vector_get(inds,i)+t2;j<gsl_vector_get(inds,i)+t2+t1;j++) gsl_vector_set(weight,j,1); if(nramp > 0) { for(j=gsl_vector_get(inds,i)+t2;j<gsl_vector_get(inds,i)+t2+nramp;j++) gsl_vector_set(weight,j,(j-gsl_vector_get(inds,i)-t2+1)/(nramp+1)); if(gsl_vector_get(inds,i)+t2+t1-nramp >= 0) for(j=gsl_vector_get(inds,i)+t2+t1-nramp;j<gsl_vector_get(inds,i)+t2+t1;j++) gsl_vector_set(weight,j,1.0-(j-gsl_vector_get(inds,i)-t2-t1+nramp+1)/(nramp+1)); } } /* Set last weighting */ i = i-1; int Nend = glottsig->size-(t2+gsl_vector_get(inds,i+1)); if(t2+gsl_vector_get(inds,i+1) < glottsig->size) { if(t1+t2 < Nend) { for(j=gsl_vector_get(inds,i+1)+t2;j<gsl_vector_get(inds,i+1)+t2+t1;j++) gsl_vector_set(weight,j,1); if(nramp > 0) { for(j=gsl_vector_get(inds,i+1)+t2;j<gsl_vector_get(inds,i+1)+t2+nramp;j++) gsl_vector_set(weight,j,(j-gsl_vector_get(inds,i+1)-t2+1)/(nramp+1)); for(j=gsl_vector_get(inds,i+1)+t2+t1-nramp;j<gsl_vector_get(inds,i+1)+t2+t1;j++) gsl_vector_set(weight,j,1.0-(j-gsl_vector_get(inds,i+1)-t2-t1+nramp+1)/(nramp+1)); } } else { t1 = Nend-t2; for(j=gsl_vector_get(inds,i+1)+t2;j<gsl_vector_get(inds,i+1)+t2+t1-1;j++) gsl_vector_set(weight,j,1); if(nramp > 0) for(j=gsl_vector_get(inds,i+1)+t2;j<gsl_vector_get(inds,i+1)+t2+nramp;j++) gsl_vector_set(weight,j,(j-gsl_vector_get(inds,i+1)-t2+1)/(nramp+1)); } } // TEST /* Windowing */ //for(i=0; i<weight->size; i++) // gsl_vector_set(weight, i, gsl_vector_get(weight, i)*BLACKMAN(i,weight->size)); /* Free memory */ gsl_vector_free(inds); } /** * Function SXLP * * Calculate Stabilized eXtended Linear Prediction (SXLP) coefficients * (unstabilized can be evaluated by switching "stabilized" to zero) * * @param frame pointer to the samples * @param a pointer to coefficiets * @param p LPC degree * @param w weighting window length */ void SXLP(gsl_vector *frame, gsl_vector *a, int w, int stabilized) { int i,j,k,s,N = frame->size,p = a->size-1; double win = 0,sum = 0; gsl_vector *wframe = gsl_vector_alloc(frame->size); /* Windowing (choose window) */ for(i=0; i<frame->size; i++) { if (WIN_TYPE == HANN_WIN) win = HANN(i,frame->size); else if (WIN_TYPE == BLACKMAN_WIN) win = BLACKMAN(i,frame->size); else if (WIN_TYPE == HAMMING_WIN) win = HAMMING(i,frame->size); else win = 1.0; gsl_vector_set(wframe, i, gsl_vector_get(frame, i)*win); } /* Initialize */ double mem = (w-1.0)/w; gsl_vector *Z = gsl_vector_alloc(p+1); gsl_vector *Zp = gsl_vector_calloc(p+1); gsl_vector *ac = gsl_vector_calloc(p+1); gsl_matrix *D = gsl_matrix_calloc(N+p,p+1); for(i=0;i<N+p;i++) for(j=0;j<i+1;j++) if(i-j<p+1 && j<N) gsl_matrix_set(D,i,i-j,gsl_vector_get(wframe,j)); /* Create matrix D */ for(i=0;i<N+p;i++) { for(j=0;j<p+1;j++) gsl_vector_set(ac,j, mem*gsl_vector_get(ac,j) + (1.0-mem) * (fabs(gsl_matrix_get(D,i,0)) + fabs(gsl_matrix_get(D,i,j)))); if(stabilized == 1) { for(j=1;j<p+1;j++) gsl_vector_set(Z,j,GSL_MAX(gsl_vector_get(ac,j),gsl_vector_get(Zp,j-1))); gsl_vector_set(Z,0,GSL_MAX(gsl_vector_get(ac,0),0)); } else for(j=0;j<p+1;j++) gsl_vector_set(Z,j,gsl_vector_get(ac,j)); for(j=0;j<p+1;j++) gsl_matrix_set(D,i,j,gsl_matrix_get(D,i,j)*gsl_vector_get(Z,j)); if(stabilized == 1) for(j=0;j<p+1;j++) gsl_vector_set(Zp,j,gsl_vector_get(Z,j)); } /* Autocorrelation matrix R (R = (DT*D)/N, size p*p) and vector b (size p) */ gsl_matrix *R = gsl_matrix_calloc(p,p); gsl_vector *b = gsl_vector_calloc(p); for(i=0;i<D->size2;i++) { for(j=0;j<D->size2;j++) { if(i > 0 && j > 0) { for(k=0;k<D->size1;k++) { gsl_matrix_set(R,i-1,j-1,gsl_matrix_get(R,i-1,j-1) + gsl_matrix_get(D,k,i)*gsl_matrix_get(D,k,j)); } gsl_matrix_set(R,i-1,j-1,gsl_matrix_get(R,i-1,j-1)/wframe->size); } if(i > 0 && j == 0) { for(k=0;k<D->size1;k++) gsl_vector_set(b,i-1,gsl_vector_get(b,i-1) + gsl_matrix_get(D,k,i)*gsl_matrix_get(D,k,j)); gsl_vector_set(b,i-1,gsl_vector_get(b,i-1)/wframe->size); sum += gsl_vector_get(b,i-1); } } } /* Ra=r solver (LU-decomposition) (Do not evaluate LU if sum = 0) */ gsl_vector *a_temp = gsl_vector_calloc(p); gsl_permutation *perm = gsl_permutation_alloc(p); if(sum != 0) { gsl_linalg_LU_decomp(R, perm, &s); gsl_linalg_LU_solve(R, perm, b, a_temp); } /* Set LP-coefficients to vector "a" */ for(i=1; i<a->size; i++) { gsl_vector_set(a, i, (-1)*gsl_vector_get(a_temp, i-1)); } gsl_vector_set(a, 0, 1); /* Stabilize unstable filter by scaling the poles along the unit circle */ if(stabilized == 0) Pole_stabilize(a); /* Free memory */ gsl_matrix_free(D); gsl_vector_free(Z); gsl_vector_free(Zp); gsl_vector_free(ac); gsl_vector_free(wframe); gsl_matrix_free(R); gsl_vector_free(b); gsl_vector_free(a_temp); gsl_permutation_free(perm); } /** * Function AllPassDelay * * All pass delay filter for WLPC. * * @param signal pointer to the samples * @param lambda all-pass filter coefficient */ void AllPassDelay(gsl_vector *signal, double lambda) { int i,j,n=2; double sum; /* Create coefficient arrays: B = [-lambda 1], A = [1 -lambda] */ double B[2] = {-lambda,1.0}; double A[2] = {0,lambda}; /* Zeropad the beginning of the signal */ gsl_vector *signal_zp = gsl_vector_calloc(signal->size+n); for(i=n;i<signal_zp->size;i++) { gsl_vector_set(signal_zp,i,gsl_vector_get(signal,i-n)); } /* Copy signal */ gsl_vector *signal_zp_orig = gsl_vector_alloc(signal_zp->size); gsl_vector_memcpy(signal_zp_orig,signal_zp); /* Filter */ for(i=n;i<signal_zp->size;i++) { sum = 0; for(j=0;j<n;j++) { sum += gsl_vector_get(signal_zp_orig,i-j)*B[j] + gsl_vector_get(signal_zp,i-j)*A[j]; } gsl_vector_set(signal_zp,i,sum); } /* Remove zeropadding from the signal */ for(i=n;i<signal_zp->size;i++) { gsl_vector_set(signal,i-n,gsl_vector_get(signal_zp,i)); } /* Free memory */ gsl_vector_free(signal_zp); gsl_vector_free(signal_zp_orig); } /** * Function Filter * * FIR-Filter implementation. * NB! Filtering starts at i=p, so there is a pre-frame attached to the actual frame. * * @param frame pointer to the samples * @param result pointer to the filtered samples * @param a LPC coefficients */ void Filter(gsl_vector *frame, gsl_vector *result, gsl_vector *a) { double sum; int i,j,p = frame->size-result->size; /* Filter signal */ for(i=p; i<frame->size; i++) { sum = 0; for(j=0; j<a->size; j++) { sum += gsl_vector_get(frame, i-j)*gsl_vector_get(a, j); } gsl_vector_set(result, i-p, sum); } } /** * Function RealRootScale * * Scale the real roots of the LPC-coefficients to near origo * * @param a pointer to the samples * */ void RealRootScale(gsl_vector *a) { int i,j,k; int n_c = a->size; int n_r = 2*(n_c-1); double coeffs[n_c]; double roots[n_r]; double real_roots[10] = {0}; /* Copy coefficients to "coeffs" */ gsl_vector_reverse(a); for(i=0; i<n_c; i++) { coeffs[i] = gsl_vector_get(a, i); } /* Solve roots */ gsl_poly_complex_workspace *w = gsl_poly_complex_workspace_alloc(n_c); gsl_poly_complex_solve(coeffs, n_c, w, roots); gsl_poly_complex_workspace_free(w); /* Find real roots */ j = 0; for (i=0; i<n_r/2; i++) { if(fabs(roots[2*i+1]) < ROOT_SCALE_ZERO_LIMIT) { real_roots[j] = roots[2*i]; j++; } } /* Scale roots */ gsl_vector_reverse(a); gsl_vector *temp = gsl_vector_calloc(a->size); double y; for(i=0; i<10; i++) { if(real_roots[i] != 0) { /* Deconvolve */ y = 0; for(j=0; j<n_c; j++) { gsl_vector_set(a, j, gsl_vector_get(a, j) + y*real_roots[i]); y = gsl_vector_get(a, j); } gsl_vector_set(a, a->size-1, 0); /* Scale the root */ double scaled_factor[2] = {1, -1*ROOT_SCALE_FACTOR*real_roots[i]}; /* Convolve with scaled root */ for(j=0; j<a->size; j++) { y = 0; for(k=0; k<=GSL_MIN(j, 1); k++) { y += gsl_vector_get(a, j-k)*scaled_factor[k]; } gsl_vector_set(temp, j, y); } /* Copy result to a */ for(j=0; j<a->size; j++) { gsl_vector_set(a, j, gsl_vector_get(temp, j)); } } else { break; } } gsl_vector_free(temp); } /** * Function Convert_matrix_to_LSF * * Converts the LPC-coefficient matrix to Line Spectrum Frequencies (LSF) * * @param LSF pointer to the LSF matrix * @param a pointer to LPC-vector * @param index time index */ void Convert_matrix_to_LSF(gsl_matrix *LSF, gsl_vector *a, int index) { int i,n; /* Count the number of nonzero elements in "a" */ n = 0; for(i=0; i<a->size; i++) { if(gsl_vector_get(a, i) != 0) { n++; } } /* In case of only one non-zero element */ if(n == 1) { for(i=0; i<LSF->size2; i++) gsl_matrix_set(LSF, index, i, (i+1)*M_PI/(LSF->size2+1)); return; } gsl_vector *aa = gsl_vector_calloc(n+1); gsl_vector *flip_aa = gsl_vector_calloc(n+1); gsl_vector *p = gsl_vector_calloc(n+1); gsl_vector *q = gsl_vector_calloc(n+1); /* Construct vectors aa=[a 0] and flip_aa=[0 flip(a)] */ for(i=0; i<n; i++) { gsl_vector_set(aa, i, gsl_vector_get(a, i)); gsl_vector_set(flip_aa, flip_aa->size-1-i, gsl_vector_get(a, i)); } /* Construct vectors p and q */ for(i=0; i<n+1; i++) { gsl_vector_set(p, i, gsl_vector_get(aa, i) + gsl_vector_get(flip_aa, i)); gsl_vector_set(q, i, gsl_vector_get(aa, i) - gsl_vector_get(flip_aa, i)); } /* Remove trivial zeros */ if((n+1)%2 == 0) { double y; /* Deconvolve p with [1 1] */ y = 0; for(i=0; i<p->size; i++) { gsl_vector_set(p, i, gsl_vector_get(p, i)-y); y = gsl_vector_get(p, i); } gsl_vector_set(p, p->size-1, 0); /* Deconvolve q with [1 -1] */ y = 0; for(i=0; i<q->size; i++) { gsl_vector_set(q, i, gsl_vector_get(q, i)+y); y = gsl_vector_get(q, i); } gsl_vector_set(q, q->size-1, 0); } else { double y; /* Deconvolve q with [1 1] */ y = 0; for(i=0; i<q->size; i++) { gsl_vector_set(q, i, gsl_vector_get(q, i)-y); y = gsl_vector_get(q, i); } /* Deconvolve q with [1 -1] */ y = 0; for(i=0; i<q->size; i++) { gsl_vector_set(q, i, gsl_vector_get(q, i)+y); y = gsl_vector_get(q, i); } gsl_vector_set(q, q->size-1, 0); gsl_vector_set(q, q->size-2, 0); } /* Count the number of nonzero elements in "p" and "q" */ int n_p = 0; int n_q = 0; for(i=0; i<p->size; i++) { if(gsl_vector_get(p, i) != 0) n_p++; if(gsl_vector_get(q, i) != 0) n_q++; } /* Take the last half of "p" and "q" to vectors "TP" and "TQ" */ gsl_vector *TP = gsl_vector_alloc((n_p+1)/2); gsl_vector *TQ = gsl_vector_alloc((n_q+1)/2); for(i=0; i<TP->size; i++) { gsl_vector_set(TP, i, gsl_vector_get(p, i+(n_p-1)/2)); } for(i=0; i<TQ->size; i++) { gsl_vector_set(TQ, i, gsl_vector_get(q, i+(n_q-1)/2)); } /* Chebyshev transform */ Chebyshev(TP); Chebyshev(TQ); /* Initialize root arrays */ int nroots_TP = 2*(TP->size-1); int nroots_TQ = 2*(TQ->size-1); double TP_coeffs[TP->size]; double TQ_coeffs[TQ->size]; double TP_roots[nroots_TP]; double TQ_roots[nroots_TQ]; /* Copy coefficients to arrays */ for(i=0; i<TP->size; i++) { TP_coeffs[i] = gsl_vector_get(TP, i); } for(i=0; i<TQ->size; i++) { TQ_coeffs[i] = gsl_vector_get(TQ, i); } /* Solve roots */ gsl_poly_complex_workspace *w_TP = gsl_poly_complex_workspace_alloc(TP->size); gsl_poly_complex_workspace *w_TQ = gsl_poly_complex_workspace_alloc(TQ->size); gsl_poly_complex_solve(TP_coeffs, TP->size, w_TP, TP_roots); if(nroots_TQ > 0) { gsl_poly_complex_solve(TQ_coeffs, TQ->size, w_TQ, TQ_roots); } /* Convert to LSF and sort */ double sorted_LSF[(nroots_TP+nroots_TQ)/2]; for(i=0; i<nroots_TP; i=i+2) { sorted_LSF[i/2] = acos(TP_roots[i]/2); } for(i=0; i<nroots_TQ; i=i+2) { sorted_LSF[(i+nroots_TP)/2] = acos(TQ_roots[i]/2); } gsl_sort(sorted_LSF, 1, (nroots_TP+nroots_TQ)/2); /* Copy LSFs to vector LSF */ for(i=0; i<(nroots_TP+nroots_TQ)/2; i++) gsl_matrix_set(LSF, index, i, sorted_LSF[i]); /* Free memory */ gsl_poly_complex_workspace_free(w_TP); gsl_poly_complex_workspace_free(w_TQ); gsl_vector_free(aa); gsl_vector_free(flip_aa); gsl_vector_free(p); gsl_vector_free(q); gsl_vector_free(TP); gsl_vector_free(TQ); } /** * Function Convert_vector_to_LSF * * Convert LPC-coefficients to Line Spectrum Frequencies (LSF) * Maximum LPC-polynomial degree is 36! * * * @param a pointer to LPC-vector * @param LSF pointer to the LSF matrix * */ void Convert_vector_to_LSF(gsl_vector *a, gsl_vector *LSF) { int i,n; /* Count the number of nonzero elements in "a" */ n = 0; for(i=0; i<a->size; i++) { if(gsl_vector_get(a, i) != 0) { n++; } } /* In case of only one non-zero element */ if(n == 1) { for(i=0; i<LSF->size; i++) gsl_vector_set(LSF, i, (i+1)*M_PI/(LSF->size+1)); return; } gsl_vector *aa = gsl_vector_calloc(n+1); gsl_vector *flip_aa = gsl_vector_calloc(n+1); gsl_vector *p = gsl_vector_calloc(n+1); gsl_vector *q = gsl_vector_calloc(n+1); /* Construct vectors aa=[a 0] and flip_aa=[0 flip(a)] */ for(i=0; i<n; i++) { gsl_vector_set(aa, i, gsl_vector_get(a, i)); gsl_vector_set(flip_aa, flip_aa->size-1-i, gsl_vector_get(a, i)); } /* Construct vectors p and q */ for(i=0; i<n+1; i++) { gsl_vector_set(p, i, gsl_vector_get(aa, i) + gsl_vector_get(flip_aa, i)); gsl_vector_set(q, i, gsl_vector_get(aa, i) - gsl_vector_get(flip_aa, i)); } /* Remove trivial zeros */ if((n+1)%2 == 0) { double y; /* Deconvolve p with [1 1] */ y = 0; for(i=0; i<p->size; i++) { gsl_vector_set(p, i, gsl_vector_get(p, i)-y); y = gsl_vector_get(p, i); } gsl_vector_set(p, p->size-1, 0); /* Deconvolve q with [1 -1] */ y = 0; for(i=0; i<q->size; i++) { gsl_vector_set(q, i, gsl_vector_get(q, i)+y); y = gsl_vector_get(q, i); } gsl_vector_set(q, q->size-1, 0); } else { double y; /* Deconvolve q with [1 1] */ y = 0; for(i=0; i<q->size; i++) { gsl_vector_set(q, i, gsl_vector_get(q, i)-y); y = gsl_vector_get(q, i); } /* Deconvolve q with [1 -1] */ y = 0; for(i=0; i<q->size; i++) { gsl_vector_set(q, i, gsl_vector_get(q, i)+y); y = gsl_vector_get(q, i); } gsl_vector_set(q, q->size-1, 0); gsl_vector_set(q, q->size-2, 0); } /* Count the number of nonzero elements in "p" and "q" */ int n_p = 0; int n_q = 0; for(i=0; i<p->size; i++) { if(gsl_vector_get(p, i) != 0) n_p++; if(gsl_vector_get(q, i) != 0) n_q++; } /* Take the last half of "p" and "q" to vectors "TP" and "TQ" */ gsl_vector *TP = gsl_vector_alloc((n_p+1)/2); gsl_vector *TQ = gsl_vector_alloc((n_q+1)/2); for(i=0; i<TP->size; i++) { gsl_vector_set(TP, i, gsl_vector_get(p, i+(n_p-1)/2)); } for(i=0; i<TQ->size; i++) { gsl_vector_set(TQ, i, gsl_vector_get(q, i+(n_q-1)/2)); } /* Chebyshev transform */ Chebyshev(TP); Chebyshev(TQ); /* Initialize root arrays */ int nroots_TP = 2*(TP->size-1); int nroots_TQ = 2*(TQ->size-1); double TP_coeffs[TP->size]; double TQ_coeffs[TQ->size]; double TP_roots[nroots_TP]; double TQ_roots[nroots_TQ]; /* Copy coefficients to arrays */ for(i=0; i<TP->size; i++) { TP_coeffs[i] = gsl_vector_get(TP, i); } for(i=0; i<TQ->size; i++) { TQ_coeffs[i] = gsl_vector_get(TQ, i); } /* Solve roots */ gsl_poly_complex_workspace *w_TP = gsl_poly_complex_workspace_alloc(TP->size); gsl_poly_complex_workspace *w_TQ = gsl_poly_complex_workspace_alloc(TQ->size); gsl_poly_complex_solve(TP_coeffs, TP->size, w_TP, TP_roots); gsl_poly_complex_solve(TQ_coeffs, TQ->size, w_TQ, TQ_roots); /* Convert to LSF and sort */ double sorted_LSF[(nroots_TP+nroots_TQ)/2]; for(i=0; i<nroots_TP; i=i+2) { sorted_LSF[i/2] = acos(TP_roots[i]/2); } for(i=0; i<nroots_TQ; i=i+2) { sorted_LSF[(i+nroots_TP)/2] = acos(TQ_roots[i]/2); } gsl_sort(sorted_LSF, 1, (nroots_TP+nroots_TQ)/2); /* Copy LSFs to vector LSF */ for(i=0; i<(nroots_TP+nroots_TQ)/2; i++) gsl_vector_set(LSF, i, sorted_LSF[i]); /* Free memory */ gsl_poly_complex_workspace_free(w_TP); gsl_poly_complex_workspace_free(w_TQ); gsl_vector_free(aa); gsl_vector_free(flip_aa); gsl_vector_free(p); gsl_vector_free(q); gsl_vector_free(TP); gsl_vector_free(TQ); } /** * Function Chebyshev * * Chebyshev transformation * * @param T pointer to polynomial coefficients (result will be computed in-place) * */ void Chebyshev(gsl_vector *T) { int i,j,s; gsl_matrix *C; gsl_vector *cheb = gsl_vector_alloc(T->size); gsl_matrix *inv_C = gsl_matrix_alloc(T->size, T->size); gsl_permutation *perm = gsl_permutation_alloc(T->size); /* Create C, matrix inversion through LU-decomposition */ C = Construct_C(T->size); gsl_linalg_LU_decomp(C, perm, &s); gsl_linalg_LU_invert(C, perm, inv_C); /* Evaluate r = inv(C)'*T */ double sum; for(i=0; i<T->size; i++) { sum = 0; for(j=0; j<T->size; j++) sum += gsl_matrix_get(inv_C, j, i)*gsl_vector_get(T, j); gsl_vector_set(cheb, i, sum); } /* Copy coefficients to T */ for(i=0; i<T->size; i++) { gsl_vector_set(T, i, gsl_vector_get(cheb, i)); } /* Free memory */ gsl_vector_free(cheb); gsl_matrix_free(C); gsl_matrix_free(inv_C); gsl_permutation_free(perm); } /** * Function Construct_C * * Construct data matrix C for Chebyshev transform * * @param size * @return C matrix * */ gsl_matrix *Construct_C(int size) { int i,j; gsl_matrix *C = gsl_matrix_calloc(size,size); gsl_vector *tmp = gsl_vector_alloc(3); gsl_vector *f = gsl_vector_alloc(3); /* Set tmp and f */ gsl_vector_set(tmp,0,1); gsl_vector_set(tmp,1,0); gsl_vector_set(tmp,2,1); gsl_vector_memcpy(f,tmp); /* Set diagonal to 1 */ for(i=0;i<size;i++) gsl_matrix_set(C,i,i,1); /* Construct C */ for(i=2;i<size;i++) { f = Conv(f,tmp); for(j=0;j<i;j++) gsl_matrix_set(C,i,j,gsl_vector_get(f,(f->size-1)/2+j)); } /* Free memory */ gsl_vector_free(tmp); gsl_vector_free(f); return C; } /** * Function MedFilt3 * * 3-point median filtering * * @param frame pointer to vector to be filtered * */ void MedFilt3(gsl_vector *frame) { int i,j,n; double temp1 = 0; double temp2 = gsl_vector_get(frame, 0); n = 3; gsl_vector *samples = gsl_vector_alloc(n); for(i=0; i<frame->size-2; i++) { for(j=0; j<n; j++) { gsl_vector_set(samples, j, gsl_vector_get(frame, i+j)); } gsl_sort_vector(samples); temp1 = gsl_vector_get(samples, 1); gsl_vector_set(frame, i, temp2); temp2 = temp1; } gsl_vector_free(samples); } /** * Function MedFilt3_matrix * * 3-point median filtering for matrices. * Filter along the first dimension. * * @param frame pointer to matrix to be filtered * */ void MedFilt3_matrix(gsl_matrix *matrix) { int i,j; gsl_vector *temp = gsl_vector_alloc(matrix->size1); for(i=0;i<matrix->size2;i++) { for(j=0;j<matrix->size1;j++) { gsl_vector_set(temp,j,gsl_matrix_get(matrix,j,i)); } MedFilt3(temp); for(j=0;j<matrix->size1;j++) { gsl_matrix_set(matrix,j,i,gsl_vector_get(temp,j)); } } gsl_vector_free(temp); } /** * Function MedFilt5_matrix * * 5-point median filtering for matrices. * Filter along the first dimension. * * @param frame pointer to matrix to be filtered * */ void MedFilt5_matrix(gsl_matrix *matrix) { int i,j; gsl_vector *temp = gsl_vector_alloc(matrix->size1); for(i=0;i<matrix->size2;i++) { for(j=0;j<matrix->size1;j++) { gsl_vector_set(temp,j,gsl_matrix_get(matrix,j,i)); } MedFilt5(temp); for(j=0;j<matrix->size1;j++) { gsl_matrix_set(matrix,j,i,gsl_vector_get(temp,j)); } } gsl_vector_free(temp); } /** * Function MedFilt5 * * 5-point median filtering * * @param frame pointer to vector to be filtered * */ void MedFilt5(gsl_vector *frame) { int i,j,n = 5; double temp1 = gsl_vector_get(frame, 0); double temp2 = gsl_vector_get(frame,1); double temp3; gsl_vector *samples = gsl_vector_alloc(n); for(i=0; i<frame->size-(n-1); i++) { for(j=0; j<n; j++) { gsl_vector_set(samples, j, gsl_vector_get(frame, i+j)); } gsl_sort_vector(samples); temp3 = gsl_vector_get(samples, 2); gsl_vector_set(frame, i, temp1); temp1 = temp2; temp2 = temp3; } gsl_vector_free(samples); } /** * Function Remove_mean * * Remove mean of given vector * * @param frame pointer to samples * */ void Remove_mean(gsl_vector *frame) { int i; double mean = 0; for(i=0; i<frame->size; i++) { mean += gsl_vector_get(frame, i); } mean = mean/(double)frame->size; for(i=0; i<frame->size; i++) { gsl_vector_set(frame, i, gsl_vector_get(frame, i)-mean); } } /** * Function Interpolate * * Interpolates given vector to new vector of given length * * @param vector original vector * @param i_vector interpolated vector */ void Interpolate(gsl_vector *vector, gsl_vector *i_vector) { int i,len = vector->size,length = i_vector->size; /* Read values to array */ double x[len]; double y[len]; for(i=0; i<len; i++) { x[i] = i; y[i] = gsl_vector_get(vector,i); } gsl_interp_accel *acc = gsl_interp_accel_alloc(); gsl_spline *spline = gsl_spline_alloc(gsl_interp_cspline,len); gsl_spline_init(spline, x, y, len); double xi; i = 0; /* New implementation (27.3.2009, bug fix 8.2.2010) */ /* Bug fix to GSL v.1.15, 26.1.2012 */ xi = x[0]; while(i<length) { gsl_vector_set(i_vector,i,gsl_spline_eval(spline, xi, acc)); xi += (len-1)/(double)(length-1); if(xi > len-1) xi = len-1; i++; } /* Free memory */ gsl_spline_free(spline); gsl_interp_accel_free(acc); } /** * Function lsf2poly * * Convert LSF to polynomial * * @param lsf_matrix * @param poly * @param index */ void lsf2poly(gsl_matrix *lsf_matrix, gsl_vector *poly, int index, int HMM) { int i,l = lsf_matrix->size2; gsl_vector *lsf_vector = gsl_vector_calloc(l); gsl_vector *fi_p = NULL, *fi_q = NULL; /* Get values to vector */ for(i=0;i<l;i++) gsl_vector_set(lsf_vector,i,gsl_matrix_get(lsf_matrix,index,i)); /* Create fi_p and fi_q */ if(l%2 == 0) { fi_p = gsl_vector_alloc(l/2); fi_q = gsl_vector_alloc(l/2); for(i=0;i<l;i=i+2) { gsl_vector_set(fi_p,i/2,gsl_vector_get(lsf_vector,i)); } for(i=1;i<l;i=i+2) { gsl_vector_set(fi_q,(i-1)/2,gsl_vector_get(lsf_vector,i)); } } else { fi_p = gsl_vector_alloc((l+1)/2); for(i=0;i<l;i=i+2) { gsl_vector_set(fi_p,i/2,gsl_vector_get(lsf_vector,i)); } if((l-1)/2 > 0) { fi_q = gsl_vector_alloc((l-1)/2); for(i=1;i<l-1;i=i+2) { gsl_vector_set(fi_q,(i-1)/2,gsl_vector_get(lsf_vector,i)); } } } /* Construct vectors P and Q */ gsl_vector *cp = gsl_vector_calloc(3); gsl_vector *cq = gsl_vector_calloc(3); gsl_vector_add_constant(cp,1); gsl_vector_add_constant(cq,1); gsl_vector *P = gsl_vector_alloc(1); gsl_vector *Q = gsl_vector_alloc(1); gsl_vector_set(P,0,1); gsl_vector_set(Q,0,1); for(i=0;i<fi_p->size;i++) { gsl_vector_set(cp,1,-2*cos(gsl_vector_get(fi_p,i))); P = Conv(P,cp); } if((l-1)/2 > 0) { for(i=0;i<fi_q->size;i++) { gsl_vector_set(cq,1,-2*cos(gsl_vector_get(fi_q,i))); Q = Conv(Q,cq); } } /* Add trivial zeros */ if(l%2 == 0) { gsl_vector *conv = gsl_vector_calloc(2); gsl_vector_add_constant(conv,1); P = Conv(P,conv); gsl_vector_set(conv,0,-1); Q = Conv(Q,conv); gsl_vector_free(conv); } else { gsl_vector *conv = gsl_vector_calloc(3); gsl_vector_set(conv,0,-1); gsl_vector_set(conv,2,1); Q = Conv(Q,conv); gsl_vector_free(conv); } /* Construct polynomial */ for(i=1;i<P->size;i++) { gsl_vector_set(poly,P->size-i-1,0.5*(gsl_vector_get(P,i)+gsl_vector_get(Q,i))); } /* Free memory */ gsl_vector_free(lsf_vector); gsl_vector_free(fi_p); if((l-1)/2 > 0) { gsl_vector_free(fi_q); } gsl_vector_free(cp); gsl_vector_free(cq); gsl_vector_free(P); gsl_vector_free(Q); } /** * Function Conv * * Convolve two vectors * * @param conv1 * @param conv2 */ gsl_vector *Conv(gsl_vector *conv1, gsl_vector *conv2) { int i,j,n = conv2->size; double sum; gsl_vector *result = gsl_vector_alloc(conv1->size+conv2->size-1); gsl_vector *temp = gsl_vector_calloc(conv1->size+conv2->size-1); /* Set coefficients to temp */ for(i=0;i<conv1->size;i++) { gsl_vector_set(temp,i,gsl_vector_get(conv1,i)); } /* FIR-filter (Convolution) */ for(i=0;i<temp->size;i++) { sum = 0; for(j=0; j<=GSL_MIN(i, n-1); j++) { sum += gsl_vector_get(temp, i-j)*gsl_vector_get(conv2,j); } gsl_vector_set(result, i, sum); } /* Free memory */ gsl_vector_free(temp); gsl_vector_free(conv1); return result; } /** * Function Convert_Hz2ERB * * Convert vector scale from Hz to ERB * * @param vector pointer to original HNR vector * @param vector_erb pointer to vector of ERB-scale HNR values * */ void Convert_Hz2ERB(gsl_vector *vector, gsl_vector *vector_erb, int FS) { int i,j,hnr_channels = vector_erb->size; gsl_vector *erb = gsl_vector_alloc(vector->size); gsl_vector *erb_sum = gsl_vector_calloc(hnr_channels); /* Evaluate ERB scale indices for vector */ for(i=0;i<vector->size;i++) gsl_vector_set(erb,i,log10(0.00437*(i/(vector->size-1.0)*(FS/2.0))+1.0)/log10(0.00437*(FS/2.0)+1.0)*(hnr_channels-SMALL_NUMBER)); /* Evaluate values according to ERB rate */ for(i=0;i<vector->size;i++) { j = floor(gsl_vector_get(erb,i)); gsl_vector_set(vector_erb,j,gsl_vector_get(vector_erb,j)+gsl_vector_get(vector,i)); gsl_vector_set(erb_sum,j,gsl_vector_get(erb_sum,j)+1); } /* Average values */ for(i=0;i<hnr_channels;i++) gsl_vector_set(vector_erb,i,gsl_vector_get(vector_erb,i)/gsl_vector_get(erb_sum,i)); /* Prevent NaN-values (due to division by zero) */ for(i=0;i<hnr_channels;i++) { if(gsl_vector_get(erb_sum,i) == 0) { j = 1; while(gsl_vector_get(erb_sum,i+j) == 0) j++; gsl_vector_set(vector_erb,i,0.5*gsl_vector_get(vector_erb,i-1)+0.5*gsl_vector_get(vector_erb,i+j)); } } /* Free memory */ gsl_vector_free(erb); gsl_vector_free(erb_sum); } /** * Function Harmonic_analysis * * Extract the magnitudes of N harmonics. * Extract the amount of aperiodicity according to smoothed upper and lower spectral envelopes. * Extract H1-H2 * * @param frame pointer to voice source frame * @param harmonics pointer to harmonic matrix * @param hnr pointer to hnr matrix * @param h1h2 pointer to h1h2 vector * @param f0 fundamental frequency * @param FS sampling frequency * @param index time index * */ void Harmonic_analysis(gsl_vector *frame, gsl_matrix *harmonics, gsl_matrix *hnr, gsl_vector *h1h2, double f0, int FS, int index) { /* Variables */ int i,j,guess_index = 0,h_values_size,harmonic_search_range; int hnr_channels = hnr->size2; double ind[MAX_HARMONICS] = {0}; double guess_index_double = 0; double data[FFT_LENGTH_LONG] = {0}; double h_values[MAX_HARMONICS] = {0}; double n_values[MAX_HARMONICS] = {0}; gsl_vector *fft = gsl_vector_calloc(FFT_LENGTH_LONG/2); gsl_vector *find; /* FFT (with windowing) */ for (i=0; i<frame->size; i++) data[i] = gsl_vector_get(frame, i)*HANN(i,frame->size); gsl_fft_real_radix2_transform(data, 1, FFT_LENGTH_LONG); for(i=1; i<FFT_LENGTH_LONG/2; i++) { gsl_vector_set(fft, i, 20*log10(sqrt(pow(data[i], 2) + pow(data[FFT_LENGTH_LONG-i], 2)))); } gsl_vector_set(fft, 0, 20*log10(fabs(data[0]))); /* Set (possible) infinity values to zero */ for(i=0;i<fft->size;i++) { if(!gsl_finite(gsl_vector_get(fft,i))) gsl_vector_set(fft,i,MIN_LOG_POWER); } /* Find the indices and magnitudes of the harmonic peaks */ i = 0; while(1) { /* Define harmonics search range, decreasing to the higher frequencies */ harmonic_search_range = GSL_MAX(HARMONIC_SEARCH_COEFF*f0/(FS/(double)FFT_LENGTH_LONG)*((fft->size-1-guess_index)/(double)(fft->size-1)),1.0); find = gsl_vector_alloc(harmonic_search_range); /* Estimate the index of the i_th harmonic * Use an iterative estimation based on earlier values */ if(i > 0) { guess_index_double = 0; for(j=0;j<i;j++) guess_index_double += ind[j]/(j+1.0)*(i+1.0); guess_index = (int)GSL_MAX(guess_index_double/j - (harmonic_search_range-1)/2.0,0); } else guess_index = (int)GSL_MAX(f0/(FS/(double)FFT_LENGTH_LONG) - (harmonic_search_range-1)/2.0,0); /* Stop search if the end (minus safe limit) of the fft vector or the maximum number of harmonics is reached */ if(guess_index + rint(HNR_UNCERTAINTY_COEFF*FFT_LENGTH_LONG) > fft->size-1 || i > MAX_HARMONICS-1) { gsl_vector_free(find); break; } /* Find the maximum of the i_th harmonic */ for(j=0; j<harmonic_search_range; j++) { if(guess_index+j < fft->size) gsl_vector_set(find, j, gsl_vector_get(fft, guess_index+j)); else gsl_vector_set(find, j, BIG_NEG_NUMBER); } ind[i] = guess_index + gsl_vector_max_index(find); h_values[i] = gsl_vector_get(fft, ind[i]); gsl_vector_free(find); i++; } h_values_size = i; /* Estimate the level of interharmonic noise */ double ind_n[MAX_HARMONICS] = {0}; for(i=0;i<h_values_size-1;i++) { /* Evaluate value exactly between the harmonics */ ind_n[i] = rint((ind[i]+ind[i+1])/2.0); n_values[i] = gsl_vector_get(fft,ind_n[i]); } //if(index == 147) { // printf("%lf\n",f0); // VPrint1(fft); // APrint1(h_values,h_values_size); // APrint3(ind,h_values_size); // APrint2(n_values,i); // APrint4(ind_n,i); // pause(1); //} /* Postfilter HNR and iterpolate vectors */ gsl_vector *hnr_est = gsl_vector_alloc(h_values_size-1); gsl_vector *hnr_est_erb = gsl_vector_calloc(hnr_channels); for(i=0;i<hnr_est->size;i++) gsl_vector_set(hnr_est,i,n_values[i]-h_values[i]); MedFilt3(hnr_est); Convert_Hz2ERB(hnr_est, hnr_est_erb, FS); /* Set values to hnr matrix */ for(i=0;i<hnr_channels;i++) gsl_matrix_set(hnr,index,i,gsl_vector_get(hnr_est_erb,i)); /* Extract harmonics values, or actually their differences. First value is H1-H2. */ double mag0 = gsl_vector_get(fft,ind[0]); for(i=0;i<harmonics->size2;i++) gsl_matrix_set(harmonics,index,i,mag0 - gsl_vector_get(fft,ind[i+1])); /* Set H1-H2 */ gsl_vector_set(h1h2,index,gsl_matrix_get(harmonics,index,0)); /* Free memory */ gsl_vector_free(fft); gsl_vector_free(hnr_est); gsl_vector_free(hnr_est_erb); } /** * Function LSF_Postfilter * * Apply formant enhancement to LSFs * * @param lsf LSF-matrix * @param alpha postfilter coefficient alpha */ void LSF_Postfilter(gsl_matrix *lsf, PARAM *params) { if(params->formant_enh_coeff > 0) { int i,j; double d[lsf->size2-1]; for(i=0;i<lsf->size1;i++) { for(j=0;j<lsf->size2-1;j++) { d[j] = params->formant_enh_coeff*(gsl_matrix_get(lsf,i,j+1) - gsl_matrix_get(lsf,i,j)); if(j>0) { gsl_matrix_set(lsf,i,j, gsl_matrix_get(lsf,i,j-1) + d[j-1] + (pow(d[j-1],2)/(pow(d[j-1],2) + pow(d[j],2))) * ( gsl_matrix_get(lsf,i,j+1) - gsl_matrix_get(lsf,i,j-1) - d[j] - d[j-1] ) ); } } } } } /** * Function Select_new_refined_values * * Select new parameter values for pulses according to smoothed and refined parameters. * * @param ... */ void Select_new_refined_values(gsl_vector *fundf, gsl_vector *gain, gsl_matrix *LSF, gsl_matrix *spectral_tilt, gsl_matrix *hnr_i, gsl_matrix *harmonics, gsl_vector *pgain, gsl_matrix *plsf, gsl_matrix *ptilt, gsl_matrix *phnr, gsl_matrix *pharm, gsl_vector *pulse_pos, gsl_vector *pulse_lengths, gsl_matrix *waveform, gsl_vector *h1h2, gsl_vector *ph1h2, gsl_vector *naq, gsl_vector *pnaq, PARAM *params) { /* Do not perform if parameters are not extracted */ if(params->extract_pulselib_params == 0) return; /* Check that the number of pulses is not more than the maximum number of pulses */ if(params->number_of_pulses > params->maxnumberofpulses) params->number_of_pulses = params->maxnumberofpulses; /* Select new parameter values for pulses according to smoothed and refined parameters * Remeber to take into account that original parameter vectors are added with a few frames * in the beginning and in the end (value empty_frames) */ int i,j,empty_frames = rint((params->frame_length/(double)params->shift - 1)/2); for(i=0;i<params->number_of_pulses;i++) { gsl_vector_set(pgain,i,gsl_vector_get(gain,gsl_vector_get(pulse_pos,i)+empty_frames)); gsl_vector_set(ph1h2,i,gsl_vector_get(h1h2,gsl_vector_get(pulse_pos,i)+empty_frames)); gsl_vector_set(pnaq,i,gsl_vector_get(naq,gsl_vector_get(pulse_pos,i)+empty_frames)); for(j=0;j<hnr_i->size2;j++) gsl_matrix_set(phnr,i,j,gsl_matrix_get(hnr_i,gsl_vector_get(pulse_pos,i)+empty_frames,j)); for(j=0;j<harmonics->size2;j++) gsl_matrix_set(pharm,i,j,gsl_matrix_get(harmonics,gsl_vector_get(pulse_pos,i)+empty_frames,j)); } } /** * Function Noise_reduction * * Reduce noise by reducing the gain of low level parts of the signal * * @param gain vector * @param params */ void Noise_reduction(gsl_vector *gain, PARAM *params) { /* Apply noise reduction */ if(params->noise_reduction_analysis == 1) { int i; for(i=0;i<gain->size;i++) if(gsl_vector_get(gain,i) < params->noise_reduction_limit_db) gsl_vector_set(gain,i,gsl_vector_get(gain,i)-params->noise_reduction_db); } } /** * Function Fill_waveform_gaps * * Fill possible gaps in parameter waveform due to f0 postprocessing/in case waveform could not be analysed * * @param ... */ void Fill_waveform_gaps(gsl_vector *fundf, gsl_matrix *waveform) { int i,j,k,k1,k2; double sum; /* Copy original waveform */ gsl_matrix *waveform_new = gsl_matrix_alloc(waveform->size1,waveform->size2); gsl_matrix_memcpy(waveform_new,waveform); /* Fix gaps in waveform */ for(i=0;i<fundf->size;i++) { if(gsl_vector_get(fundf,i) > 0) { sum = 0; for(j=0;j<waveform->size2;j++) sum += fabs(gsl_matrix_get(waveform,i,j)); if(sum == 0) { /* Gap found, find the next non-zero waveform */ k1 = i+1; while(sum == 0) { if(k1 > waveform->size1-1) break; for(j=0;j<waveform->size2;j++) sum += fabs(gsl_matrix_get(waveform,k1,j)); k1++; } sum = 0; k2 = i-1; while(sum == 0) { if(k2 < 0) break; for(j=0;j<waveform->size2;j++) sum += fabs(gsl_matrix_get(waveform,k2,j)); k2--; } if(fabs(k1-i) < fabs(k2-i)) k = k1-1; else k = k2+1; /* Fill the gap with the nearest found non-zero waveform */ for(j=0;j<waveform->size2;j++) gsl_matrix_set(waveform_new,i,j,gsl_matrix_get(waveform,k,j)); } } else { /* If f0 == 0, set zero */ for(j=0;j<waveform->size2;j++) gsl_matrix_set(waveform,i,j,0); } } /* Copy fixed waveform matrix to the original one and free memory */ gsl_matrix_memcpy(waveform,waveform_new); gsl_matrix_free(waveform_new); } /** * Function Fill_naq_gaps * * Fill possible gaps in parameter NAQ due to f0 postprocessing/in case waveform could not be analysed * * @param ... */ void Fill_naq_gaps(gsl_vector *fundf, gsl_vector *naq) { int i,k,k1,k2; /* Copy original vector */ gsl_vector *naq_new = gsl_vector_alloc(naq->size); gsl_vector_memcpy(naq_new,naq); /* Fix gaps in naq */ for(i=0;i<fundf->size;i++) { if(gsl_vector_get(fundf,i) > 0) { /* If gap is found, find the nearest non-zero value */ if(gsl_vector_get(naq,i) == 0) { k1 = i+1; while(k1 < naq->size-1 && gsl_vector_get(naq,k1) == 0) k1++; k2 = i-1; while(k2 > 0 && gsl_vector_get(naq,k2) == 0) k2--; if(fabs(k1-i) < fabs(k2-i)) { if(k1 < naq->size-1) k = k1; else k = k2; } else { if(k2 > 0) k = k2; else k = k1; } /* Sanity check */ if(k < 0 || k > naq->size-1) break; /* Fill the gap with the nearest found non-zero value */ gsl_vector_set(naq_new,i,gsl_vector_get(naq,k)); } } else { /* If f0 == 0, set zero */ gsl_vector_set(naq,i,0); } } /* Copy fixed vector to the original one and free memory */ gsl_vector_memcpy(naq,naq_new); gsl_vector_free(naq_new); } /** * Function Construct_source * * Construct continuous source signal from the glottal inverse filtered signal * * @param ... */ void Construct_source(gsl_vector *source_signal, gsl_vector *glottal, gsl_vector *glottal_f0, int index, PARAM *params) { if(params->extract_source != 1) return; int i; int N = glottal->size; /* Get glottal samples to source signal */ if(index == 0) { for(i=0; i<N/2; i++) gsl_vector_set(source_signal, i, gsl_vector_get(glottal,i)); for(i=0; i<params->shift; i++) gsl_vector_set(source_signal, N/2+i, gsl_vector_get(glottal,N/2+i)*HANN(params->shift+i,2*params->shift)); } else { for(i=0; i<2*params->shift; i++) gsl_vector_set(source_signal, (index-1)*params->shift+ceil(N/2)+i, gsl_vector_get(source_signal,(index-1)*params->shift+ceil(N/2)+i) + gsl_vector_get(glottal, ceil(N/2)-params->shift+i)*HANN(i,2*params->shift)); } /* Get glottal samples to source signal from the longer frame (FO) */ /* int Ng = glottal_f0->size; if(index == 0) { for(i=0; i<N/2; i++) gsl_vector_set(source_signal, i, gsl_vector_get(glottal_f0,i)); for(i=0; i<shift; i++) gsl_vector_set(source_signal, N/2+i, gsl_vector_get(glottal_f0,N/2+i)*HANN(shift+i,2*shift)); } else { for(i=0; i<2*shift; i++) gsl_vector_set(source_signal, (index-1)*shift+ceil(N/2)+i, gsl_vector_get(source_signal,(index-1)*shift+ceil(N/2)+i) + gsl_vector_get(glottal_f0, ceil(Ng/2)-shift+i)*HANN(i,2*shift)); } */ } /** * Function Write_parameters_to_file * * Write speech parameters to file * * @param ... */ void Write_parameters_to_file(char *filename, gsl_matrix *LSF, gsl_matrix *LSF2, gsl_matrix *spectral_tilt, gsl_matrix *HNR, gsl_matrix* harmonics, gsl_matrix *waveform,gsl_vector *fundf, gsl_vector *gain, gsl_vector *h1h2, gsl_vector *naq, gsl_vector *source_signal, gsl_matrix *fftmatrix_vt, gsl_matrix *fftmatrix_src, PARAM *params) { /* Initialize */ FILE *LSF_file = NULL, *LSF2_file = NULL, *gain_file = NULL, *fundf_file = NULL, *spectral_tilt_file = NULL, *params_file = NULL; FILE *HNR_file = NULL, *source_file = NULL, *harmonics_file = NULL, *waveform_file = NULL, *h1h2_file = NULL, *naq_file = NULL; FILE *FFTvt_file = NULL, *FFTsrc_file = NULL; int slen = strlen(filename)-4; // Remove ending ".wav" char orig[slen+1]; char tmp[DEF_STRING_LEN]; strncpy(orig, filename, slen); orig[slen] = '\0'; /* Open files */ if(params->extract_lsf == 1) {strcpy(tmp, orig);LSF_file = fopen(strcat(tmp, FILENAME_ENDING_LSF), "w"); if(LSF_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);}} if(params->extract_gain == 1) {strcpy(tmp, orig);gain_file = fopen(strcat(tmp, FILENAME_ENDING_GAIN), "w"); if(gain_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);}} if(params->extract_h1h2 == 1) {strcpy(tmp, orig);h1h2_file = fopen(strcat(tmp, FILENAME_ENDING_H1H2), "w"); if(h1h2_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);}} if(params->extract_naq == 1) {strcpy(tmp, orig);naq_file = fopen(strcat(tmp, FILENAME_ENDING_NAQ), "w"); if(naq_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);}} if(params->extract_f0 == 1) {strcpy(tmp, orig);fundf_file = fopen(strcat(tmp, FILENAME_ENDING_F0), "w"); if(fundf_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);}} if(params->extract_tilt == 1) {strcpy(tmp, orig);spectral_tilt_file = fopen(strcat(tmp, FILENAME_ENDING_LSFSOURCE), "w"); if(spectral_tilt_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);}} if(params->extract_info == 1) {strcpy(tmp, orig);params_file = fopen(strcat(tmp, FILE_ENDING_INFO), "w"); if(params_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);}} if(params->extract_hnr == 1) {strcpy(tmp, orig);HNR_file = fopen(strcat(tmp, FILENAME_ENDING_HNR), "w"); if(HNR_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);}} if(params->extract_harmonics == 1) {strcpy(tmp, orig);harmonics_file = fopen(strcat(tmp, FILENAME_ENDING_HARMONICS), "w");if(harmonics_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);}} if(params->extract_waveform == 1) {strcpy(tmp, orig);waveform_file = fopen(strcat(tmp, FILENAME_ENDING_WAVEFORM), "w");if(waveform_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);}} if(params->extract_source == 1) {strcpy(tmp, orig);source_file = fopen(strcat(tmp, FILENAME_ENDING_SOURCESIGNAL), "w"); if(source_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);}} if(params->sep_vuv_spectrum == 1) {strcpy(tmp, orig);LSF2_file = fopen(strcat(tmp, FILENAME_ENDING_LSF2), "w"); if(LSF2_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);}} if(params->write_fftspectra_to_file == 1) {strcpy(tmp, orig);FFTvt_file = fopen(strcat(tmp, FILENAME_ENDING_FFT_VT), "w"); if(FFTvt_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);}} if(params->write_fftspectra_to_file == 1) {strcpy(tmp, orig);FFTsrc_file = fopen(strcat(tmp, FILENAME_ENDING_FFT_SRC), "w"); if(FFTsrc_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);}} /* Write analysis parameters to file */ if(params->extract_info == 1) { gsl_vector *parameters = gsl_vector_alloc(NPARAMS); gsl_vector_set(parameters, 0, params->frame_length_ms); gsl_vector_set(parameters, 1, params->shift_ms); gsl_vector_set(parameters, 2, (int)fundf->size); // This is inequal (but correct) to n_frames due to the "add_missing_frames" procedure! gsl_vector_set(parameters, 3, params->lpc_order_vt); gsl_vector_set(parameters, 4, params->lpc_order_gl); gsl_vector_set(parameters, 5, params->lambda_vt); gsl_vector_set(parameters, 6, params->lambda_gl); gsl_vector_set(parameters, 7, HNR->size2); gsl_vector_set(parameters, 8, harmonics->size2); gsl_vector_set(parameters, 9, params->number_of_pulses); gsl_vector_set(parameters, 10, params->pulsemaxlen_ms); gsl_vector_set(parameters, 11, params->rspulsemaxlen_ms); gsl_vector_set(parameters, 12, waveform->size2); gsl_vector_set(parameters, 13, params->FS); gsl_vector_set(parameters, 14, params->data_format); gsl_vector_fprintf(params_file, parameters, "%f"); gsl_vector_free(parameters); } /* Write parameters to file */ if(params->data_format == DATA_FORMAT_ID_ASCII) { if(params->extract_hnr == 1) gsl_matrix_fprintf(HNR_file, HNR, "%.5f"); if(params->extract_lsf == 1) gsl_matrix_fprintf(LSF_file, LSF, "%.7f"); if(params->extract_tilt == 1) gsl_matrix_fprintf(spectral_tilt_file, spectral_tilt, "%.7f"); if(params->extract_gain == 1) gsl_vector_fprintf(gain_file, gain, "%.7f"); if(params->extract_h1h2 == 1) gsl_vector_fprintf(h1h2_file, h1h2, "%.7f"); if(params->extract_naq == 1) gsl_vector_fprintf(naq_file, naq, "%.7f"); if(params->extract_f0 == 1) gsl_vector_fprintf(fundf_file, fundf, "%.7f"); if(params->extract_harmonics == 1) gsl_matrix_fprintf(harmonics_file, harmonics, "%.7f"); if(params->extract_waveform == 1) gsl_matrix_fprintf(waveform_file, waveform, "%.7f"); if(params->extract_source == 1) gsl_vector_fprintf(source_file, source_signal, "%.7f"); if(params->sep_vuv_spectrum == 1) gsl_matrix_fprintf(LSF2_file, LSF2, "%.7f"); if(params->write_fftspectra_to_file == 1) gsl_matrix_fprintf(FFTvt_file, fftmatrix_vt, "%.7f"); if(params->write_fftspectra_to_file == 1) gsl_matrix_fprintf(FFTsrc_file, fftmatrix_src, "%.7f"); } else if(params->data_format == DATA_FORMAT_ID_BINARY) { if(params->extract_hnr == 1) gsl_matrix_fwrite(HNR_file, HNR); if(params->extract_lsf == 1) gsl_matrix_fwrite(LSF_file, LSF); if(params->extract_tilt == 1) gsl_matrix_fwrite(spectral_tilt_file, spectral_tilt); if(params->extract_gain == 1) gsl_vector_fwrite(gain_file, gain); if(params->extract_h1h2 == 1) gsl_vector_fwrite(h1h2_file, h1h2); if(params->extract_naq == 1) gsl_vector_fwrite(naq_file, naq); if(params->extract_f0 == 1) gsl_vector_fwrite(fundf_file, fundf); if(params->extract_harmonics == 1) gsl_matrix_fwrite(harmonics_file, harmonics); if(params->extract_waveform == 1) gsl_matrix_fwrite(waveform_file, waveform); if(params->extract_source == 1) gsl_vector_fwrite(source_file, source_signal); if(params->sep_vuv_spectrum == 1) gsl_matrix_fwrite(LSF2_file, LSF2); if(params->write_fftspectra_to_file == 1) gsl_matrix_fwrite(FFTvt_file, fftmatrix_vt); if(params->write_fftspectra_to_file == 1) gsl_matrix_fwrite(FFTsrc_file, fftmatrix_src); } /* Close files */ if(params->extract_lsf == 1) fclose(LSF_file); if(params->extract_gain == 1) fclose(gain_file); if(params->extract_h1h2 == 1) fclose(h1h2_file); if(params->extract_naq == 1) fclose(naq_file); if(params->extract_tilt == 1) fclose(spectral_tilt_file); if(params->extract_f0 == 1) fclose(fundf_file); if(params->extract_info == 1) fclose(params_file); if(params->extract_hnr == 1) fclose(HNR_file); if(params->extract_harmonics == 1) fclose(harmonics_file); if(params->extract_waveform == 1) fclose(waveform_file); if(params->extract_source == 1) fclose(source_file); if(params->sep_vuv_spectrum == 1) fclose(LSF2_file); if(params->write_fftspectra_to_file == 1) fclose(FFTvt_file); if(params->write_fftspectra_to_file == 1) fclose(FFTsrc_file); /* Save source signal to wav file */ Save_source_signal_to_wavfile(filename, source_signal, params); /* Free memory */ gsl_vector_free(source_signal); gsl_vector_free(gain); gsl_vector_free(h1h2); gsl_vector_free(naq); gsl_vector_free(fundf); gsl_matrix_free(spectral_tilt); gsl_matrix_free(LSF); gsl_matrix_free(LSF2); gsl_matrix_free(HNR); gsl_matrix_free(harmonics); gsl_matrix_free(waveform); gsl_matrix_free(fftmatrix_vt); gsl_matrix_free(fftmatrix_src); } /** * Function Select_unique_pulses * * Select only unique pulses from the pulses library, i.e. remove pulses that are extracted from different frames, * but are actually the same pulse instants. Among several same pulses, select the ones closest to global or local * average. * * @param ... */ void Select_unique_pulses(gsl_matrix **gpulses, gsl_matrix **gpulses_rs, gsl_vector **pulse_lengths, gsl_vector **pulse_pos, gsl_vector **pulse_inds, gsl_matrix **plsf, gsl_matrix **ptilt, gsl_matrix **phnr, gsl_matrix **pharm, gsl_matrix **pwaveform, gsl_vector **pgain, gsl_vector **ph1h2, gsl_vector **pnaq, PARAM *params) { /* Do not perform if there is no pulse library */ if(params->extract_pulselib_params == 0 || params->number_of_pulses == 0) return; /* Initialize */ int i,j; gsl_vector *best_pulse_inds = NULL; /* Do not perform if all pulses must be extracted */ if(params->extract_only_unique_pulses == 1) { /* Initialize */ int k,N = params->number_of_pulses; /* Evaluate global mean of the pulses */ gsl_vector *global_mean = gsl_vector_calloc((*gpulses_rs)->size2); for(i=0;i<global_mean->size;i++) for(j=0;j<N;j++) gsl_vector_set(global_mean,i,gsl_vector_get(global_mean,i) + gsl_matrix_get((*gpulses_rs),j,i)); for(i=0;i<global_mean->size;i++) gsl_vector_set(global_mean,i,gsl_vector_get(global_mean,i)/N); /* Find pulses with (approximately) the same starting sample index */ gsl_vector *pulse_number = gsl_vector_alloc(N); gsl_vector *pulse_inds_tmp = gsl_vector_alloc((*pulse_inds)->size); gsl_vector_memcpy(pulse_inds_tmp,(*pulse_inds)); double psit = PULSE_START_INDEX_THRESHOLD*(params->FS/16000.0); int new_flag; int ind = 0; for(i=0;i<N;i++) { new_flag = 0; if(gsl_vector_get(pulse_inds_tmp,i) > 0) { for(j=i;j<N;j++) { if(fabs(gsl_vector_get((*pulse_inds),i)-gsl_vector_get(pulse_inds_tmp,j)) < psit) { gsl_vector_set(pulse_number,j,ind); gsl_vector_set(pulse_inds_tmp,j,BIG_NEG_NUMBER); new_flag = 1; } } if(new_flag == 1) ind++; } } gsl_vector_free(pulse_inds_tmp); /* Select best estimate of the pulse from all the instances */ int Nuniq = gsl_vector_max(pulse_number)+1; best_pulse_inds = gsl_vector_alloc(Nuniq); gsl_vector *local_mean = gsl_vector_alloc((*gpulses_rs)->size2); gsl_vector *pinds_tmp = gsl_vector_alloc(N); int npulses; for(i=0;i<Nuniq;i++) { /* Initialize */ gsl_vector_set_zero(pinds_tmp); npulses = 0; /* Count and mark pulses belonging to the same time instance */ for(j=0;j<N;j++) { if(gsl_vector_get(pulse_number,j) == i) { gsl_vector_set(pinds_tmp,npulses,j); npulses++; } } /* Evaluate best pulses: * * 1. Single instance, set directly */ if(npulses == 1) { gsl_vector_set(best_pulse_inds,i,gsl_vector_get(pinds_tmp,0)); /* 2. Two instances, select the one closest to global mean */ } else if(npulses == 2) { double err1 = 0, err2 = 0; for(j=0;j<global_mean->size;j++) { err1 += fabs(gsl_vector_get(global_mean,j) - gsl_matrix_get((*gpulses_rs),gsl_vector_get(pinds_tmp,0),j)); err2 += fabs(gsl_vector_get(global_mean,j) - gsl_matrix_get((*gpulses_rs),gsl_vector_get(pinds_tmp,1),j)); } if(err1 < err2) gsl_vector_set(best_pulse_inds,i,gsl_vector_get(pinds_tmp,0)); else gsl_vector_set(best_pulse_inds,i,gsl_vector_get(pinds_tmp,1)); /* 3. More than two instances, select the one closest to local mean */ } else { /* Eval local mean */ gsl_vector_set_zero(local_mean); for(k=0;k<local_mean->size;k++) for(j=0;j<npulses;j++) gsl_vector_set(local_mean,k,gsl_vector_get(local_mean,k) + gsl_matrix_get((*gpulses_rs),gsl_vector_get(pinds_tmp,j),k)); for(k=0;k<local_mean->size;k++) gsl_vector_set(local_mean,k,gsl_vector_get(local_mean,k)/(double)npulses); /* Eval error */ gsl_vector *error = gsl_vector_calloc(npulses); for(j=0;j<npulses;j++) for(k=0;k<local_mean->size;k++) gsl_vector_set(error,j,gsl_vector_get(error,j) + fabs(gsl_vector_get(local_mean,k) - gsl_matrix_get((*gpulses_rs),gsl_vector_get(pinds_tmp,j),k))); /* Find minimum error */ double min_error = BIG_POS_NUMBER; double min_index = 0; for(j=0;j<npulses;j++) { if(gsl_vector_get(error,j) < min_error) { min_error = gsl_vector_get(error,j); min_index = j; } } gsl_vector_free(error); /* Select pulse with minimum error */ gsl_vector_set(best_pulse_inds,i,gsl_vector_get(pinds_tmp,min_index)); } } gsl_vector_free(global_mean); gsl_vector_free(local_mean); gsl_vector_free(pinds_tmp); gsl_vector_free(pulse_number); /* Set number of pulses */ params->number_of_pulses = Nuniq; } /* Resize pulse and parameter matrices */ gsl_matrix *gpulses_new = gsl_matrix_alloc(params->number_of_pulses,(*gpulses)->size2); gsl_matrix *gpulses_rs_new = gsl_matrix_alloc(params->number_of_pulses,(*gpulses_rs)->size2); gsl_vector *pulse_pos_new = gsl_vector_alloc(params->number_of_pulses); gsl_vector *pulse_inds_new = gsl_vector_alloc(params->number_of_pulses); gsl_vector *pulse_lengths_new = gsl_vector_alloc(params->number_of_pulses); gsl_matrix *plsf_new = gsl_matrix_alloc(params->number_of_pulses,(*plsf)->size2); gsl_matrix *ptilt_new = gsl_matrix_alloc(params->number_of_pulses,(*ptilt)->size2); gsl_matrix *pharm_new = gsl_matrix_alloc(params->number_of_pulses,(*pharm)->size2); gsl_matrix *phnr_new = gsl_matrix_alloc(params->number_of_pulses,(*phnr)->size2); gsl_matrix *pwaveform_new = gsl_matrix_alloc(params->number_of_pulses,(*pwaveform)->size2); gsl_vector *pgain_new = gsl_vector_alloc(params->number_of_pulses); gsl_vector *ph1h2_new = gsl_vector_alloc(params->number_of_pulses); gsl_vector *pnaq_new = gsl_vector_alloc(params->number_of_pulses); /* Set pulses and parameters */ int index; for(i=0;i<params->number_of_pulses;i++) { /* Select index (depending on whether only unique or all pulses are saved */ if(params->extract_only_unique_pulses == 1) index = gsl_vector_get(best_pulse_inds,i); else index = i; /* Set pulses and parameters */ for(j=0;j<(*gpulses)->size2;j++) gsl_matrix_set(gpulses_new,i,j,gsl_matrix_get((*gpulses),index,j)); for(j=0;j<(*gpulses_rs)->size2;j++) gsl_matrix_set(gpulses_rs_new,i,j,gsl_matrix_get((*gpulses_rs),index,j)); gsl_vector_set(pulse_pos_new,i,gsl_vector_get((*pulse_pos),index)); gsl_vector_set(pulse_lengths_new,i,gsl_vector_get((*pulse_lengths),index)); gsl_vector_set(pulse_inds_new,i,gsl_vector_get((*pulse_inds),index)); for(j=0;j<(*plsf)->size2;j++) gsl_matrix_set(plsf_new,i,j,gsl_matrix_get((*plsf),index,j)); for(j=0;j<(*ptilt)->size2;j++) gsl_matrix_set(ptilt_new,i,j,gsl_matrix_get((*ptilt),index,j)); for(j=0;j<(*pharm)->size2;j++) gsl_matrix_set(pharm_new,i,j,gsl_matrix_get((*pharm),index,j)); for(j=0;j<(*phnr)->size2;j++) gsl_matrix_set(phnr_new,i,j,gsl_matrix_get((*phnr),index,j)); for(j=0;j<(*pwaveform)->size2;j++) gsl_matrix_set(pwaveform_new,i,j,gsl_matrix_get((*pwaveform),index,j)); gsl_vector_set(pgain_new,i,gsl_vector_get((*pgain),index)); gsl_vector_set(ph1h2_new,i,gsl_vector_get((*ph1h2),index)); gsl_vector_set(pnaq_new,i,gsl_vector_get((*pnaq),index)); } /* Free variables */ if(params->extract_only_unique_pulses == 1) gsl_vector_free(best_pulse_inds); gsl_matrix_free(*gpulses); gsl_matrix_free(*gpulses_rs); gsl_vector_free(*pulse_inds); gsl_vector_free(*pulse_pos); gsl_vector_free(*pulse_lengths); gsl_matrix_free(*plsf); gsl_matrix_free(*ptilt); gsl_matrix_free(*pharm); gsl_matrix_free(*phnr); gsl_matrix_free(*pwaveform); gsl_vector_free(*pgain); gsl_vector_free(*ph1h2); gsl_vector_free(*pnaq); /* Set pointers */ (*gpulses) = gpulses_new; (*gpulses_rs) = gpulses_rs_new; (*pulse_inds) = pulse_inds_new; (*pulse_pos) = pulse_pos_new; (*pulse_lengths) = pulse_lengths_new; (*plsf) = plsf_new; (*ptilt) = ptilt_new; (*pharm) = pharm_new; (*phnr) = phnr_new; (*pwaveform) = pwaveform_new; (*pgain) = pgain_new; (*ph1h2) = ph1h2_new; (*pnaq) = pnaq_new; } /** * Function Select_one_pulse_per_frame * * Select only one pulse per frame, i.e. remove pulses (except one) that are extracted from the same frame in order to remove bias * towards high-pitched pulses. Among several pulses in the frame, select the one closest to global or local average. * * @param ... */ void Select_one_pulse_per_frame(gsl_matrix **gpulses, gsl_matrix **gpulses_rs, gsl_vector **pulse_lengths, gsl_vector **pulse_pos, gsl_vector **pulse_inds, gsl_matrix **plsf, gsl_matrix **ptilt, gsl_matrix **phnr, gsl_matrix **pharm, gsl_matrix **pwaveform, gsl_vector **pgain, gsl_vector **ph1h2, gsl_vector **pnaq, PARAM *params) { /* Do not perform if there is no pulse library */ if(params->extract_pulselib_params == 0 || params->number_of_pulses == 0) return; /* Initialize */ int i,j; gsl_vector *best_pulse_inds = NULL; /* Do not perform if all pulses must be extracted */ if(params->extract_one_pulse_per_frame == 1) { /* Initialize */ int k,N = params->number_of_pulses; /* Evaluate global mean of the pulses */ gsl_vector *global_mean = gsl_vector_calloc((*gpulses_rs)->size2); for(i=0;i<global_mean->size;i++) for(j=0;j<N;j++) gsl_vector_set(global_mean,i,gsl_vector_get(global_mean,i) + gsl_matrix_get((*gpulses_rs),j,i)); for(i=0;i<global_mean->size;i++) gsl_vector_set(global_mean,i,gsl_vector_get(global_mean,i)/N); /* Find pulses from same frame */ gsl_vector *pulse_number = gsl_vector_calloc(N); gsl_vector *pulse_pos_tmp = gsl_vector_alloc((*pulse_pos)->size); gsl_vector_memcpy(pulse_pos_tmp,(*pulse_pos)); int new_flag; int ind = 0; for(i=0;i<N;i++) { new_flag = 0; for(j=i;j<N;j++) { if(fabs(gsl_vector_get((*pulse_pos),i) == gsl_vector_get(pulse_pos_tmp,j))) { gsl_vector_set(pulse_number,j,ind); gsl_vector_set(pulse_pos_tmp,j,BIG_NEG_NUMBER); new_flag = 1; } } if(new_flag == 1) ind++; } gsl_vector_free(pulse_pos_tmp); /* Select one pulse from each frame */ int Nuniq = gsl_vector_max(pulse_number)+1; best_pulse_inds = gsl_vector_alloc(Nuniq); gsl_vector *local_mean = gsl_vector_alloc((*gpulses_rs)->size2); gsl_vector *pinds_tmp = gsl_vector_alloc(N); int npulses; for(i=0;i<Nuniq;i++) { /* Initialize */ gsl_vector_set_zero(pinds_tmp); npulses = 0; /* Count and mark pulses belonging to the same frame */ for(j=0;j<N;j++) { if(gsl_vector_get(pulse_number,j) == i) { gsl_vector_set(pinds_tmp,npulses,j); npulses++; } } /* Evaluate best pulses: * * 1. Single instance, set directly */ if(npulses == 1) { gsl_vector_set(best_pulse_inds,i,gsl_vector_get(pinds_tmp,0)); /* 2. Two instances, select the one closest to global mean */ } else if(npulses == 2) { double err1 = 0, err2 = 0; for(j=0;j<global_mean->size;j++) { err1 += fabs(gsl_vector_get(global_mean,j) - gsl_matrix_get((*gpulses_rs),gsl_vector_get(pinds_tmp,0),j)); err2 += fabs(gsl_vector_get(global_mean,j) - gsl_matrix_get((*gpulses_rs),gsl_vector_get(pinds_tmp,1),j)); } if(err1 < err2) gsl_vector_set(best_pulse_inds,i,gsl_vector_get(pinds_tmp,0)); else gsl_vector_set(best_pulse_inds,i,gsl_vector_get(pinds_tmp,1)); /* 3. More than two instances, select the one closest to local mean */ } else { /* Eval local mean */ gsl_vector_set_zero(local_mean); for(k=0;k<local_mean->size;k++) for(j=0;j<npulses;j++) gsl_vector_set(local_mean,k,gsl_vector_get(local_mean,k) + gsl_matrix_get((*gpulses_rs),gsl_vector_get(pinds_tmp,j),k)); for(k=0;k<local_mean->size;k++) gsl_vector_set(local_mean,k,gsl_vector_get(local_mean,k)/(double)npulses); /* Eval error */ gsl_vector *error = gsl_vector_calloc(npulses); for(j=0;j<npulses;j++) for(k=0;k<local_mean->size;k++) gsl_vector_set(error,j,gsl_vector_get(error,j) + fabs(gsl_vector_get(local_mean,k) - gsl_matrix_get((*gpulses_rs),gsl_vector_get(pinds_tmp,j),k))); /* Find minimum error */ double min_error = BIG_POS_NUMBER; double min_index = 0; for(j=0;j<npulses;j++) { if(gsl_vector_get(error,j) < min_error) { min_error = gsl_vector_get(error,j); min_index = j; } } gsl_vector_free(error); /* Select pulse with minimum error */ gsl_vector_set(best_pulse_inds,i,gsl_vector_get(pinds_tmp,min_index)); } } gsl_vector_free(global_mean); gsl_vector_free(local_mean); gsl_vector_free(pinds_tmp); gsl_vector_free(pulse_number); /* Set number of pulses */ params->number_of_pulses = Nuniq; } /* Resize pulse and parameter matrices */ gsl_matrix *gpulses_new = gsl_matrix_alloc(params->number_of_pulses,(*gpulses)->size2); gsl_matrix *gpulses_rs_new = gsl_matrix_alloc(params->number_of_pulses,(*gpulses_rs)->size2); gsl_vector *pulse_pos_new = gsl_vector_alloc(params->number_of_pulses); gsl_vector *pulse_inds_new = gsl_vector_alloc(params->number_of_pulses); gsl_vector *pulse_lengths_new = gsl_vector_alloc(params->number_of_pulses); gsl_matrix *plsf_new = gsl_matrix_alloc(params->number_of_pulses,(*plsf)->size2); gsl_matrix *ptilt_new = gsl_matrix_alloc(params->number_of_pulses,(*ptilt)->size2); gsl_matrix *pharm_new = gsl_matrix_alloc(params->number_of_pulses,(*pharm)->size2); gsl_matrix *phnr_new = gsl_matrix_alloc(params->number_of_pulses,(*phnr)->size2); gsl_matrix *pwaveform_new = gsl_matrix_alloc(params->number_of_pulses,(*pwaveform)->size2); gsl_vector *pgain_new = gsl_vector_alloc(params->number_of_pulses); gsl_vector *ph1h2_new = gsl_vector_alloc(params->number_of_pulses); gsl_vector *pnaq_new = gsl_vector_alloc(params->number_of_pulses); /* Set pulses and parameters */ int index; for(i=0;i<params->number_of_pulses;i++) { /* Select index */ if(params->extract_one_pulse_per_frame == 1) index = gsl_vector_get(best_pulse_inds,i); else index = i; /* Set pulses and parameters */ for(j=0;j<(*gpulses)->size2;j++) gsl_matrix_set(gpulses_new,i,j,gsl_matrix_get((*gpulses),index,j)); for(j=0;j<(*gpulses_rs)->size2;j++) gsl_matrix_set(gpulses_rs_new,i,j,gsl_matrix_get((*gpulses_rs),index,j)); gsl_vector_set(pulse_pos_new,i,gsl_vector_get((*pulse_pos),index)); gsl_vector_set(pulse_lengths_new,i,gsl_vector_get((*pulse_lengths),index)); gsl_vector_set(pulse_inds_new,i,gsl_vector_get((*pulse_inds),index)); for(j=0;j<(*plsf)->size2;j++) gsl_matrix_set(plsf_new,i,j,gsl_matrix_get((*plsf),index,j)); for(j=0;j<(*ptilt)->size2;j++) gsl_matrix_set(ptilt_new,i,j,gsl_matrix_get((*ptilt),index,j)); for(j=0;j<(*pharm)->size2;j++) gsl_matrix_set(pharm_new,i,j,gsl_matrix_get((*pharm),index,j)); for(j=0;j<(*phnr)->size2;j++) gsl_matrix_set(phnr_new,i,j,gsl_matrix_get((*phnr),index,j)); for(j=0;j<(*pwaveform)->size2;j++) gsl_matrix_set(pwaveform_new,i,j,gsl_matrix_get((*pwaveform),index,j)); gsl_vector_set(pgain_new,i,gsl_vector_get((*pgain),index)); gsl_vector_set(ph1h2_new,i,gsl_vector_get((*ph1h2),index)); gsl_vector_set(pnaq_new,i,gsl_vector_get((*pnaq),index)); } /* Free variables */ if(params->extract_only_unique_pulses == 1) gsl_vector_free(best_pulse_inds); gsl_matrix_free(*gpulses); gsl_matrix_free(*gpulses_rs); gsl_vector_free(*pulse_inds); gsl_vector_free(*pulse_pos); gsl_vector_free(*pulse_lengths); gsl_matrix_free(*plsf); gsl_matrix_free(*ptilt); gsl_matrix_free(*pharm); gsl_matrix_free(*phnr); gsl_matrix_free(*pwaveform); gsl_vector_free(*pgain); gsl_vector_free(*ph1h2); gsl_vector_free(*pnaq); /* Set pointers */ (*gpulses) = gpulses_new; (*gpulses_rs) = gpulses_rs_new; (*pulse_inds) = pulse_inds_new; (*pulse_pos) = pulse_pos_new; (*pulse_lengths) = pulse_lengths_new; (*plsf) = plsf_new; (*ptilt) = ptilt_new; (*pharm) = pharm_new; (*phnr) = phnr_new; (*pwaveform) = pwaveform_new; (*pgain) = pgain_new; (*ph1h2) = ph1h2_new; (*pnaq) = pnaq_new; } /** * Function Write_pulselibrary_to_file * * Write pulse library parameters to file * * @param ... */ void Write_pulselibrary_to_file(char *filename, gsl_matrix *gpulses, gsl_matrix *gpulses_rs, gsl_vector *pulse_lengths, gsl_vector *pulse_pos, gsl_vector *pulse_inds, gsl_matrix *plsf, gsl_matrix *ptilt, gsl_matrix *phnr, gsl_matrix *pharm, gsl_matrix *pwaveform, gsl_vector *pgain, gsl_vector *ph1h2, gsl_vector *pnaq, PARAM *params) { /* Do not save data if not requested or pulses were not found */ if(params->extract_pulselib_params == 1 && params->number_of_pulses > 0) { /* Initialize */ int slen = strlen(filename)-4; // Remove ".wav" extension char orig[slen+1]; char tmp[DEF_STRING_LEN]; strncpy(orig, filename, slen); orig[slen] = '\0'; /* Check that the number of pulses is not more than the maximum number of pulses */ if(params->number_of_pulses > params->maxnumberofpulses) params->number_of_pulses = params->maxnumberofpulses; /* Save pulse data */ FILE *gpulses_file,*gpulses_rs_file,*pulse_pos_file,*pulse_lengths_file,*pulse_inds_file; strcpy(tmp, orig);gpulses_file = fopen(strcat(tmp, FILENAME_ENDING_PULSELIB_PULSES), "w"); if(gpulses_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);} strcpy(tmp, orig);gpulses_rs_file = fopen(strcat(tmp, FILENAME_ENDING_PULSELIB_RSPULSES), "w"); if(gpulses_rs_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);} strcpy(tmp, orig);pulse_pos_file = fopen(strcat(tmp, FILENAME_ENDING_PULSELIB_PULSEPOS), "w"); if(pulse_pos_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);} strcpy(tmp, orig);pulse_inds_file = fopen(strcat(tmp, FILENAME_ENDING_PULSELIB_PULSEINDS), "w"); if(pulse_inds_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);} strcpy(tmp, orig);pulse_lengths_file = fopen(strcat(tmp, FILENAME_ENDING_PULSELIB_PULSELENGTHS), "w"); if(pulse_lengths_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);} if(params->data_format == DATA_FORMAT_ID_ASCII) { gsl_matrix_fprintf(gpulses_file, gpulses, "%.9f"); gsl_matrix_fprintf(gpulses_rs_file, gpulses_rs, "%.9f"); gsl_vector_fprintf(pulse_lengths_file, pulse_lengths, "%.0f"); gsl_vector_fprintf(pulse_pos_file, pulse_pos, "%.0f"); gsl_vector_fprintf(pulse_inds_file, pulse_inds, "%.0f"); } else if(params->data_format == DATA_FORMAT_ID_BINARY) { gsl_matrix_fwrite(gpulses_file, gpulses); gsl_matrix_fwrite(gpulses_rs_file, gpulses_rs); gsl_vector_fwrite(pulse_lengths_file, pulse_lengths); gsl_vector_fwrite(pulse_pos_file, pulse_pos); gsl_vector_fwrite(pulse_inds_file, pulse_inds); } fclose(gpulses_file); fclose(gpulses_rs_file); fclose(pulse_pos_file); fclose(pulse_inds_file); fclose(pulse_lengths_file); /* Save parameter data */ FILE *plsf_file,*ptilt_file,*pharm_file,*phnr_file,*pgain_file,*pwaveform_file,*ph1h2_file,*pnaq_file; strcpy(tmp, orig);plsf_file = fopen(strcat(tmp, FILENAME_ENDING_PULSELIB_LSF), "w"); if(plsf_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);} strcpy(tmp, orig);ptilt_file = fopen(strcat(tmp, FILENAME_ENDING_PULSELIB_TILT), "w"); if(ptilt_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);} strcpy(tmp, orig);pharm_file = fopen(strcat(tmp, FILENAME_ENDING_PULSELIB_HARM), "w"); if(pharm_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);} strcpy(tmp, orig);phnr_file = fopen(strcat(tmp, FILENAME_ENDING_PULSELIB_HNR), "w"); if(phnr_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);} strcpy(tmp, orig);pwaveform_file = fopen(strcat(tmp, FILENAME_ENDING_PULSELIB_WAVEFORM), "w"); if(pwaveform_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);} strcpy(tmp, orig);pgain_file = fopen(strcat(tmp, FILENAME_ENDING_PULSELIB_GAIN), "w"); if(pgain_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);} strcpy(tmp, orig);ph1h2_file = fopen(strcat(tmp, FILENAME_ENDING_PULSELIB_H1H2), "w"); if(ph1h2_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);} strcpy(tmp, orig);pnaq_file = fopen(strcat(tmp, FILENAME_ENDING_PULSELIB_NAQ), "w"); if(pnaq_file==NULL) {printf("Error: Can't create file \"%s\".\n", tmp);} if(params->data_format == DATA_FORMAT_ID_ASCII) { gsl_matrix_fprintf(plsf_file, plsf, "%.7f"); gsl_matrix_fprintf(ptilt_file, ptilt, "%.7f"); gsl_matrix_fprintf(pharm_file, pharm, "%.7f"); gsl_matrix_fprintf(phnr_file, phnr, "%.7f"); gsl_matrix_fprintf(pwaveform_file, pwaveform, "%.7f"); gsl_vector_fprintf(pgain_file, pgain, "%.7f"); gsl_vector_fprintf(ph1h2_file, ph1h2, "%.7f"); gsl_vector_fprintf(pnaq_file, pnaq, "%.7f"); } else if(params->data_format == DATA_FORMAT_ID_BINARY) { gsl_matrix_fwrite(plsf_file, plsf); gsl_matrix_fwrite(ptilt_file, ptilt); gsl_matrix_fwrite(pharm_file, pharm); gsl_matrix_fwrite(phnr_file, phnr); gsl_matrix_fwrite(pwaveform_file, pwaveform); gsl_vector_fwrite(pgain_file, pgain); gsl_vector_fwrite(ph1h2_file, ph1h2); gsl_vector_fwrite(pnaq_file, pnaq); } fclose(plsf_file); fclose(ptilt_file); fclose(pharm_file); fclose(phnr_file); fclose(pwaveform_file); fclose(pgain_file); fclose(ph1h2_file); fclose(pnaq_file); } /* Free memory */ gsl_matrix_free(gpulses); gsl_matrix_free(gpulses_rs); gsl_vector_free(pulse_inds); gsl_vector_free(pulse_pos); gsl_vector_free(pulse_lengths); gsl_matrix_free(plsf); gsl_matrix_free(ptilt); gsl_matrix_free(pharm); gsl_matrix_free(phnr); gsl_matrix_free(pwaveform); gsl_vector_free(pgain); gsl_vector_free(ph1h2); gsl_vector_free(pnaq); } /** * Function Free_variables * * Free analysis variables * * @param ... */ void Free_variables(gsl_vector *frame, gsl_vector *frame0, gsl_vector *signal, gsl_vector *glottal, gsl_vector *glottsig, gsl_vector *glottsig_f0, gsl_vector *uvgain, gsl_vector *f0_frame, gsl_vector *f0_frame0, gsl_vector *glottal_f0, gsl_matrix *bp_gain, gsl_matrix *fundf_candidates, gsl_matrix *fftmatrix_uv) { gsl_vector_free(frame); gsl_vector_free(frame0); gsl_vector_free(signal); gsl_vector_free(glottal); gsl_vector_free(glottsig); gsl_vector_free(glottsig_f0); gsl_vector_free(uvgain); gsl_vector_free(f0_frame); gsl_vector_free(f0_frame0); gsl_vector_free(glottal_f0); gsl_matrix_free(bp_gain); gsl_matrix_free(fundf_candidates); gsl_matrix_free(fftmatrix_uv); } /** * Function Save_source_signal_to_wavfile * * Save source signal to wav file * * @param filename * @param signal * @param params */ void Save_source_signal_to_wavfile(char *filename, gsl_vector *signal, PARAM *params) { if(params->extract_source == 0) return; /* Scale maximum to one if absmax is greater than one */ int i; double absmax = GSL_MAX(gsl_vector_max(signal),-gsl_vector_min(signal)); if(absmax > 1.0) { absmax = WAV_SCALE/absmax; for(i=0;i<signal->size;i++) gsl_vector_set(signal,i,gsl_vector_get(signal,i)*absmax); } /* Copy values to array */ double *samples = (double *)calloc(signal->size, sizeof(double)); for(i=0;i<signal->size;i++) samples[i] = gsl_vector_get(signal,i); /* Save synthesized speech to wav-file */ SNDFILE *soundfile; SF_INFO sfinfo; sfinfo.samplerate = params->FS; sfinfo.channels = 1; sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16; char temp[DEF_STRING_LEN]; strcpy(temp, filename); /* Open file with default ending or givend ending */ int slen = strlen(filename)-4; // Remove ending ".wav" char tmp[DEF_STRING_LEN]; strncpy(tmp, filename, slen); tmp[slen] = '\0'; soundfile = sf_open(strcat(tmp,FILENAME_ENDING_SOURCESIGNAL_WAV), SFM_WRITE, &sfinfo); /* Check if success */ if(soundfile==NULL) { printf("\n\nError creating file \"%s\": %s\n\n",temp,strerror(errno)); return; } /* Write to file */ sf_write_double(soundfile, samples, signal->size); /* Free memory */ free(samples); sf_close(soundfile); } /** * Function Convert_F0_to_log * * Convert fundamental frequency vector to natural logarithm * * @param fundf * @param params */ void Convert_F0_to_log(gsl_vector *fundf, PARAM *params) { if(params->logf0 == 0) return; int i; for(i=0;i<fundf->size;i++) gsl_vector_set(fundf,i,log(gsl_vector_get(fundf,i))); } /** * Function EvalFFTSpectrum * * Calculate FFT of the signal and write spectrum to matrix * * @param signal pointer to signal vector * @param matrix matrix for the spectrum * @param index index of the parameters * */ void EvalFFTSpectrum(gsl_vector *signal, gsl_matrix *matrix, int index, PARAM *params) { /* Skip if not defined to be performed */ if(params->write_fftspectra_to_file == 1) { /* Initialize */ int i; double data[OUTPUT_FFT_LENGTH] = {0}; /* FFT with windowing */ for(i=0; i<signal->size; i++) data[i] = gsl_vector_get(signal, i)*HANN(i,signal->size); gsl_fft_real_radix2_transform(data, 1, OUTPUT_FFT_LENGTH); for(i=1; i<OUTPUT_FFT_LENGTH/2; i++) { gsl_matrix_set(matrix, index, i, sqrt(pow(data[i], 2) + pow(data[OUTPUT_FFT_LENGTH-i], 2))); } gsl_matrix_set(matrix, index, 0, data[0]); } } /** * Function WriteFFTSpectrumToFile * * Write spectrum matrix to file * * @param filename * @param fft matrix * */ void WriteFFTSpectrumToFile(char *filename, gsl_matrix *fft, PARAM *params) { /* Skip if not defined to be performed */ if(params->write_fftspectra_to_file == 1) { } } /*****************************************************************************/ /* FUNCTIONS NOT IN USE */ /*****************************************************************************/ /** * Function Interpolate_lin * * Interpolates linearly given vector to new vector of given length * * @param vector original vector * @param i_vector interpolated vector */ void Interpolate_lin(gsl_vector *vector, gsl_vector *i_vector) { int i,len = vector->size,length = i_vector->size; /* Read values to array */ double x[len]; double y[len]; for(i=0; i<len; i++) { x[i] = i; y[i] = gsl_vector_get(vector,i); } gsl_interp_accel *acc = gsl_interp_accel_alloc(); gsl_spline *spline = gsl_spline_alloc(gsl_interp_linear, len); gsl_spline_init(spline, x, y, len); double xi; i = 0; /* New implementation (27.3.2009, bug fix 8.2.2010) */ xi = x[0]; while(i<length) { gsl_vector_set(i_vector,i,gsl_spline_eval(spline, xi, acc)); xi += (len-1)/(double)(length-1); i++; } /* Free memory */ gsl_spline_free(spline); gsl_interp_accel_free(acc); } /** * Function Interpolate_poly * * Interpolate (polynomial) given vector to new vector of given length * * @param vector original vector * @param i_vector interpolated vector */ void Interpolate_poly(gsl_vector *vector, gsl_vector *i_vector) { int i,len = vector->size,length = i_vector->size; /* Read values to array */ double x[len]; double y[len]; for(i=0; i<len; i++) { x[i] = i; y[i] = gsl_vector_get(vector,i); } gsl_interp_accel *acc = gsl_interp_accel_alloc(); gsl_spline *spline = gsl_spline_alloc(gsl_interp_polynomial,len); gsl_spline_init(spline, x, y, len); double xi; i = 0; /* New implementation (27.3.2009, bug fix 8.2.2010) */ xi = x[0]; while(i<length) { gsl_vector_set(i_vector,i,gsl_spline_eval(spline, xi, acc)); xi += (len-1)/(double)(length-1); i++; } /* Free memory */ gsl_spline_free(spline); gsl_interp_accel_free(acc); } /** * Function Pole_stabilize * * Check the validity of polynomial through mirroring poles outside the unit circle * * @param lpc polynomial vector */ void Pole_stabilize(gsl_vector *a) { int i,j,k; int n_c = a->size; int n_r = 2*(n_c-1); double r,yr,yc; double coeffs[n_c]; double roots[n_r]; gsl_vector *out_roots = gsl_vector_calloc(n_c); gsl_matrix *ac = gsl_matrix_calloc(2,a->size); gsl_matrix *temp = gsl_matrix_alloc(ac->size1,ac->size2); /* Copy coefficients to array coeffs and matrix ac */ for(i=0; i<n_c; i++) { coeffs[i] = gsl_vector_get(a, a->size-i-1); gsl_matrix_set(ac,0,i,gsl_vector_get(a,i)); } /* Solve roots */ gsl_poly_complex_workspace *w = gsl_poly_complex_workspace_alloc(n_c); gsl_poly_complex_solve(coeffs, n_c, w, roots); gsl_poly_complex_workspace_free(w); /* Find roots whose absolute value is greater than one */ for(i=0; i<n_r/2; i++) { r = sqrt(powf(roots[2*i],2) + powf(roots[2*i+1],2)); if(r > 1.0) gsl_vector_set(out_roots,i,1.0/powf(r,2)); } /* Scale roots that are greater than one */ for(i=0; i<n_c; i++) { if(gsl_vector_get(out_roots,i) > 0) { /* Deconvolve with root outside the unit circle (complex numbers) */ yr = 0;yc = 0; for(j=0; j<n_c; j++) { gsl_matrix_set(ac, 0, j, gsl_matrix_get(ac, 0, j) + yr*roots[2*i] - yc*roots[2*i+1]); gsl_matrix_set(ac, 1, j, gsl_matrix_get(ac, 1, j) + yr*roots[2*i+1] + yc*roots[2*i]); yr = gsl_matrix_get(ac, 0, j); yc = gsl_matrix_get(ac, 1, j); } gsl_matrix_set(ac, 0, ac->size2-1, 0); gsl_matrix_set(ac, 1, ac->size2-1, 0); /* Scaled root */ double scaled_root_r[2] = {1, -1*gsl_vector_get(out_roots,i)*roots[2*i]}; double scaled_root_c[2] = {0, -1*gsl_vector_get(out_roots,i)*roots[2*i+1]}; /* Convolve with scaled root (complex numbers) */ gsl_matrix_set_all(temp,0); for(j=0; j<n_c; j++) { yr = 0;yc = 0; for(k=0; k<=GSL_MIN(j, 1); k++) { yr += gsl_matrix_get(ac, 0, j-k)*scaled_root_r[k] - gsl_matrix_get(ac, 1, j-k)*scaled_root_c[k]; yc += gsl_matrix_get(ac, 0, j-k)*scaled_root_c[k] + gsl_matrix_get(ac, 1, j-k)*scaled_root_r[k]; } gsl_matrix_set(temp, 0, j, yr); gsl_matrix_set(temp, 1, j, yc); } /* Copy result to ac */ for(j=0; j<n_c; j++) { gsl_matrix_set(ac, 0, j, gsl_matrix_get(temp, 0, j)); gsl_matrix_set(ac, 1, j, gsl_matrix_get(temp, 1, j)); } } } /* Take only the real values and copy to original coefficient vector */ for(j=0; j<n_c; j++) gsl_vector_set(a, j, gsl_matrix_get(ac, 0, j)); /* Free memory */ gsl_vector_free(out_roots); gsl_matrix_free(ac); gsl_matrix_free(temp); } /** * Function LSF_stabilize * * Check the validity of polynomial through LSFs and fix found errors * * @param lsf vector */ void LSF_stabilize(gsl_vector *a) { gsl_vector *lsf = gsl_vector_calloc(a->size-1); Convert_vector_to_LSF(a, lsf); LSF_fix_vector(lsf); lsf_vector2poly(lsf,a); } /** * Function LSF_fix_vector * * Check the validity of LSF and fix found errors (vector) * * @param lsf vector */ void LSF_fix_vector(gsl_vector *lsf) { int i,ok = 0; double mean; int flag_neg = 0; int flag_zero = 0; int flag_pi = 0; int flag_piplus = 0; int flag_nan = 0; int flag_dec = 0; int flag_close = 0; /* Repeat until LSF is fixed */ while(ok == 0) { /* Set ok */ ok = 1; /* Check and correct values less than zero or greater than pi */ for(i=0;i<lsf->size;i++) { if(gsl_vector_get(lsf,i) < 0) { gsl_vector_set(lsf,i,LSF_EPSILON); flag_neg++; ok = 0; } else if(gsl_vector_get(lsf,i) < LSF_EPSILON) { gsl_vector_set(lsf,i,LSF_EPSILON); flag_zero++; ok = 0; } else if(gsl_vector_get(lsf,i) > M_PI) { gsl_vector_set(lsf,i,M_PI-LSF_EPSILON); flag_piplus++; ok = 0; } else if(gsl_vector_get(lsf,i) > M_PI-LSF_EPSILON) { gsl_vector_set(lsf,i,M_PI-LSF_EPSILON); flag_pi++; ok = 0; } if(gsl_isnan(gsl_vector_get(lsf,i))) { if(i == 0) gsl_vector_set(lsf,i,LSF_EPSILON); else if(i == lsf->size-1) gsl_vector_set(lsf,i,M_PI-LSF_EPSILON); else gsl_vector_set(lsf,i,(gsl_vector_get(lsf,i-1)+gsl_vector_get(lsf,i+1))/2.0); flag_nan++; ok = 0; } } /* Check and correct non-increasing values or coefficients too close */ for(i=0;i<lsf->size-1;i++) { if(gsl_vector_get(lsf,i) > gsl_vector_get(lsf,i+1)) { mean = (gsl_vector_get(lsf,i)+gsl_vector_get(lsf,i+1))/2.0; gsl_vector_set(lsf,i,mean - LSF_EPSILON/2.0); gsl_vector_set(lsf,i+1,mean + LSF_EPSILON/2.0); flag_dec++; ok = 0; } else if(gsl_vector_get(lsf,i) > gsl_vector_get(lsf,i+1)-LSF_EPSILON/10.0) { mean = (gsl_vector_get(lsf,i)+gsl_vector_get(lsf,i+1))/2.0; gsl_vector_set(lsf,i,mean - LSF_EPSILON/2.0); gsl_vector_set(lsf,i+1,mean + LSF_EPSILON/2.0); flag_close++; ok = 0; } } } /* Report */ if(flag_dec > 0) printf("Warning: %i decreasing LSFs -> Fixed!\n",flag_dec); if(flag_neg > 0) printf("Warning: %i negative LSFs -> Fixed!\n",flag_neg); if(flag_piplus > 0) printf("Warning: %i LSFs greater than Pi -> Fixed!\n",flag_piplus); if(flag_zero > 0) printf("Warning: %i LSFs too close to 0 -> Fixed!\n",flag_zero); if(flag_piplus > 0) printf("Warning: %i LSFs greater than Pi -> Fixed!\n",flag_pi); if(flag_close > 0) printf("Warning: %i LSFs too close to each other -> Fixed!\n",flag_close); if(flag_nan > 0) printf("Warning: %i NaN LSF value(s) -> Fixed!\n",flag_nan); } /** * Function IIR_filter * * IIR filter implementation (all-pole), coefficients in vector * * @param signal pointer to the samples * @param coeffs pointer to coefficients */ void IIR_filter(gsl_vector *signal, gsl_vector *coeffs) { int i,j,n = coeffs->size; double sum; /* Multiply filter coefficients by -1 */ for(i=1;i<coeffs->size;i++) { gsl_vector_set(coeffs,i,-gsl_vector_get(coeffs,i)); } /* Filter signal */ for(i=0; i<signal->size; i++) { sum = 0; for(j=0; j<=GSL_MIN(i, n-1); j++) { sum += gsl_vector_get(signal, i-j)*gsl_vector_get(coeffs,j); } gsl_vector_set(signal, i, sum); } } /** * Function FIR_filter_file * * FIR filter, coefficients from file * * @param signal pointer to the samples * @param filename name of the filter coefficient file * @param n length of the filter */ void FIR_filter_file(gsl_vector *signal, char *filename, int n) { int i,j; double sum; gsl_vector *temp = gsl_vector_alloc(signal->size); gsl_vector *coeffs = gsl_vector_alloc(n); FILE *COEFFS; /* Open file */ COEFFS = fopen(filename, "r"); if(COEFFS == NULL) { printf("\nError: Can't open file \"%s\".\n",filename); } /* Read coefficients */ gsl_vector_fscanf(COEFFS,coeffs); fclose(COEFFS); /* Filter signal */ for(i=0; i<signal->size; i++) { sum = 0; for(j=0; j<=GSL_MIN(i, n-1); j++) { sum += gsl_vector_get(signal, i-j)*gsl_vector_get(coeffs,j); } gsl_vector_set(temp, i, sum); } /* Copy "temp" samples to "signal" */ for(i=0; i<signal->size; i++) { gsl_vector_set(signal, i, gsl_vector_get(temp, i)); } /* Free memory */ gsl_vector_free(temp); gsl_vector_free(coeffs); } /** * Function lsf_vector2poly * * Convert LSF vector to polynomial * * @param lsf_vector * @param poly * @param index * @param HMM switch for HMM */ void lsf_vector2poly(gsl_vector *lsf_vector, gsl_vector *poly) { int i,l = lsf_vector->size; gsl_vector *fi_p = NULL, *fi_q = NULL; /* Create fi_p and fi_q */ if(l%2 == 0) { fi_p = gsl_vector_alloc(l/2); fi_q = gsl_vector_alloc(l/2); for(i=0;i<l;i=i+2) { gsl_vector_set(fi_p,i/2,gsl_vector_get(lsf_vector,i)); } for(i=1;i<l;i=i+2) { gsl_vector_set(fi_q,(i-1)/2,gsl_vector_get(lsf_vector,i)); } } else { fi_p = gsl_vector_alloc((l+1)/2); for(i=0;i<l;i=i+2) { gsl_vector_set(fi_p,i/2,gsl_vector_get(lsf_vector,i)); } if((l-1)/2 > 0) { fi_q = gsl_vector_alloc((l-1)/2); for(i=1;i<l-1;i=i+2) { gsl_vector_set(fi_q,(i-1)/2,gsl_vector_get(lsf_vector,i)); } } } /* Construct vectors P and Q */ gsl_vector *cp = gsl_vector_calloc(3); gsl_vector *cq = gsl_vector_calloc(3); gsl_vector_add_constant(cp,1); gsl_vector_add_constant(cq,1); gsl_vector *P = gsl_vector_alloc(1); gsl_vector *Q = gsl_vector_alloc(1); gsl_vector_set(P,0,1); gsl_vector_set(Q,0,1); for(i=0;i<fi_p->size;i++) { gsl_vector_set(cp,1,-2*cos(gsl_vector_get(fi_p,i))); P = Conv(P,cp); } if((l-1)/2 > 0) { for(i=0;i<fi_q->size;i++) { gsl_vector_set(cq,1,-2*cos(gsl_vector_get(fi_q,i))); Q = Conv(Q,cq); } } /* Add trivial zeros */ if(l%2 == 0) { gsl_vector *conv = gsl_vector_calloc(2); gsl_vector_add_constant(conv,1); P = Conv(P,conv); gsl_vector_set(conv,0,-1); Q = Conv(Q,conv); gsl_vector_free(conv); } else { gsl_vector *conv = gsl_vector_calloc(3); gsl_vector_set(conv,0,-1); gsl_vector_set(conv,2,1); Q = Conv(Q,conv); gsl_vector_free(conv); } /* Construct polynomial */ for(i=1;i<P->size;i++) { gsl_vector_set(poly,P->size-i-1,0.5*(gsl_vector_get(P,i)+gsl_vector_get(Q,i))); } /* Free memory */ gsl_vector_free(fi_p); if((l-1)/2 > 0) gsl_vector_free(fi_q); gsl_vector_free(cp); gsl_vector_free(cq); gsl_vector_free(P); gsl_vector_free(Q); } // TEST void Estimate_ERB_gain(gsl_vector *frame, gsl_matrix *erb_gain, int index, int FS) { /* Variables */ int i,j,erb_channels = erb_gain->size2; double data[FFT_LENGTH_LONG] = {0}; gsl_vector *fft = gsl_vector_calloc(FFT_LENGTH_LONG/2); gsl_vector *erb_inds = gsl_vector_alloc(FFT_LENGTH_LONG/2); gsl_vector *gain_erb = gsl_vector_calloc(erb_channels); gsl_vector *erb_index_sum = gsl_vector_calloc(erb_channels); /* FFT (with windowing) */ for (i=0; i<frame->size; i++) data[i] = gsl_vector_get(frame, i)*HANN(i,frame->size); gsl_fft_real_radix2_transform(data, 1, FFT_LENGTH_LONG); for(i=1; i<FFT_LENGTH_LONG/2; i++) { gsl_vector_set(fft, i, 20*log10(sqrt(pow(data[i], 2) + pow(data[FFT_LENGTH_LONG-i], 2)))); } gsl_vector_set(fft, 0, 20*log10(fabs(data[0]))); /* Evaluate ERB scale indices */ for(i=0;i<fft->size;i++) gsl_vector_set(erb_inds,i,log10(0.00437*(i/(fft->size-1.0)*(FS/2.0))+1.0)/log10(0.00437*(FS/2.0)+1.0)*(erb_channels-SMALL_NUMBER)); /* Evaluate gain values according to ERB rate */ for(i=0;i<fft->size;i++) { j = floor(gsl_vector_get(erb_inds,i)); gsl_vector_set(gain_erb,j,gsl_vector_get(gain_erb,j)+gsl_vector_get(fft,i)); gsl_vector_set(erb_index_sum,j,gsl_vector_get(erb_index_sum,j)+1); } /* Average values */ for(i=0;i<erb_channels;i++) gsl_vector_set(gain_erb,i,gsl_vector_get(gain_erb,i)/gsl_vector_get(erb_index_sum,i)); /* Set values to matrix */ for(i=0;i<erb_channels;i++) gsl_matrix_set(erb_gain,index,i,gsl_vector_get(gain_erb,i)); /* Free memory */ gsl_vector_free(fft); gsl_vector_free(erb_inds); gsl_vector_free(erb_index_sum); gsl_vector_free(gain_erb); } /*********************************************************************/ /* TEST FUNCTIONS */ /*********************************************************************/ // TEST FUNCTION // PRINT VECTOR TO FILE: p1.dat void VPrint1(gsl_vector *vector) { FILE *f = fopen("p1.dat", "w"); gsl_vector_fprintf(f, vector, "%.30f"); fclose(f); } // TEST FUNCTION // PRINT VECTOR TO FILE: p2.dat void VPrint2(gsl_vector *vector) { FILE *f = fopen("p2.dat", "w"); gsl_vector_fprintf(f, vector, "%.30f"); fclose(f); } // TEST FUNCTION // PRINT VECTOR TO FILE: p3.dat void VPrint3(gsl_vector *vector) { FILE *f = fopen("p3.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT VECTOR TO FILE: p4.dat void VPrint4(gsl_vector *vector) { FILE *f = fopen("p4.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT VECTOR TO FILE: p5.dat void VPrint5(gsl_vector *vector) { FILE *f = fopen("p5.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT VECTOR TO FILE: p6.dat void VPrint6(gsl_vector *vector) { FILE *f = fopen("p6.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT VECTOR TO FILE: p7.dat void VPrint7(gsl_vector *vector) { FILE *f = fopen("p7.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT VECTOR TO FILE: p8.dat void VPrint8(gsl_vector *vector) { FILE *f = fopen("p8.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT VECTOR TO FILE: p9.dat void VPrint9(gsl_vector *vector) { FILE *f = fopen("p9.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT VECTOR TO FILE: p10.dat void VPrint10(gsl_vector *vector) { FILE *f = fopen("p10.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT MATRIX TO FILE: p3.dat void MPrint1(gsl_matrix *matrix) { FILE *f = fopen("m1.dat", "w"); gsl_matrix_fprintf(f, matrix, "%.30f"); fclose(f); } // TEST FUNCTION // PRINT MATRIX TO FILE: p4.dat void MPrint2(gsl_matrix *matrix) { FILE *f = fopen("m2.dat", "w"); gsl_matrix_fprintf(f, matrix, "%.30f"); fclose(f); } // TEST FUNCTION // PRINT MATRIX TO FILE: m3.dat void MPrint3(gsl_matrix *matrix) { FILE *f = fopen("m3.dat", "w"); gsl_matrix_fprintf(f, matrix, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT MATRIX TO FILE: m4.dat void MPrint4(gsl_matrix *matrix) { FILE *f = fopen("m4.dat", "w"); gsl_matrix_fprintf(f, matrix, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT ARRAY TO FILE: a1.dat void APrint1(double *array, int size) { int i; gsl_vector *vector = gsl_vector_alloc(size); for(i=0;i<size;i++) gsl_vector_set(vector,i,array[i]); FILE *f = fopen("a1.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); gsl_vector_free(vector); } // TEST FUNCTION // PRINT ARRAY TO FILE: a2.dat void APrint2(double *array, int size) { int i; gsl_vector *vector = gsl_vector_alloc(size); for(i=0;i<size;i++) gsl_vector_set(vector,i,array[i]); FILE *f = fopen("a2.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); gsl_vector_free(vector); } // TEST FUNCTION // PRINT ARRAY TO FILE: a3.dat void APrint3(double *array, int size) { int i; gsl_vector *vector = gsl_vector_alloc(size); for(i=0;i<size;i++) gsl_vector_set(vector,i,array[i]); FILE *f = fopen("a3.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); gsl_vector_free(vector); } // TEST FUNCTION // PRINT ARRAY TO FILE: a4.dat void APrint4(double *array, int size) { int i; gsl_vector *vector = gsl_vector_alloc(size); for(i=0;i<size;i++) gsl_vector_set(vector,i,array[i]); FILE *f = fopen("a4.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); gsl_vector_free(vector); } // TEST FUNCTION // PAUSE void pause(int print) { if(print == 1) printf("\n\nPAUSED - PRESS ENTER TO CONTINUE\n"); getchar(); } // TEST FUNCTION // TEST FOR NANS AND INFS (MATRIX) int Find_matrix_NaN_Inf(gsl_matrix *m) { int i,j,err = 0; for(i=0;i<m->size1;i++) { for(j=0;j<m->size2;j++) { if(isnan(gsl_matrix_get(m,i,j)) == 1) { printf("Warning: NaN value found!\n"); err = 1; } if(isinf(gsl_matrix_get(m,i,j)) == 1) { printf("Warning: Inf value found!\n"); err = 1; } } } return err; } // TEST FUNCTION // TEST FOR NANS AND INFS (VECTOR) int Find_vector_NaN_Inf(gsl_vector *v) { int i,err = 0; for(i=0;i<v->size;i++) { if(isnan(gsl_vector_get(v,i)) == 1) { printf("Warning: NaN value found!\n"); err = 1; } if(isinf(gsl_vector_get(v,i)) == 1) { printf("Warning: Inf value found!\n"); err = 1; } } return err; }
{ "alphanum_fraction": 0.6865914841, "avg_line_length": 29.7251097578, "ext": "c", "hexsha": "9f02c6a6e712d93891aced781f6e15d44ceedc76", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2022-03-28T09:17:33.000Z", "max_forks_repo_forks_event_min_datetime": "2016-08-03T12:08:32.000Z", "max_forks_repo_head_hexsha": "4dfe5eb0b6dacc227299acc29c6df8b030de82b8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mjansche/GlottHMM", "max_forks_repo_path": "src/AnalysisFunctions.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "4dfe5eb0b6dacc227299acc29c6df8b030de82b8", "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": "mjansche/GlottHMM", "max_issues_repo_path": "src/AnalysisFunctions.c", "max_line_length": 227, "max_stars_count": 10, "max_stars_repo_head_hexsha": "4dfe5eb0b6dacc227299acc29c6df8b030de82b8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mjansche/GlottHMM", "max_stars_repo_path": "src/AnalysisFunctions.c", "max_stars_repo_stars_event_max_datetime": "2020-09-03T12:46:50.000Z", "max_stars_repo_stars_event_min_datetime": "2016-06-29T22:08:09.000Z", "num_tokens": 66091, "size": 209889 }
// // syrk.h // Linear Algebra Template Library // // Created by Rodney James on 1/4/12. // Copyright (c) 2012 University of Colorado Denver. All rights reserved. // #ifndef _syrk_h #define _syrk_h /// @file syrk.h Performs matrix-matrix multiplication operations resulting in symmetric matrices. #include <cctype> #include "latl.h" namespace LATL { /// @brief Performs multiplcation of a real matrix with its transpose. /// /// For real matrix A, real symmetric matrix C, and real scalars alpha and beta /// /// C := alpha*A*A'+beta*C or C := alpha*A'*A+beta*C /// is computed. /// @return 0 if success. /// @return -i if the ith argument is invalid. /// @tparam real_t Floating point type. /// @param uplo Specifies whether the upper or lower triangular part of the symmetric matrix C /// is to be referenced: /// /// if uplo = 'U' or 'u' then C is upper triangular, /// if uplo = 'L' or 'l' then C is lower triangular. /// @param trans Specifies the operation to be perfomed as follows: /// /// if trans = 'N' or 'n' then C := alpha*A*A'+beta*C /// if trans = 'T' or 't' then C := alpha*A'*A+beta*C /// if trans = 'C' or 'c' then C := alpha*A'*A+beta*C /// @param n Specifies the order of the symmetric matrix C. n>=0 /// @param k Specifies the other dimension of the real matrix A (see below). k>=0 /// @param alpha Real scalar. /// @param A Pointer to real matrix. /// /// if trans = 'N' or 'n' then A is n-by-k /// if trans = 'T' or 't' then A is k-by-n /// if trans = 'C' or 'c' then A is k-by-n /// @param ldA Column length of the matrix A. If trans = 'N' or 'n' ldA>=n, otherwise ldA>=k. /// @param beta Real scalar. /// @param C Pointer to real symmetric n-by-n matrix C. /// Only the upper or lower triangular part of C is referenced, depending on the value of uplo above. /// @param ldC Column length of the matrix C. ldC>=n /// @ingroup BLAS template <typename real_t> int SYRK(char uplo, char trans, int_t n, int_t k, real_t alpha, real_t *A, int_t ldA, real_t beta, real_t *C, int_t ldC) { using std::toupper; const real_t zero(0.0); const real_t one(1.0); int_t i,j,l; real_t *a,*c,*at; real_t t; uplo=toupper(uplo); trans=toupper(trans); if((uplo!='U')&&(uplo!='L')) return -1; else if((trans!='N')&&(trans!='T')&&(trans!='C')) return -2; else if(n<0) return -3; else if(k<0) return -4; else if(ldA<((trans=='N')?n:k)) return -7; else if(ldC<n) return -10; else if((n==0)||(((alpha==zero)||(k==0))&&(beta==one))) return 0; if(alpha==zero) { if(uplo=='U') { c=C; for(j=0;j<n;j++) { for(i=0;i<=j;i++) c[i]*=beta; c+=ldC; } } else { c=C; for(j=0;j<n;j++) { for(i=j;i<n;i++) c[i]*=beta; c+=ldC; } } } else if(trans=='N') { if(uplo=='U') { c=C; for(j=0;j<n;j++) { for(i=0;i<=j;i++) c[i]*=beta; a=A; for(l=0;l<k;l++) { t=alpha*a[j]; for(i=0;i<=j;i++) c[i]+=t*a[i]; a+=ldA; } c+=ldC; } } else { c=C; for(j=0;j<n;j++) { for(i=j;i<n;i++) c[i]*=beta; a=A; for(l=0;l<k;l++) { t=alpha*a[j]; for(i=j;i<n;i++) c[i]+=t*a[i]; a+=ldA; } c+=ldC; } } } else { if(uplo=='U') { c=C; at=A; for(j=0;j<n;j++) { a=A; for(i=0;i<=j;i++) { t=zero; for(l=0;l<k;l++) t+=a[l]*at[l]; c[i]=alpha*t+beta*c[i]; a+=ldA; } at+=ldA; c+=ldC; } } else { at=A; c=C; for(j=0;j<n;j++) { a=A+j*ldA; for(i=j;i<n;i++) { t=zero; for(l=0;l<k;l++) t+=a[l]*at[l]; c[i]=alpha*t+beta*c[i]; a+=ldA; } at+=ldA; c+=ldC; } } } return 0; } /// @brief Performs multiplcation of a complex matrix with its transpose. /// /// For complex matrix A, complex symmetric matrix C, and complex scalars alpha and beta /// /// C := alpha*A*A.'+beta*C or C := alpha*A.'*A+beta*C /// is computed. /// @return 0 if success. /// @return -i if the ith argument is invalid. /// @tparam real_t Floating point type. /// @param uplo Specifies whether the upper or lower triangular part of the symmetric matrix C /// is to be referenced: /// /// if uplo = 'U' or 'u' then C is upper triangular, /// if uplo = 'L' or 'l' then C is lower triangular. /// @param trans Specifies the operation to be perfomed as follows: /// /// if trans = 'N' or 'n' then C := alpha*A*A.'+beta*C /// if trans = 'T' or 't' then C := alpha*A.'*A+beta*C /// @param n Specifies the order of the complex symmetric matrix C. n>=0 /// @param k Specifies the other dimension of the complex matrix A (see below). k>=0 /// @param alpha Complex scalar. /// @param A Pointer to complex matrix. /// /// if trans = 'N' or 'n' then A is n-by-k /// if trans = 'T' or 't' then A is k-by-n /// @param ldA Column length of the matrix A. If trans = 'N' or 'n' ldA>=n, otherwise ldA>=k. /// @param beta Complex scalar. /// @param C Pointer to complex symmetric n-by-n matrix C. /// Only the upper or lower triangular part of C is referenced, depending on the value of uplo above. /// @param ldC Column length of the matrix C. ldC>=n /// @ingroup BLAS template <typename real_t> int SYRK(char uplo, char trans, int_t n, int_t k, complex<real_t> alpha, complex<real_t> *A, int_t ldA, complex<real_t> beta, complex<real_t> *C, int_t ldC) { using std::toupper; const complex<real_t> zero(0.0,0.0); const complex<real_t> one(1.0,0.0); int_t i,j,l; complex<real_t> *a,*c,*at; complex<real_t> t; uplo=toupper(uplo); trans=toupper(trans); if((uplo!='U')&&(uplo!='L')) return -1; else if((trans!='N')&&(trans!='T')) return -2; else if(n<0) return -3; else if(k<0) return -4; else if(ldA<((trans=='N')?n:k)) return -7; else if(ldC<n) return -10; else if((n==0)||(((alpha==zero)||(k==0))&&(beta==one))) return 0; if(alpha==zero) { if(uplo=='U') { c=C; for(j=0;j<n;j++) { for(i=0;i<=j;i++) c[i]*=beta; c+=ldC; } } else { c=C; for(j=0;j<n;j++) { for(i=j;i<n;i++) c[i]*=beta; c+=ldC; } } } else if(trans=='N') { if(uplo=='U') { c=C; for(j=0;j<n;j++) { for(i=0;i<=j;i++) c[i]*=beta; a=A; for(l=0;l<k;l++) { t=alpha*a[j]; for(i=0;i<=j;i++) c[i]+=t*a[i]; a+=ldA; } c+=ldC; } } else { c=C; for(j=0;j<n;j++) { for(i=j;i<n;i++) c[i]*=beta; a=A; for(l=0;l<k;l++) { t=alpha*a[j]; for(i=j;i<n;i++) c[i]+=t*a[i]; a+=ldA; } c+=ldC; } } } else { if(uplo=='U') { c=C; at=A; for(j=0;j<n;j++) { a=A; for(i=0;i<=j;i++) { t=zero; for(l=0;l<k;l++) t+=a[l]*at[l]; c[i]=alpha*t+beta*c[i]; a+=ldA; } at+=ldA; c+=ldC; } } else { at=A; c=C; for(j=0;j<n;j++) { a=A+j*ldA; for(i=j;i<n;i++) { t=zero; for(l=0;l<k;l++) t+=a[l]*at[l]; c[i]=alpha*t+beta*c[i]; a+=ldA; } at+=ldA; c+=ldC; } } } return 0; } #ifdef __latl_cblas #include <cblas.h> template <> int SYRK<float>(char uplo, char trans, int_t n, int_t k, float alpha, float *A, int_t ldA, float beta, float *C, int_t ldC) { using std::toupper; uplo=toupper(uplo); trans=toupper(trans); if((uplo!='U')&&(uplo!='L')) return -1; else if((trans!='N')&&(trans!='T')&&(trans!='C')) return -2; else if(n<0) return -3; else if(k<0) return -4; else if(ldA<((trans=='N')?n:k)) return -7; else if(ldC<n) return -10; const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower; const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans); cblas_ssyrk(CblasColMajor,Uplo,Trans,n,k,alpha,A,ldA,beta,C,ldC); return 0; } template <> int SYRK<double>(char uplo, char trans, int_t n, int_t k, double alpha, double *A, int_t ldA, double beta, double *C, int_t ldC) { using std::toupper; uplo=toupper(uplo); trans=toupper(trans); if((uplo!='U')&&(uplo!='L')) return -1; else if((trans!='N')&&(trans!='T')&&(trans!='C')) return -2; else if(n<0) return -3; else if(k<0) return -4; else if(ldA<((trans=='N')?n:k)) return -7; else if(ldC<n) return -10; const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower; const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans); cblas_dsyrk(CblasColMajor,Uplo,Trans,n,k,alpha,A,ldA,beta,C,ldC); return 0; } template <> int SYRK<float>(char uplo, char trans, int_t n, int_t k, complex<float> alpha, complex<float> *A, int_t ldA, complex<float> beta, complex<float> *C, int_t ldC) { using std::toupper; uplo=toupper(uplo); trans=toupper(trans); if((uplo!='U')&&(uplo!='L')) return -1; else if((trans!='N')&&(trans!='T')) return -2; else if(n<0) return -3; else if(k<0) return -4; else if(ldA<((trans=='N')?n:k)) return -7; else if(ldC<n) return -10; const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower; const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans); cblas_csyrk(CblasColMajor,Uplo,Trans,n,k,&alpha,A,ldA,&beta,C,ldC); return 0; } template <> int SYRK<double>(char uplo, char trans, int_t n, int_t k, complex<double> alpha, complex<double> *A, int_t ldA, complex<double> beta, complex<double> *C, int_t ldC) { using std::toupper; uplo=toupper(uplo); trans=toupper(trans); if((uplo!='U')&&(uplo!='L')) return -1; else if((trans!='N')&&(trans!='T')) return -2; else if(n<0) return -3; else if(k<0) return -4; else if(ldA<((trans=='N')?n:k)) return -7; else if(ldC<n) return -10; const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower; const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans); cblas_zsyrk(CblasColMajor,Uplo,Trans,n,k,&alpha,A,ldA,&beta,C,ldC); return 0; } #endif } #endif
{ "alphanum_fraction": 0.4325299355, "avg_line_length": 27.5433403805, "ext": "h", "hexsha": "986fdec88457ddb5b5cc23d42c65a67305ddafd5", "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/syrk.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/syrk.h", "max_line_length": 179, "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/syrk.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": 3666, "size": 13028 }
/** * @file convolution.h * @brief Block convolution realization of an LTI system with the FFT.Time delay estimation * @author John McDonough */ #ifndef CONVOLUTION_H #define CONVOLUTION_H #include <stdio.h> #include <assert.h> #include <gsl/gsl_block.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include "common/jexception.h" #include "stream/stream.h" #include "feature/feature.h" // ----- definition for class `OverlapAdd' ----- // class OverlapAdd : public VectorFloatFeatureStream { public: OverlapAdd(VectorFloatFeatureStreamPtr& samp, const gsl_vector* impulseResponse = NULL, unsigned fftLen = 0, const String& nm = "OverlapAdd"); ~OverlapAdd(); virtual const gsl_vector_float* next(int frame_no = -5); virtual void reset(); private: void set_impulse_response_(const gsl_vector* impulseResponse); unsigned check_fftLen_(unsigned sectionLen, unsigned irLen, unsigned fftLen); const VectorFloatFeatureStreamPtr samp_; const unsigned L_; const unsigned P_; const unsigned N_; const unsigned N2_; double* section_; gsl_vector_complex* frequencyResponse_; gsl_vector_float* buffer_; }; typedef Inherit<OverlapAdd, VectorFloatFeatureStreamPtr> OverlapAddPtr; // ----- definition for class `OverlapSave' ----- // class OverlapSave : public VectorFloatFeatureStream { public: OverlapSave(VectorFloatFeatureStreamPtr& samp, const gsl_vector* impulseResponse = NULL, const String& nm = "OverlapSave"); ~OverlapSave(); virtual const gsl_vector_float* next(int frame_no = -5); virtual void reset(); void update(const gsl_vector_complex* delta); private: void set_impulse_response_(const gsl_vector* impulseResponse); unsigned check_output_size_(unsigned irLen, unsigned sampLen); unsigned check_L_(unsigned irLen, unsigned sampLen); const VectorFloatFeatureStreamPtr samp_; const unsigned L_; const unsigned L2_; const unsigned P_; double* section_; gsl_vector_complex* frequencyResponse_; }; typedef Inherit<OverlapSave, VectorFloatFeatureStreamPtr> OverlapSavePtr; #endif // CONVOLUTION_H
{ "alphanum_fraction": 0.731522707, "avg_line_length": 25.816091954, "ext": "h", "hexsha": "79692c8e7fa40adeb60fe86db9f058d21fcd4ac9", "lang": "C", "max_forks_count": 68, "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z", "max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z", "max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "musiclvme/distant_speech_recognition", "max_forks_repo_path": "btk20_src/convolution/convolution.h", "max_issues_count": 25, "max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z", "max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "musiclvme/distant_speech_recognition", "max_issues_repo_path": "btk20_src/convolution/convolution.h", "max_line_length": 91, "max_stars_count": 136, "max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "musiclvme/distant_speech_recognition", "max_stars_repo_path": "btk20_src/convolution/convolution.h", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z", "num_tokens": 529, "size": 2246 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_spline.h> int main(void) { size_t i; const size_t N = 9; /* this dataset is taken from * J. M. Hyman, Accurate Monotonicity preserving cubic interpolation, * SIAM J. Sci. Stat. Comput. 4, 4, 1983. */ const double x[] = { 7.99, 8.09, 8.19, 8.7, 9.2, 10.0, 12.0, 15.0, 20.0 }; const double y[] = { 0.0, 2.76429e-5, 4.37498e-2, 0.169183, 0.469428, 0.943740, 0.998636, 0.999919, 0.999994 }; gsl_interp_accel *acc = gsl_interp_accel_alloc(); gsl_spline *spline_cubic = gsl_spline_alloc(gsl_interp_cspline, N); gsl_spline *spline_akima = gsl_spline_alloc(gsl_interp_akima, N); gsl_spline *spline_steffen = gsl_spline_alloc(gsl_interp_steffen, N); gsl_spline_init(spline_cubic, x, y, N); gsl_spline_init(spline_akima, x, y, N); gsl_spline_init(spline_steffen, x, y, N); for (i = 0; i < N; ++i) printf("%g %g\n", x[i], y[i]); printf("\n\n"); for (i = 0; i <= 100; ++i) { double xi = (1 - i / 100.0) * x[0] + (i / 100.0) * x[N-1]; double yi_cubic = gsl_spline_eval(spline_cubic, xi, acc); double yi_akima = gsl_spline_eval(spline_akima, xi, acc); double yi_steffen = gsl_spline_eval(spline_steffen, xi, acc); printf("%g %g %g %g\n", xi, yi_cubic, yi_akima, yi_steffen); } gsl_spline_free(spline_cubic); gsl_spline_free(spline_akima); gsl_spline_free(spline_steffen); gsl_interp_accel_free(acc); return 0; }
{ "alphanum_fraction": 0.6266751755, "avg_line_length": 29.0185185185, "ext": "c", "hexsha": "2049df48ed454064e0e24d1db6f62e81c59098f6", "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/doc/examples/interp_compare.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/doc/examples/interp_compare.c", "max_line_length": 71, "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/doc/examples/interp_compare.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": 573, "size": 1567 }
#ifndef FUNCTIONS_H #define FUNCTIONS_H #include <vector> #include <string> #include <fstream> #include <gsl/gsl_matrix.h> #include "structures.h" double rad2deg(double rad); double deg2rad(double deg); double vect_len(const vect &v); void norm(vect &vr); double double_dot_prod(const gsl_matrix* m1, const gsl_matrix* m2); double calc_evM(const gsl_matrix* def); double calc_internal_energy(const gsl_matrix* shear, const slip_system_matrix *smatrix, grain *g); double calc_energy(const gsl_matrix* slpsysmat, const gsl_matrix* def_l, const slip_system_matrix *smatrix, grain *g, bool falg=false); void cleanup_energy(); double update_rot_matrix(const std::vector<int>& comb, const gsl_matrix* shaermin, const std::vector<slip_system*>& systems, const gsl_matrix* uk1, const gsl_matrix* uk2, gsl_matrix* rmat, int def_step); gsl_matrix* get_rot_matrix(const grain *g, bool free_m=false); grain* grain_from_rot_matrix(gsl_matrix *rot_mat); void print_matrix(const gsl_matrix *m); void load_settings(double *max_def, double *def_step, gsl_matrix *deformation, gsl_matrix *k1, gsl_matrix *k2, const std::string &settings_file_name); void load_grains(std::vector<grain*> &grains, const std::string &grains_file_name); void load_slip_systems(std::vector<slip_system*> &slip_systems, const std::string &slip_system_file, int max_def); std::vector<grain*>* prepare_rot_matrices(const std::string &grains_file_name); void fill_grain_crss(std::vector<grain*> *grains, const std::vector<slip_system*> &slip_systems); void prepare_slip_systems_matrices(std::vector<slip_system_matrix*> &matrices, std::vector<slip_system*> &slip_systems); void convert2U(const gsl_matrix* mat, gsl_matrix* umat); void calc_handler(handler &h, const gsl_matrix *def, const gsl_matrix *rm); void get_uhandler(U_handler &uh, const handler &h, int s=2); void write_grains(const std::vector<grain*> &grinas, std::ofstream &file, const std::string &delimiter); void export_grains_to_file(const std::vector<grain*> &grains, const std::string &export_file, const std::string &delimiter); void export_taylor_factor_to_file(const std::vector<double> &total_tf, const std::string& filename); void write_slip_system_activity(const std::vector<slip_system*> &slip_systems, std::ofstream &export_file, int grains_num, double eVM); void export_slip_system_activity_to_file(const std::vector<slip_system*> &slip_systems, const std::string& filename, int grains_num, double eVM); void free_grains(std::vector<grain*> &grains); void free_slip_systems(std::vector<slip_system*> &slip_systems); void free_rotation_matrices(std::vector<gsl_matrix*> rot_matrices); void free_slip_systems_matrices(std::vector<slip_system_matrix*> &matrices); #endif //FUNCTIONS_H
{ "alphanum_fraction": 0.7889740781, "avg_line_length": 42.1384615385, "ext": "h", "hexsha": "760bae72e9933bf50dca1e5cb83ba90deff12f6c", "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": "c613ccb2603f0f89ee4c177047e16fa2eaf4ddd9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "bainit/hextexsim", "max_forks_repo_path": "src/includes/functions.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c613ccb2603f0f89ee4c177047e16fa2eaf4ddd9", "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": "bainit/hextexsim", "max_issues_repo_path": "src/includes/functions.h", "max_line_length": 203, "max_stars_count": 2, "max_stars_repo_head_hexsha": "c613ccb2603f0f89ee4c177047e16fa2eaf4ddd9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "bainit/hextexsim", "max_stars_repo_path": "src/includes/functions.h", "max_stars_repo_stars_event_max_datetime": "2018-03-20T14:07:43.000Z", "max_stars_repo_stars_event_min_datetime": "2018-01-24T13:21:03.000Z", "num_tokens": 723, "size": 2739 }
/* AUTORIGHTS Copyright (C) 2007 Princeton University This file is part of Ferret Toolkit. Ferret Toolkit 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, 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 <math.h> #ifdef _OPENMP #include <omp.h> #endif #include <gsl/gsl_cdf.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_multiroots.h> #include <cass.h> #include "LSH.h" #include "local.h" #define ERR 1e-4 struct local_params { double a; double b; double W; int M; int L; int K; }; static inline double p_col_helper (double x) { double result; result = 2.0*gsl_cdf_ugaussian_P(x) - 1.0; result += sqrt(2.0/M_PI) * (exp(-x*x/2.0)-1.0)/x; return result; } static inline double p_col (double x, double W, int M, int L) { return 1.0 - pow(1.0 - pow(p_col_helper(W/x), M), L); } static int fun (const gsl_vector *x, void *params, gsl_vector *f) { double W = ((struct local_params *)params)->W; int M = ((struct local_params *)params)->M; int L = ((struct local_params *)params)->L; int K = ((struct local_params *)params)->K; double fa = ((struct local_params *)params)->a; double fb = ((struct local_params *)params)->b; double sxx, sxy, sx, sy, k, d; double a, b; int n; double alpha = gsl_vector_get(x, 0); double beta = gsl_vector_get(x, 1); sxx = sxy = sx = sy = 0; n = 0; k = 0; while ((k < K) && (n < 1000)) { double lk, ld; n++; d = alpha * pow(n, beta); k += p_col(sqrt(d), W, M, L); lk = log(k); ld = log(d); sx += lk; sy += ld; sxx += lk * lk; sxy += lk * ld; } least_squares(&a, &b, n, sxx, sxy, sx, sy); a = exp(a); gsl_vector_set(f, 0, a - fa); gsl_vector_set(f, 1, b - fb); return GSL_SUCCESS; } int print_state (size_t iter, gsl_multiroot_fsolver *s) { fprintf(stderr, "iter = %3zu x = %.3f %.3f " "f(x) = %.3e %.3e\n", iter, gsl_vector_get(s->x, 0), gsl_vector_get(s->x, 1), gsl_vector_get(s->f, 0), gsl_vector_get(s->f, 1)); return 0; } int localdim (double a, double b, double *alpha, double *beta, double W, int M, int L, int K) { const gsl_multiroot_fsolver_type *T = NULL; gsl_multiroot_fsolver *s = NULL; int status; size_t iter = 0; struct local_params params = {.a = a, .b = b, .W = W, .M = M, .L = L, .K = K}; gsl_multiroot_function f = {&fun, 2, &params}; gsl_vector *x = gsl_vector_alloc(2); gsl_vector_set(x, 0, a); gsl_vector_set(x, 1, b); if (s == NULL) { T = gsl_multiroot_fsolver_hybrids; s = gsl_multiroot_fsolver_alloc(T, 2); } gsl_multiroot_fsolver_set(s, &f, x); do { status = gsl_multiroot_fsolver_iterate(s); // print_state(iter, s); if (status) break; status = gsl_multiroot_test_residual(s->f, ERR); iter++; } while ((status == GSL_CONTINUE) && (iter < 1000)); // fprintf(stderr, "status = %s\n", gsl_strerror(status)); *alpha = gsl_vector_get(s->x, 0); *beta = gsl_vector_get(s->x, 1); gsl_multiroot_fsolver_free(s); gsl_vector_free(x); return 0; } int LSH_est_init (LSH_est_t *est, int a_step, double a_min, double a_max, int b_step, double b_min, double b_max, double W, int M, int L, int K) { double a_delta, b_delta; int i, j; est->a_step = a_step; est->b_step = b_step; est->a_min = a_min; est->b_min = b_min; est->a_max = a_max; est->b_max = b_max; a_delta = est->a_delta = (a_max - a_min) / a_step; b_delta = est->b_delta = (b_max - b_min) / b_step; est->a_table = type_matrix_alloc(double , a_step, b_step); est->b_table = type_matrix_alloc(double , a_step, b_step); for (i = 0; i < a_step; i++) { for (j = 0; j < b_step; j++) { localdim(a_min + i * a_delta, b_min + j * b_delta, &est->a_table[i][j], &est->b_table[i][j], W, M, L, K); } } return 0; }
{ "alphanum_fraction": 0.6523171019, "avg_line_length": 22.8548387097, "ext": "c", "hexsha": "5a46af74ba18f906182acc4530b5a9996cb9af6f", "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": "68add84d77c61c26bbf180ba55c85decf7e142eb", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "wustl-pctg/PORRidge", "max_forks_repo_path": "bench/ferret/src/src/lsh/local.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "68add84d77c61c26bbf180ba55c85decf7e142eb", "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": "wustl-pctg/PORRidge", "max_issues_repo_path": "bench/ferret/src/src/lsh/local.c", "max_line_length": 93, "max_stars_count": 1, "max_stars_repo_head_hexsha": "68add84d77c61c26bbf180ba55c85decf7e142eb", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "wustl-pctg/PORRidge", "max_stars_repo_path": "bench/ferret/src/src/lsh/local.c", "max_stars_repo_stars_event_max_datetime": "2020-06-10T06:22:32.000Z", "max_stars_repo_stars_event_min_datetime": "2020-06-10T06:22:32.000Z", "num_tokens": 1407, "size": 4251 }
/* The MIT License Copyright (c) 2013-2015 Genome Research Ltd. Author: Petr Danecek <pd3@sanger.ac.uk> 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. */ #include "peakfit.h" #include <stdio.h> #include <gsl/gsl_version.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_multifit_nlin.h> #include <htslib/hts.h> #include <htslib/kstring.h> #include <assert.h> #include <math.h> #define NPARAMS 5 // gauss params: sqrt(scale), center, sigma typedef struct _peak_t { int fit_mask; double params[NPARAMS], ori_params[NPARAMS]; // current and input parameters struct { int scan; double min, max, best; } mc[NPARAMS]; // monte-carlo settings and best parameter void (*calc_f) (int nvals, double *xvals, double *yvals, void *args); void (*calc_df) (int nvals, double *xvals, double *yvals, double *dfvals, int idf, void *args); void (*print_func) (struct _peak_t *pk, kstring_t *str); void (*convert_get) (struct _peak_t *pk, double *params); double (*convert_set) (struct _peak_t *pk, int iparam, double value); } peak_t; struct _peakfit_t { int npeaks, mpeaks, nparams, mparams; peak_t *peaks; double *params; int nvals, mvals; double *xvals, *yvals, *vals; kstring_t str; int verbose, nmc_iter; }; /* Gaussian peak with the center bound in the interval <d,e>: yi = scale^2 * exp(-(xi-z)^2/sigma^2) dy/dscale = 2*scale * EXP dy/dcenter = -scale^2 * sin(center) * (e-d) * (xi - z) * EXP / sigma^2 dy/dsigma = 2*scale^2 * (xi - z)^2 * EXP / sigma^3 where z = 0.5*(cos(center)+1)*(e-d) + d EXP = exp(-(xi-z)^2/sigma^2) */ void bounded_gaussian_calc_f(int nvals, double *xvals, double *yvals, void *args) { peak_t *pk = (peak_t*) args; double scale2 = pk->params[0] * pk->params[0]; double center = pk->params[1]; double sigma = pk->params[2]; double d = pk->params[3]; double e = pk->params[4]; double z = 0.5*(cos(center)+1)*(e-d) + d; int i; for (i=0; i<nvals; i++) { double tmp = (xvals[i] - z)/sigma; yvals[i] += scale2 * exp(-tmp*tmp); } } void bounded_gaussian_calc_df(int nvals, double *xvals, double *yvals, double *dfvals, int idf, void *args) { peak_t *pk = (peak_t*) args; double scale = pk->params[0]; double center = pk->params[1]; double sigma = pk->params[2]; double d = pk->params[3]; double e = pk->params[4]; double z = 0.5*(cos(center)+1)*(e-d) + d; int i; for (i=0; i<nvals; i++) { double EXP = exp(-(xvals[i]-z)*(xvals[i]-z)/sigma/sigma); double zi = xvals[i] - z; if ( idf==0 ) // dscale dfvals[i] += 2*scale*EXP; else if ( idf==1 ) // dcenter dfvals[i] -= scale*scale*sin(center)*(e-d)*zi*EXP/sigma/sigma; else if ( idf==2 ) // dsigma dfvals[i] += 2*scale*scale*zi*zi*EXP/sigma/sigma/sigma; } } void bounded_gaussian_sprint_func(peak_t *pk, kstring_t *str) { double center = pk->params[1]; double d = pk->params[3]; double e = pk->params[4]; double z = 0.5*(cos(center)+1)*(e-d) + d; ksprintf(str,"%f**2 * exp(-(x-%f)**2/%f**2)",fabs(pk->params[0]),z,fabs(pk->params[2])); } double bounded_gaussian_convert_set(peak_t *pk, int iparam, double value) { if ( iparam!=1 ) return value; double d = pk->ori_params[3]; double e = pk->ori_params[4]; if ( value<d ) value = d; else if ( value>e ) value = e; return acos(2*(value-d)/(e-d) - 1); } void bounded_gaussian_convert_get(peak_t *pk, double *params) { params[0] = fabs(pk->params[0]); params[2] = fabs(pk->params[2]); double center = pk->params[1]; double d = pk->params[3]; double e = pk->params[4]; params[1] = 0.5*(cos(center)+1)*(e-d) + d; } void peakfit_add_bounded_gaussian(peakfit_t *pkf, double a, double b, double c, double d, double e, int fit_mask) { pkf->npeaks++; hts_expand0(peak_t,pkf->npeaks,pkf->mpeaks,pkf->peaks); int i, nfit = 0; for (i=0; i<NPARAMS; i++) if ( fit_mask & (1<<i) ) nfit++; assert( d<e ); pkf->nparams += nfit; hts_expand0(double,pkf->nparams,pkf->mparams,pkf->params); peak_t *pk = &pkf->peaks[pkf->npeaks-1]; memset(pk, 0, sizeof(peak_t)); pk->calc_f = bounded_gaussian_calc_f; pk->calc_df = bounded_gaussian_calc_df; pk->print_func = bounded_gaussian_sprint_func; pk->convert_set = bounded_gaussian_convert_set; pk->convert_get = bounded_gaussian_convert_get; pk->fit_mask = fit_mask; pk->ori_params[0] = a; pk->ori_params[2] = c; pk->ori_params[3] = d; pk->ori_params[4] = e; pk->ori_params[1] = pk->convert_set(pk, 1, b); } /* Gaussian peak: yi = scale^2 * exp(-(x-center)^2/sigma^2) dy/dscale = 2 * scale * EXP dy/dcenter = 2 * scale^2 * (x-center) * EXP / sigma^2 dy/dsigma = 2 * scale^2 * (x-center)^2 * EXP / sigma^3 where EXP = exp(-(x-center)^2/sigma^2) */ void gaussian_calc_f(int nvals, double *xvals, double *yvals, void *args) { peak_t *pk = (peak_t*) args; double scale2 = pk->params[0] * pk->params[0]; double center = pk->params[1]; double sigma = pk->params[2]; int i; for (i=0; i<nvals; i++) { double tmp = (xvals[i] - center)/sigma; yvals[i] += scale2 * exp(-tmp*tmp); } } void gaussian_calc_df(int nvals, double *xvals, double *yvals, double *dfvals, int idf, void *args) { peak_t *pk = (peak_t*) args; double scale = pk->params[0]; double center = pk->params[1]; double sigma = pk->params[2]; int i; for (i=0; i<nvals; i++) { double zi = xvals[i] - center; double EXP = exp(-zi*zi/(sigma*sigma)); if ( idf==0 ) // dscale dfvals[i] += 2*scale*EXP; else if ( idf==1 ) // dcenter dfvals[i] += 2*scale*scale*zi*EXP/(sigma*sigma); else if ( idf==2 ) // dsigma dfvals[i] += 2*scale*scale*zi*zi*EXP/(sigma*sigma*sigma); } } void gaussian_sprint_func(struct _peak_t *pk, kstring_t *str) { ksprintf(str,"%f**2 * exp(-(x-%f)**2/%f**2)",fabs(pk->params[0]),pk->params[1],fabs(pk->params[2])); } void gaussian_convert_get(peak_t *pk, double *params) { params[0] = fabs(pk->params[0]); params[1] = fabs(pk->params[1]); params[2] = fabs(pk->params[2]); } void peakfit_add_gaussian(peakfit_t *pkf, double a, double b, double c, int fit_mask) { pkf->npeaks++; hts_expand0(peak_t,pkf->npeaks,pkf->mpeaks,pkf->peaks); int i, nfit = 0; for (i=0; i<NPARAMS; i++) if ( fit_mask & (1<<i) ) nfit++; pkf->nparams += nfit; hts_expand0(double,pkf->nparams,pkf->mparams,pkf->params); peak_t *pk = &pkf->peaks[pkf->npeaks-1]; memset(pk, 0, sizeof(peak_t)); pk->calc_f = gaussian_calc_f; pk->calc_df = gaussian_calc_df; pk->print_func = gaussian_sprint_func; pk->convert_get = gaussian_convert_get; pk->fit_mask = fit_mask; pk->ori_params[0] = a; pk->ori_params[1] = b; pk->ori_params[2] = c; } /* exp peak: yi = scale^2 * exp((x-center)/sigma^2) dy/dscale = 2 * scale * EXP dy/dcenter = -scale^2 * EXP / sigma^2 dy/dsigma = -2 * scale^2 * (x-center) * EXP / sigma^3 where EXP = exp((x-center)/sigma^2) */ void exp_calc_f(int nvals, double *xvals, double *yvals, void *args) { peak_t *pk = (peak_t*) args; double scale2 = pk->params[0] * pk->params[0]; double center = pk->params[1]; double sigma = pk->params[2]; int i; for (i=0; i<nvals; i++) { yvals[i] += scale2 * exp((xvals[i]-center)/sigma/sigma); } } void exp_calc_df(int nvals, double *xvals, double *yvals, double *dfvals, int idf, void *args) { peak_t *pk = (peak_t*) args; double scale = pk->params[0]; double center = pk->params[1]; double sigma = pk->params[2]; int i; for (i=0; i<nvals; i++) { double EXP = exp((xvals[i]-center)/sigma/sigma); if ( idf==0 ) // dscale dfvals[i] += 2*scale*EXP; else if ( idf==2 ) // dsigma dfvals[i] -= 2*scale*scale*(xvals[i]-center)*EXP/sigma/sigma/sigma; } } void exp_sprint_func(struct _peak_t *pk, kstring_t *str) { ksprintf(str,"%f**2 * exp((x-%f)/%f**2)",fabs(pk->params[0]),pk->params[1],fabs(pk->params[2])); } void exp_convert_get(peak_t *pk, double *params) { params[0] = fabs(pk->params[0]); params[1] = fabs(pk->params[1]); params[2] = fabs(pk->params[2]); } void peakfit_add_exp(peakfit_t *pkf, double a, double b, double c, int fit_mask) { pkf->npeaks++; hts_expand0(peak_t,pkf->npeaks,pkf->mpeaks,pkf->peaks); int i, nfit = 0; for (i=0; i<NPARAMS; i++) if ( fit_mask & (1<<i) ) nfit++; assert( !(fit_mask&2) ); pkf->nparams += nfit; hts_expand0(double,pkf->nparams,pkf->mparams,pkf->params); peak_t *pk = &pkf->peaks[pkf->npeaks-1]; memset(pk, 0, sizeof(peak_t)); pk->calc_f = exp_calc_f; pk->calc_df = exp_calc_df; pk->print_func = exp_sprint_func; pk->convert_get = exp_convert_get; pk->fit_mask = fit_mask; pk->ori_params[0] = a; pk->ori_params[1] = b; pk->ori_params[2] = c; } void peakfit_set_params(peakfit_t *pkf, int ipk, double *params, int nparams) { peak_t *pk = &pkf->peaks[ipk]; int i; if ( pk->convert_set ) for (i=0; i<nparams; i++) pk->params[i] = pk->convert_set(pk, i, params[i]); else for (i=0; i<nparams; i++) pk->params[i] = params[i]; } void peakfit_get_params(peakfit_t *pkf, int ipk, double *params, int nparams) { peak_t *pk = &pkf->peaks[ipk]; if ( pk->convert_get ) pk->convert_get(pk, params); else { int i; for (i=0; i<nparams; i++) params[i] = pk->params[i]; } } peakfit_t *peakfit_init(void) { return (peakfit_t*)calloc(1,sizeof(peakfit_t)); } void peakfit_reset(peakfit_t *pkf) { pkf->npeaks = pkf->nparams = 0; memset(pkf->peaks,0,sizeof(peak_t)*pkf->mpeaks); } void peakfit_destroy(peakfit_t *pkf) { free(pkf->str.s); free(pkf->vals); free(pkf->params); free(pkf->peaks); free(pkf); } int peakfit_calc_f(const gsl_vector *params, void *data, gsl_vector *yvals) { peakfit_t *pkf = (peakfit_t *) data; int i,j; for (i=0; i<pkf->nvals; i++) pkf->vals[i] = 0; int iparam = 0; for (i=0; i<pkf->npeaks; i++) { peak_t *pk = &pkf->peaks[i]; for (j=0; j<NPARAMS; j++) { if ( !(pk->fit_mask & (1<<j)) ) continue; pk->params[j] = gsl_vector_get(params,iparam); iparam++; } pk->calc_f(pkf->nvals, pkf->xvals, pkf->vals, pk); } for (i=0; i<pkf->nvals; i++) gsl_vector_set(yvals, i, (pkf->vals[i] - pkf->yvals[i])/0.01); return GSL_SUCCESS; } int peakfit_calc_df(const gsl_vector *params, void *data, gsl_matrix *jacobian) { peakfit_t *pkf = (peakfit_t *) data; int i,j,k,iparam = 0; for (i=0; i<pkf->npeaks; i++) { peak_t *pk = &pkf->peaks[i]; int iparam_prev = iparam; for (j=0; j<NPARAMS; j++) { if ( !(pk->fit_mask & (1<<j)) ) continue; pk->params[j] = gsl_vector_get(params,iparam); iparam++; } iparam = iparam_prev; for (j=0; j<NPARAMS; j++) { if ( !(pk->fit_mask & (1<<j)) ) continue; for (k=0; k<pkf->nvals; k++) pkf->vals[k] = 0; pk->calc_df(pkf->nvals, pkf->xvals, pkf->yvals, pkf->vals, j, pk); for (k=0; k<pkf->nvals; k++) gsl_matrix_set(jacobian, k, iparam, pkf->vals[k]); iparam++; } } return GSL_SUCCESS; } int peakfit_calc_fdf(const gsl_vector *params, void *data, gsl_vector *yvals, gsl_matrix *jacobian) { peakfit_calc_f(params, data, yvals); peakfit_calc_df(params, data, jacobian); return GSL_SUCCESS; } double peakfit_evaluate(peakfit_t *pkf) { int i; for (i=0; i<pkf->nvals; i++) pkf->vals[i] = 0; for (i=0; i<pkf->npeaks; i++) pkf->peaks[i].calc_f(pkf->nvals, pkf->xvals, pkf->vals, &pkf->peaks[i]); double sum = 0; for (i=0; i<pkf->nvals; i++) sum += fabs(pkf->vals[i] - pkf->yvals[i]); return sum; } const char *peakfit_sprint_func(peakfit_t *pkf) { pkf->str.l = 0; int i; for (i=0; i<pkf->npeaks; i++) { if ( i>0 ) kputs(" + ", &pkf->str); pkf->peaks[i].print_func(&pkf->peaks[i], &pkf->str); } return (const char*)pkf->str.s; } void peakfit_verbose(peakfit_t *pkf, int level) { pkf->verbose = level; } void peakfit_set_mc(peakfit_t *pkf, double xmin, double xmax, int iparam, int niter) { peak_t *pk = &pkf->peaks[ pkf->npeaks-1 ]; pk->mc[iparam].scan = 1; pk->mc[iparam].min = xmin; pk->mc[iparam].max = xmax; pkf->nmc_iter = niter; } double peakfit_run(peakfit_t *pkf, int nvals, double *xvals, double *yvals) { srand(0); // for reproducibility pkf->nvals = nvals; pkf->xvals = xvals; pkf->yvals = yvals; hts_expand0(double,pkf->nvals,pkf->mvals,pkf->vals); if ( !pkf->nparams ) return peakfit_evaluate(pkf); gsl_multifit_function_fdf mfunc; mfunc.f = &peakfit_calc_f; mfunc.df = &peakfit_calc_df; mfunc.fdf = &peakfit_calc_fdf; mfunc.n = nvals; mfunc.p = pkf->nparams; mfunc.params = pkf; const gsl_multifit_fdfsolver_type *solver_type; gsl_multifit_fdfsolver *solver; solver_type = gsl_multifit_fdfsolver_lmsder; solver = gsl_multifit_fdfsolver_alloc(solver_type, nvals, mfunc.p); gsl_vector *grad = gsl_vector_alloc(pkf->nparams); int imc_iter, i,j, iparam; double best_fit = HUGE_VAL; for (imc_iter=0; imc_iter<=pkf->nmc_iter; imc_iter++) // possibly multiple monte-carlo iterations { // set GSL parameters iparam = 0; for (i=0; i<pkf->npeaks; i++) { peak_t *pk = &pkf->peaks[i]; for (j=0; j<NPARAMS; j++) { pk->params[j] = pk->ori_params[j]; if ( pk->mc[j].scan ) { pk->params[j] = rand()*(pk->mc[j].max - pk->mc[j].min)/RAND_MAX + pk->mc[j].min; if ( pk->convert_set ) pk->params[j] = pk->convert_set(pk, j, pk->params[j]); } if ( !(pk->fit_mask & (1<<j)) ) continue; pkf->params[iparam] = pk->params[j]; iparam++; } } gsl_vector_view vview = gsl_vector_view_array(pkf->params, mfunc.p); gsl_multifit_fdfsolver_set(solver, &mfunc, &vview.vector); // iterate until convergence (or lack of it) int ret, test1 = 0, test2 = 0, niter = 0, niter_max = 500; do { ret = gsl_multifit_fdfsolver_iterate(solver); if ( pkf->verbose >1 ) { fprintf(stderr, "%d: ", niter); for (i=0; i<pkf->npeaks; i++) { peak_t *pk = &pkf->peaks[i]; fprintf(stderr,"\t%f %f %f", pk->params[0],pk->params[1],pk->params[2]); } fprintf(stderr, "\t.. %s\n", gsl_strerror(ret)); } if ( ret ) break; #if GSL_MAJOR_VERSION >= 2 int info; test1 = gsl_multifit_fdfsolver_test(solver, 1e-8,1e-8, 0.0, &info); #else gsl_multifit_gradient(solver->J, solver->f, grad); test1 = gsl_multifit_test_gradient(grad, 1e-8); test2 = gsl_multifit_test_delta(solver->dx, solver->x, 1e-8, 1e-8); #endif } while ((test1==GSL_CONTINUE || test2==GSL_CONTINUE) && ++niter<niter_max); if ( pkf->verbose >1 ) { fprintf(stderr,"test1=%s\n", gsl_strerror(test1)); fprintf(stderr,"test2=%s\n", gsl_strerror(test2)); } // recover parameters iparam = 0; for (i=0; i<pkf->npeaks; i++) { peak_t *pk = &pkf->peaks[i]; for (j=0; j<NPARAMS; j++) { if ( !(pk->fit_mask & (1<<j)) ) continue; pk->params[j] = gsl_vector_get(solver->x, iparam++); } } // evaluate fit, update best parameters double fit = peakfit_evaluate(pkf); if ( fit<best_fit ) { for (i=0; i<pkf->npeaks; i++) { peak_t *pk = &pkf->peaks[i]; for (j=0; j<NPARAMS; j++) pk->mc[j].best = pk->params[j]; } } if ( fit<best_fit ) best_fit = fit; } gsl_multifit_fdfsolver_free(solver); gsl_vector_free(grad); for (i=0; i<pkf->npeaks; i++) { peak_t *pk = &pkf->peaks[i]; for (j=0; j<NPARAMS; j++) pk->params[j] = pk->mc[j].best; } return best_fit; }
{ "alphanum_fraction": 0.5720783183, "avg_line_length": 29.7508250825, "ext": "c", "hexsha": "8094b5d52b86dd675a9d8fec5542906e9ef9f28b", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2020-12-27T22:03:05.000Z", "max_forks_repo_forks_event_min_datetime": "2017-11-21T08:11:50.000Z", "max_forks_repo_head_hexsha": "7cf9740108844da30dcc506e733015fd5dd76a05", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "benranco/test", "max_forks_repo_path": "tools/bcftools/peakfit.c", "max_issues_count": 8, "max_issues_repo_head_hexsha": "7cf9740108844da30dcc506e733015fd5dd76a05", "max_issues_repo_issues_event_max_datetime": "2021-03-23T02:51:15.000Z", "max_issues_repo_issues_event_min_datetime": "2020-02-13T10:53:30.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "benranco/test", "max_issues_repo_path": "tools/bcftools/peakfit.c", "max_line_length": 113, "max_stars_count": 32, "max_stars_repo_head_hexsha": "7cf9740108844da30dcc506e733015fd5dd76a05", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "benranco/test", "max_stars_repo_path": "tools/bcftools/peakfit.c", "max_stars_repo_stars_event_max_datetime": "2022-02-06T16:14:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-05-07T21:12:49.000Z", "num_tokens": 5865, "size": 18029 }
/* Copyright (c) 2011-2012, Jérémy Fix. All rights reserved. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions are met: */ /* * Redistributions of source code must retain the above copyright notice, */ /* this list of conditions and the following disclaimer. */ /* * 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. */ /* * None of 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 AUTHOR 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. */ #ifndef UKF_TYPES_H #define UKF_TYPES_H #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_math.h> #include <gsl/gsl_linalg.h> #include "ukf_math.h" namespace ukf { /** * @short The different types of implemented process noise for UKF state estimation */ typedef enum { /** * @brief The covariance of the evolution noise is fixed to \f$\textbf{P}_{\theta\theta_i} = \alpha . \textbf{I}\f$ */ UKF_PROCESS_FIXED, /** * @brief The covariance of the evolution noise is defined as \f$\textbf{P}_{\theta\theta_i} = (\alpha^{-1} - 1)\textbf{P}_i\f$ */ UKF_PROCESS_RLS } ProcessNoise; namespace parameter { class EvolutionNoise; /** * @short Structure holding the parameters of the Unscented Kalman Filter * */ typedef struct { /** * @short \f$\kappa \geq 0\f$, \f$\kappa = 0\f$ is a good choice. According to van der Merwe, its value is not critical */ double kpa; /** * @short \f$0 \leq \alpha \leq 1\f$ : "Size" of sigma-point distribution. Should be small if the function is strongly non-linear */ double alpha; /** * @short Non negative weights used to introduce knowledge about the higher order moments of the distribution. For gaussian distributions, \f$\beta = 2\f$ is a good choice */ double beta; /** * @short \f$\lambda = \alpha^2 (n + \kappa) - n\f$ */ double lambda; /** * @short \f$\gamma = \sqrt{\lambda + n}\f$ */ double gamma; /** * @short Parameter used for the evolution noise */ //double evolution_noise_parameter; /** * @short Initial value of the evolution noise */ //double evolution_noise; /** * @short Evolution noise type */ //EvolutionNoise evolution_noise_type; EvolutionNoise * evolution_noise; /** * @short Covariance of the observation noise */ double observation_noise; /** * @short Prior estimate of the covariance matrix */ double prior_pi; /** * @short Number of parameters to estimate */ int n; /** * @short \f$nbSamples = (2 n + 1)\f$ Number of sigma-points */ int nbSamples; /** * @short Dimension of the output */ int no; } ukf_param; /** * @short Pointer to the function to approximate in the scalar case * */ //typedef double (*ukf_function_scalar) (gsl_vector * param, gsl_vector * input); /** * @short Structure holding the matrices manipulated by the statistical linearization * in the scalar case * */ typedef struct { /** * @short Kalman gain, a vector of size \f$n\f$ */ gsl_vector * Kk; /** * @short Temporary matrix for the kalman gain, a matrix of size \f$(n,1)\f$ */ gsl_matrix * Kk_mat; /** * @short Temporary matrix for the transpose of the kalman gain, a matrix of size \f$(1,n)\f$ */ gsl_matrix * Kk_mat_T; /** * @short Covariance of \f$(w, d)\f$: \f$P_{w_k d_k}\f$, of size \f$n\f$ */ gsl_vector * Pwdk; /** * @short Covariance of the evolution noise */ gsl_matrix * Prrk; /** * @short Covariance of the observation noise */ double Peek; /** * @short Covariance of the output */ double Pddk; /** * @short Parameter vector, of size \f$n\f$ */ gsl_vector * w; /** * @short Temporary vector, holding a sigma-point */ gsl_vector * wk; /** * @short Covariance matrix of the parameters, of size \f$(n,n)\f$ */ gsl_matrix * Pk; /** * @short Matrix holding the Cholesky decomposition of \f$P_k\f$, of size \f$(n,n)\f$ */ gsl_matrix * Sk; /** * @short Vector holding one column of Sk, of size \f$n\f$ */ gsl_vector * cSk; /** * @short Weights used to compute the mean of the sigma points' images * @brief \f$wm_0 = \frac{\lambda}{n + \lambda}\f$ * \f$wm_i = \frac{1}{2(n + \lambda)}\f$ */ gsl_vector * wm; /** * @short Weights used to update the covariance matrices * @brief \f$wc_0 = \frac{\lambda}{n + \lambda} + (1 - \alpha^2 + \beta)\f$ * \f$wc_i = \frac{1}{2(n + \lambda)}\f$ */ gsl_vector * wc; /** * @short Temporary vector holding the image of the sigma points, of size \f$nbSamples\f$ */ gsl_vector * dk; /** * @short Innovation */ double ino_dk; /** * @short Variable holding the mean of the sigma points image */ double d_mean; /** * @short Matrix holding the sigma points in the columns, of size \f$(n,nbSamples)\f$ */ gsl_matrix * sigmaPoints; /** * @short Temporary vector */ gsl_vector * temp_n; /** * @short Temporary matrix */ gsl_matrix * temp_n_n; } ukf_scalar_state; /** * @short Structure holding the matrices manipulated by the unscented kalman filter * in the vectorial case, for Parameter estimation * */ typedef struct { /** * @short Kalman gain, a matrix of size \f$n \times no\f$ */ gsl_matrix * Kk; /** * @short The tranposed Kalman gain, a vector of size \f$no \times n\f$ */ gsl_matrix * Kk_T; /** * @short Covariance of \f$(w, d)\f$: \f$P_{w_k d_k}\f$, of size \f$n \times no\f$ */ gsl_matrix * Pwdk; /** * @short Covariance of the output, a matrix of size \f$ no \times no \f$ */ gsl_matrix * Pddk; /** * @short Covariance of the observation noise, of size \f$ no \times no \f$ */ gsl_matrix * Peek; /** * @short Covariance of the evolution noise, of size \f$ n \times n \f$ */ gsl_matrix * Prrk; /** * @short Parameter vector, of size \f$n\f$ */ gsl_vector * w; /** * @short Temporary vector holding one sigma point, of size \f$n\f$ */ gsl_vector * wk; /** * @short Covariance matrix of the parameters, of size \f$(n,n)\f$ */ gsl_matrix * Pk; /** * @short Matrix holding the Cholesky decomposition of \f$P_k\f$, of size \f$(n,n)\f$ */ gsl_matrix * Sk; /** * @short Vector holding one column of Sk, of size \f$n\f$ */ gsl_vector * cSk; /** * @short Weights used to compute the mean of the sigma points' images * @brief \f$wm_0 = \frac{\lambda}{n + \lambda}\f$ * \f$wm_i = \frac{1}{2(n + \lambda)}\f$ */ gsl_vector * wm; /** * @short Weights used to update the covariance matrices * @brief \f$wc_0 = \frac{\lambda}{n + \lambda} + (1 - \alpha^2 + \beta)\f$ * \f$wc_i = \frac{1}{2(n + \lambda)}\f$ */ gsl_vector * wc; /** * @short Temporary matrix holding the image of the sigma points, of size \f$ no \times nbSamples\f$ */ gsl_matrix * dk; /** * @short Vector holding the mean of the sigma points image, of size \f$ no \f$ŝ */ gsl_vector * d_mean; /** * @short Vector holding the inovation, of size \f$ no \f$ŝ */ gsl_vector * ino_dk; /** * @short Matrix holding the sigma points in the columns, of size \f$(n,nbSamples)\f$ */ gsl_matrix * sigmaPoints; /** * @short Temporary vector of size \f$ n \f$ */ gsl_vector * vec_temp_n; /** * @short Temporary vector of size \f$ no \f$ */ gsl_vector * vec_temp_output; /** * @short Temporary matrix of size \f$ n \times 1 \f$ */ gsl_matrix * mat_temp_n_1; /** * @short Temporary matrix of size \f$ n \times no \f$ */ gsl_matrix * mat_temp_n_output; /** * @short Temporary matrix of size \f$ no \times n \f$ */ gsl_matrix * mat_temp_output_n; /** * @short Temporary matrix of size \f$ 1 \times no \f$ */ gsl_matrix * mat_temp_1_output; /** * @short Temporary matrix of size \f$ no \times 1 \f$ */ gsl_matrix * mat_temp_output_1; /** * @short Temporary matrix of size \f$ no \times no \f$ */ gsl_matrix * mat_temp_output_output; /** * @short Temporary matrix of size \f$ n \times n \f$ */ gsl_matrix * mat_temp_n_n; } ukf_state; /** * @short Mother class from which the evolution noises inherit */ class EvolutionNoise { protected: double _initial_value; public: EvolutionNoise(double initial_value) : _initial_value(initial_value) {}; void init(ukf_param &p, ukf_state &s) { gsl_matrix_set_identity(s.Prrk); gsl_matrix_scale(s.Prrk, _initial_value); } void init(ukf_param &p, ukf_scalar_state &s) { gsl_matrix_set_identity(s.Prrk); gsl_matrix_scale(s.Prrk, _initial_value); } virtual void updateEvolutionNoise(ukf_param &p, ukf_state &s) = 0; virtual void updateEvolutionNoise(ukf_param &p, ukf_scalar_state &s) = 0; }; /** * @short Annealing type evolution noise */ class EvolutionAnneal : public EvolutionNoise { double _decay, _lower_bound; public: EvolutionAnneal(double initial_value, double decay, double lower_bound) : EvolutionNoise(initial_value), _decay(decay), _lower_bound(lower_bound) { }; void updateEvolutionNoise(ukf_param &p, ukf_state &s) { for(int i = 0 ; i < p.n ; ++i) { for(int j = 0 ; j < p.n ; ++j) { if(i == j) gsl_matrix_set(s.Prrk, i, i, ukf::math::max(_decay * gsl_matrix_get(s.Prrk,i,i),_lower_bound)); else gsl_matrix_set(s.Prrk, i, j, 0.0); } } } void updateEvolutionNoise(ukf_param &p, ukf_scalar_state &s) { for(int i = 0 ; i < p.n ; ++i) { for(int j = 0 ; j < p.n ; ++j) { if(i == j) gsl_matrix_set(s.Prrk, i, i, ukf::math::max(_decay * gsl_matrix_get(s.Prrk,i,i),_lower_bound)); else gsl_matrix_set(s.Prrk, i, j, 0.0); } } } }; /** * @short Forgetting type evolution noise */ class EvolutionRLS : public EvolutionNoise { double _decay; public: EvolutionRLS(double initial_value, double decay) : EvolutionNoise(initial_value), _decay(decay) { if(ukf::math::cmp_equal(_decay, 0.0)) printf("Forgetting factor should not be null !!\n"); }; void updateEvolutionNoise(ukf_param &p, ukf_state &s) { gsl_matrix_memcpy(s.Prrk, s.Pk); gsl_matrix_scale(s.Prrk, 1.0 / _decay - 1.0); } void updateEvolutionNoise(ukf_param &p, ukf_scalar_state &s) { gsl_matrix_memcpy(s.Prrk, s.Pk); gsl_matrix_scale(s.Prrk, 1.0 / _decay - 1.0); } }; /** * @short Robbins-Monro evolution noise */ class EvolutionRobbinsMonro : public EvolutionNoise { double _alpha; public: EvolutionRobbinsMonro(double initial_value, double alpha) : EvolutionNoise(initial_value), _alpha(alpha) { }; void updateEvolutionNoise(ukf_param &p, ukf_state &s) { // Compute Kk * ino_yk gsl_matrix_view mat_view = gsl_matrix_view_array(s.ino_dk->data, p.no, 1); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, s.Kk, &mat_view.matrix, 0.0, s.mat_temp_n_1); // Compute : Prrk = (1 - alpha) Prrk + alpha . (Kk * ino_dk) * (Kk * ino_dk)^T gsl_blas_dgemm(CblasNoTrans, CblasTrans, _alpha, s.mat_temp_n_1, s.mat_temp_n_1, (1.0 - _alpha),s.Prrk); } void updateEvolutionNoise(ukf_param &p, ukf_scalar_state &s) { // Compute Prrk = (1 - alpha) Prrk + alpha . ino_dk^2 Kk Kk^T gsl_matrix_view mat_view = gsl_matrix_view_array(s.Kk->data,p.n,1); gsl_blas_dgemm(CblasNoTrans, CblasTrans, gsl_pow_2(s.ino_dk) * _alpha, &mat_view.matrix, &mat_view.matrix, 1.0 - _alpha, s.Prrk); } }; } // parameter namespace state { class EvolutionNoise; /** * @short Structure holding the parameters of the statistical linearization * */ typedef struct { /** * @short \f$\kappa \geq 0\f$, \f$\kappa = 0\f$ is a good choice. According to van der Merwe, its value is not critical */ double kpa; /** * @short \f$0 \leq \alpha \leq 1\f$ : "Size" of sigma-point distribution. Should be small if the function is strongly non-linear */ double alpha; /** * @short Non negative weights used to introduce knowledge about the higher order moments of the distribution. For gaussian distributions, \f$\beta = 2\f$ is a good choice */ double beta; /** * @short \f$\lambda = \alpha^2 (n + \kappa) - n\f$ */ double lambda; double lambda_aug; /** * @short \f$\gamma = \sqrt{\lambda + n}\f$ */ double gamma; double gamma_aug; /** * @short Size of the state vector */ int n; /** * @short \f$nbSamples = (2 n + 1)\f$ Number of sigma-points */ int nbSamples; /** * @short \f$nbSamplesMeasure = (4 n + 1)\f$ Number of sigma-points */ int nbSamplesMeasure; /** * @short Dimension of the output : the measurements */ int no; /** * @short Prior estimate of the covariance matrix of the state */ double prior_x; /** * @short Type of process noise */ EvolutionNoise * evolution_noise; /** * @short Parameter used for the evolution noise */ //double process_noise; /** * @short Covariance of the observation noise */ double measurement_noise; } ukf_param; /** * @short Structure holding the matrices manipulated by the statistical linearization * in the vectorial case for state estimation * */ typedef struct { gsl_vector * params; // The parameters of the process equation or anything you need to give to the process function gsl_vector * xi; // State vector gsl_matrix * xi_prediction; // Prediction of the states for each sigma-point gsl_vector * xi_mean; // Mean state vector gsl_matrix * Pxxi; // State covariance matrix gsl_matrix * cholPxxi; // Cholesky decomposition of Pxxi gsl_matrix * Pvvi; // Process noise covariance gsl_matrix * cholPvvi; // Cholesky decomposition of the process noise gsl_matrix * yi_prediction; // Prediction of the measurements for each sigma-point gsl_vector * yi_mean; // Mean measurement vector gsl_vector * ino_yi; // Innovations gsl_matrix * Pyyi; // Measurement covariance matrix gsl_matrix * Pnni; // Measurement noise covariance gsl_matrix * Pxyi; // State-Measurement covariance matrix gsl_vector * sigmaPoint; // Vector holding one sigma point gsl_matrix * sigmaPoints; // Matrix holding all the sigma points gsl_vector * sigmaPointMeasure; // one sigma point for the observation equation gsl_matrix * sigmaPointsMeasure; // Sigma points for the observation equation gsl_vector * wm_j; // Weights used to compute the mean of the sigma points images gsl_vector * wc_j; // Weights used to update the covariance matrices gsl_vector * wm_aug_j; // Augmented set of Weights used to compute the mean of the sigma points images for the observations gsl_vector * wc_aug_j; // Augmented set of Weights used to update the covariance matrices of the observations gsl_matrix * Ki; // Kalman gain gsl_matrix * Ki_T; // Its transpose gsl_vector * temp_n; gsl_matrix * temp_n_n; gsl_matrix * temp_n_1; gsl_matrix * temp_1_n; gsl_matrix * temp_n_no; gsl_matrix * temp_no_no; gsl_matrix * temp_no_1; gsl_matrix * temp_1_no; } ukf_state; /** * @short Mother class from which the evolution noises inherit */ class EvolutionNoise { protected: double _initial_value; public: EvolutionNoise(double initial_value) : _initial_value(initial_value) {}; void init(ukf_param &p, ukf_state &s) { gsl_matrix_set_identity(s.Pvvi); gsl_matrix_scale(s.Pvvi, _initial_value); gsl_matrix_set_identity(s.cholPvvi); gsl_matrix_scale(s.cholPvvi, sqrt(_initial_value)); } virtual void updateEvolutionNoise(ukf_param &p, ukf_state &s) = 0; }; /** * @short Annealing type evolution noise */ class EvolutionAnneal : public EvolutionNoise { double _decay, _lower_bound; public: EvolutionAnneal(double initial_value, double decay, double lower_bound) : EvolutionNoise(initial_value), _decay(decay), _lower_bound(lower_bound) { }; void updateEvolutionNoise(ukf_param &p, ukf_state &s) { double value; for(int i = 0 ; i < p.n ; ++i) { for(int j = 0 ; j < p.n ; ++j) { if(i == j) { value = ukf::math::max(_decay * gsl_matrix_get(s.Pvvi,i,i),_lower_bound); gsl_matrix_set(s.Pvvi, i, i, value); gsl_matrix_set(s.cholPvvi, i ,i, sqrt(value)); } else { gsl_matrix_set(s.Pvvi, i, j, 0.0); gsl_matrix_set(s.cholPvvi, i, j, 0.0); } } } } }; /** * @short Forgetting type evolution noise */ class EvolutionRLS : public EvolutionNoise { double _decay; public: EvolutionRLS(double initial_value, double decay) : EvolutionNoise(initial_value), _decay(decay) { if(ukf::math::cmp_equal(_decay, 0.0)) printf("Forgetting factor should not be null !!\n"); }; void updateEvolutionNoise(ukf_param &p, ukf_state &s) { gsl_matrix_memcpy(s.Pvvi, s.Pxxi); gsl_matrix_scale(s.Pvvi, 1.0 / _decay - 1.0); gsl_matrix_memcpy(s.cholPvvi, s.Pvvi); gsl_linalg_cholesky_decomp(s.cholPvvi); // Set all the elements of cholPvvi strictly above the diagonal to zero for(int j = 0 ; j < p.n ; j++) for(int k = j+1 ; k < p.n ; k++) gsl_matrix_set(s.cholPvvi,j,k,0.0); } }; /** * @short Robbins-Monro evolution noise */ class EvolutionRobbinsMonro : public EvolutionNoise { double _alpha; public: EvolutionRobbinsMonro(double initial_value, double alpha) : EvolutionNoise(initial_value), _alpha(alpha) { }; void updateEvolutionNoise(ukf_param &p, ukf_state &s) { // Compute Kk * ino_yk gsl_blas_dgemv(CblasNoTrans, 1.0, s.Ki, s.ino_yi, 0.0, s.temp_n); // Compute : Prrk = (1 - alpha) Prrk + alpha . (Kk * ino_dk) * (Kk * ino_dk)^T gsl_matrix_view mat_view = gsl_matrix_view_array(s.temp_n->data,p.n,1); gsl_blas_dgemm(CblasNoTrans, CblasTrans, _alpha, &mat_view.matrix, &mat_view.matrix, (1.0 - _alpha),s.Pvvi); } }; } // namespace for state estimation namespace srstate { /** * @short Structure holding the parameters of the statistical linearization * */ typedef struct { /** * @short \f$\kappa \geq 0\f$, \f$\kappa = 0\f$ is a good choice. According to van der Merwe, its value is not critical */ double kpa; /** * @short \f$0 \leq \alpha \leq 1\f$ : "Size" of sigma-point distribution. Should be small if the function is strongly non-linear */ double alpha; /** * @short Non negative weights used to introduce knowledge about the higher order moments of the distribution. For gaussian distributions, \f$\beta = 2\f$ is a good choice */ double beta; /** * @short \f$\lambda = \alpha^2 (n + \kappa) - n\f$ */ double lambda; double lambda_aug; /** * @short \f$\gamma = \sqrt{\lambda + n}\f$ */ double gamma; double gamma_aug; /** * @short Size of the state vector */ int n; /** * @short \f$nbSamples = (2 n + 1)\f$ Number of sigma-points */ int nbSamples; /** * @short \f$nbSamplesMeasure = (4 n + 1)\f$ Number of sigma-points */ int nbSamplesMeasure; /** * @short Dimension of the output : the measurements */ int no; /** * @short Prior estimate of the covariance matrix of the state */ double prior_x; /** * @short Type of process noise */ ProcessNoise process_noise_type; /** * @short Parameter used for the evolution noise */ double process_noise; /** * @short Covariance of the observation noise */ double measurement_noise; } ukf_param; /** * @short Structure holding the matrices manipulated by the statistical linearization * in the vectorial case for state estimation * */ typedef struct { gsl_vector * params; // The parameters of the process equation or anything you need to give to the process function gsl_vector * xi; // State vector gsl_matrix * xi_prediction; // Prediction of the states for each sigma-point gsl_vector * xi_mean; // Mean state vector gsl_matrix * Sxi; // Cholesky factor of variance covariance of the state gsl_matrix * Svi; // Cholesky factor of the process noise gsl_matrix * yi_prediction; // Prediction of the measurements for each sigma-point gsl_vector * yi_mean; // Mean measurement vector gsl_vector * ino_yi; // Innovations gsl_matrix * Syi; // Cholesky factor of the variance covariance of the output gsl_matrix * Sni; // Cholesky factor of the measurement noise gsl_matrix * Pxyi; // State-Measurement covariance matrix gsl_vector * sigmaPoint; // Vector holding one sigma point gsl_matrix * sigmaPoints; // Matrix holding all the sigma points gsl_vector * sigmaPointMeasure; // one sigma point for the observation equation gsl_matrix * sigmaPointsMeasure; // Sigma points for the observation equation gsl_matrix * U; gsl_vector * wm_j; // Weights used to compute the mean of the sigma points images gsl_vector * wc_j; // Weights used to update the covariance matrices gsl_vector * wm_aug_j; // Augmented set of Weights used to compute the mean of the sigma points images for the observations gsl_vector * wc_aug_j; // Augmented set of Weights used to update the covariance matrices of the observations gsl_matrix * Ki; // Kalman gain gsl_matrix * Ki_T; // Its transpose gsl_vector * temp_n; gsl_vector * temp_no; gsl_matrix * temp_n_n; gsl_matrix * temp_n_1; gsl_matrix * temp_1_n; gsl_matrix * temp_n_no; gsl_matrix * temp_no_no; gsl_matrix * temp_no_1; gsl_matrix * temp_1_no; gsl_matrix * temp_3n_n; gsl_matrix * temp_2nno_no; } ukf_state; } // namespace for state estimation, square root implementation } #endif // UKF_TYPES_H
{ "alphanum_fraction": 0.5024306836, "avg_line_length": 33.588963964, "ext": "h", "hexsha": "6ceb9b8093d459ccf32d8231c19c82db55fdbc98", "lang": "C", "max_forks_count": 52, "max_forks_repo_forks_event_max_datetime": "2021-09-13T02:47:35.000Z", "max_forks_repo_forks_event_min_datetime": "2015-03-10T01:02:09.000Z", "max_forks_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "bahia14/C-Kalman-filtering", "max_forks_repo_path": "src/ukf_types.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_issues_repo_issues_event_max_datetime": "2018-10-17T21:45:18.000Z", "max_issues_repo_issues_event_min_datetime": "2018-10-16T10:29:05.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "bahia14/C-Kalman-filtering", "max_issues_repo_path": "src/ukf_types.h", "max_line_length": 184, "max_stars_count": 101, "max_stars_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "bahia14/C-Kalman-filtering", "max_stars_repo_path": "src/ukf_types.h", "max_stars_repo_stars_event_max_datetime": "2022-02-21T15:24:07.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-07T05:30:09.000Z", "num_tokens": 6638, "size": 29827 }
/* * 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 tree_5172eda7_51f9_405a_9f3b_bcaa5e4243c1_h #define tree_5172eda7_51f9_405a_9f3b_bcaa5e4243c1_h #include <assert.h> #include <gslib/std.h> #include <gslib/string.h> __gslib_begin__ struct _tree_trait_copy {}; struct _tree_trait_detach {}; template<class _node> struct _treenode_list { public: typedef _node mynode; typedef _treenode_list<_node> mylist; protected: mynode* _first; mynode* _last; int _size; public: _treenode_list() { reset(); } _treenode_list(mynode* node) { setup(node, node, 1); } _treenode_list(mynode* first, mynode* last, int size) { setup(first, last, size); } _treenode_list(mynode* first, mynode* last) { setup(first, last, count_nodes(first, last)); } bool empty() const { return !_size; } int size() const { return _size; } mynode* front() const { return _first; } mynode* back() const { return _last; } template<class _lambda> void for_each(_lambda lam) { for_each(_first, _last, lam); } public: void setup(mynode* first, mynode* last, int size) { _first = first; _last = last; _size = size; } void reset() { _first = _last = nullptr; _size = 0; } void swap(mylist& that) { gs_swap(_first, that._first); gs_swap(_last, that._last); gs_swap(_size, that._size); } void erase(mynode* node) { assert(node); mynode* prev = node->prev(); mynode* next = node->next(); join(prev, next); if(node == _first) _first = next; if(node == _last) _last = prev; node->_prev = node->_next = nullptr; _size --; } void init(mynode* node) { assert(node); assert(!_first && !_last && !_size); _first = _last = node; _size = 1; } void insert_before(mynode* pos, mynode* node) { assert(node); if(pos == nullptr) return init(node); join(pos->prev(), node); join(node, pos); if(pos == _first) _first = node; _size ++; } void insert_after(mynode* pos, mynode* node) { assert(node); if(pos == nullptr) return init(node); join(node, pos->next()); join(pos, node); if(pos == _last) _last = node; _size ++; } void connect(mylist& that) { if(empty()) return swap(that); else if(that.empty()) return; assert(!empty() && !that.empty()); join(back(), that.front()); _size += that.size(); _last = that.back(); that.reset(); } public: static int count_nodes(mynode* first, mynode* last) { assert(first && last); int c = 0; mynode* n = first; for(;;) { c ++; if(n == last) return c; n = n->next(); } return c; } static void join(mynode* node1, mynode* node2) { if(node1 != nullptr) node1->_next = node2; if(node2 != nullptr) node2->_prev = node1; } template<class _lambda> static void for_each(mynode* first, mynode* last, _lambda lam) { if(!first) return; for(mynode* node = first; node != last; ) { mynode* next = node->next(); lam(node); node = next; } lam(last); } }; template<class _wrapper> struct _treenode_default_wrapper { typedef _wrapper wrapper; typedef _treenode_default_wrapper<wrapper> default_wrapper; typedef _treenode_list<wrapper> children; template<class, class, class> friend class tree; template<class> friend struct _treenode_list; protected: wrapper* _parent; wrapper* _prev; wrapper* _next; children _children; public: default_wrapper() { _parent = _prev = _next = nullptr; } int childs() const { return _children.size(); } wrapper* parent() const { return _parent; } wrapper* prev() const { return _prev; } wrapper* next() const { return _next; } wrapper* child() const { return _children.empty() ? nullptr : _children.front(); } wrapper* last_child() const { return _children.empty() ? nullptr : _children.back(); } void birth_before(wrapper* pos, wrapper* node) { return _children.insert_before(pos, node); } void birth_after(wrapper* pos, wrapper* node) { return _children.insert_after(pos, node); } void erase(wrapper* node) { return _children.erase(node); } void acquire_children(children& chs) { chs.for_each([this](wrapper* w) { w->_parent = static_cast<wrapper*>(this); }); _children.swap(chs); } void swap_children(wrapper& w) { children t; t.swap(_children); w.acquire_children(t); acquire_children(t); } void reset_children() { _children.reset(); } template<class _lambda> void for_each(_lambda lam) { _children.for_each(lam); } }; template<class _ty> struct _treenode_cpy_wrapper: public _treenode_default_wrapper<_treenode_cpy_wrapper<_ty> > { typedef _ty value; typedef _treenode_cpy_wrapper<_ty> wrapper; typedef _treenode_list<wrapper> children; typedef _tree_trait_copy tsf_behavior; template<class, class, class> friend class tree; protected: value _value; public: value* get_ptr() { return &_value; } const value* get_ptr() const { return &_value; } value& get_ref() { return _value; } const value& get_ref() const { return _value; } template<class _ctor> void born() {} void born() {} void kill() {} void copy(const wrapper* a) { _value = a->_value; } void attach(wrapper* a) { !!error!! } }; template<class _ty> struct _treenode_wrapper: public _treenode_default_wrapper<_treenode_wrapper<_ty> > { typedef _ty value; typedef _treenode_wrapper<_ty> wrapper; typedef _treenode_list<wrapper> children; typedef _tree_trait_detach tsf_behavior; template<class, class, class> friend class tree; protected: value* _value; public: wrapper() { _value = nullptr; } value* get_ptr() const { return _value; } value& get_ref() const { return *_value; } template<class _ctor> void born() { _value = new _ctor; } template<class _ctor, class _a1> void born(_a1& a) { _value = new _ctor(a); } template<class _ctor, class _a1, class _a2> void born(_a1& a, _a2& b) { _value = new _ctor(a, b); } template<class _ctor, class _a1, class _a2, class _a3> void born(_a1& a, _a2& b, _a3& c) { _value = new _ctor(a, b, c); } void born() { _value = new value; } void kill() { delete _value; } void copy(const wrapper* a) { assert(!"prevent."); } void attach(wrapper* a) { assert(a && a->_value); kill(); _value = a->_value; a->_value = nullptr; } }; template<class _wrapper> struct _tree_allocator { typedef _wrapper wrapper; static wrapper* born() { return new wrapper; } static void kill(wrapper* w) { delete w; } }; template<class _val> struct _treenode_val { typedef _val value; typedef const _val const_value; template<class, class, class> friend class tree; union { value* _vptr; const_value* _cvptr; }; value* get_wrapper() const { return _vptr; } operator bool() const { return _vptr != nullptr; } protected: value* vparent() const { return _vptr ? _vptr->_parent : nullptr; } value* vchild() const { return _vptr ? _vptr->front() : nullptr; } value* vchild_last() const { return _vptr ? _vptr->back() : nullptr; } value* vsibling() const { return _vptr ? _vptr->next() : nullptr; } value* vsibling_last() const { return _vptr ? _vptr->prev() : nullptr; } protected: template<class _lambda, class _value> static void preorder_traversal(_lambda lam, _value* v) { assert(v); lam(v); for(_value* w = v->child(); w; w = w->next()) preorder_traversal(lam, w); } template<class _lambda, class _value> static void postorder_traversal(_lambda lam, _value* v) { assert(v); for(_value* w = v->child(); w; w = w->next()) postorder_traversal(lam, w); lam(v); } public: template<class _lambda> void preorder_traversal(_lambda lam) { if(_vptr) preorder_traversal(lam, _vptr); } template<class _lambda> void preorder_traversal(_lambda lam) const { if(_cvptr) preorder_traversal(lam, _cvptr); } template<class _lambda> void postorder_traversal(_lambda lam) { if(_vptr) postorder_traversal(lam, _vptr); } template<class _lambda> void postorder_traversal(_lambda lam) const { if(_cvptr) postorder_traversal(lam, _cvptr); } }; template<class _ty, class _wrapper = _treenode_cpy_wrapper<_ty> > class _tree_const_iterator: public _treenode_val<_wrapper> { public: typedef _ty value; typedef _wrapper wrapper; typedef _tree_const_iterator<value, wrapper> iterator; template<class, class, class> friend class tree; public: iterator(const wrapper* w = nullptr) { _cvptr = w; } bool is_valid() const { return _cvptr != nullptr; } const value* get_ptr() const { return _cvptr->get_ptr(); } const value* operator->() const { return _cvptr->get_ptr(); } const value& operator*() const { return _cvptr->get_ref(); } int childs() const { return _cvptr->childs(); } int siblings() const { return _cvptr->parent() ? _cvptr->parent()->childs() : 1; } bool is_root() const { return _cvptr ? !_cvptr->parent() : false; } bool is_leaf() const { return _cvptr ? !_cvptr->childs() : false; } bool operator==(const iterator& that) const { return _cvptr == that._cvptr; } bool operator!=(const iterator& that) const { return _cvptr != that._cvptr; } iterator child() const { return _cvptr ? iterator(_cvptr->child()) : iterator(); } iterator last_child() const { return _cvptr ? iterator(_cvptr->last_child()) : iterator(); } iterator parent() const { return _cvptr ? iterator(_cvptr->parent()) : iterator(); } iterator next() const { return _cvptr ? iterator(_cvptr->next()) : iterator(); } iterator prev() const { return _cvptr ? iterator(_cvptr->prev()) : iterator(); } iterator root() const { if(const wrapper* w = _cvptr) { for( ; w->parent(); w = w->parent()); return iterator(w); } return iterator(); } iterator eldest() const { if(const wrapper* w = _cvptr ? _cvptr->parent() : nullptr) return iterator(w->child()); return iterator(); } iterator youngest() const { if(const wrapper* w = _cvptr ? _cvptr->parent() : nullptr) return iterator(w->last_child()); return iterator(); } }; template<class _ty, class _wrapper = _treenode_cpy_wrapper<_ty> > class _tree_iterator: public _tree_const_iterator<_ty, _wrapper> { public: typedef _ty value; typedef _wrapper wrapper; typedef _tree_const_iterator<value, wrapper> superref; typedef _tree_const_iterator<value, wrapper> const_iterator; typedef _tree_iterator<value, wrapper> iterator; template<class, class, class> friend class tree; public: iterator(wrapper* w = nullptr): superref(w) {} value* get_ptr() const { return _vptr->get_ptr(); } value* operator->() const { return _vptr->get_ptr(); } value& operator*() const { return _vptr->get_ref(); } bool operator==(const iterator& that) const { return _vptr == that._vptr; } bool operator!=(const iterator& that) const { return _vptr != that._vptr; } bool operator==(const const_iterator& that) const { return _vptr == that._vptr; } bool operator!=(const const_iterator& that) const { return _vptr != that._vptr; } operator const_iterator() { return const_iterator(_cvptr); } void to_root() { while(wrapper* w = _vptr->parent()) _vptr = w; } void to_child() { _vptr = _vptr->child(); } void to_last_child() { _vptr = _vptr->last_child(); } void to_parent() { _vptr = _vptr->parent(); } void to_next() { _vptr = _vptr->next(); } void to_prev() { _vptr = _vptr->prev(); } void to_eldest() { if(wrapper* w = _vptr->parent()) _vptr = w->child(); } void to_youngest() { if(wrapper* w = _vptr->parent()) _vptr = w->last_child(); } iterator root() const { iterator i(_vptr); i.to_root(); return i; } iterator child() const { return _vptr ? iterator(_vptr->child()) : iterator(); } iterator last_child() const { return _vptr ? iterator(_vptr->last_child()) : iterator(); } iterator parent() const { return _vptr ? iterator(_vptr->parent()) : iterator(); } iterator next() const { return _vptr ? iterator(_vptr->next()) : iterator(); } iterator prev() const { return _vptr ? iterator(_vptr->prev()) : iterator(); } iterator eldest() const { iterator i(_vptr); i.to_eldest(); return i; } iterator youngest() const { iterator i(_vptr); i.to_youngest(); return i; } }; template<class _ty, class _wrapper = _treenode_cpy_wrapper<_ty>, class _alloc = _tree_allocator<_wrapper> > class tree: public _treenode_val<_wrapper> { public: typedef _ty value; typedef _wrapper wrapper; typedef _alloc alloc; typedef tree<value, wrapper, alloc> myref; typedef _tree_const_iterator<value, wrapper> const_iterator; typedef _tree_iterator<value, wrapper> iterator; friend class const_iterator; friend class iterator; public: tree() { _vptr = nullptr; } ~tree() { destroy(); } void destroy() { erase(get_root()); } void clear() { destroy(); } void swap(myref& that) { gs_swap(_vptr, that._vptr); } iterator get_root() { return iterator(_vptr); } const_iterator get_root() const { return const_iterator(_cvptr); } bool is_valid() const { return _cvptr != nullptr; } iterator insert(iterator i) { return insert<value>(i); } iterator insert_after(iterator i) { return insert_after<value>(i); } iterator birth(iterator i) { return birth<value>(i); } iterator birth_tail(iterator i) { return birth_tail<value>(i); } public: bool is_root(const_iterator i) const { if(!i.is_valid()) return false; return _cvptr == i._cvptr; } bool is_mine(const_iterator i) const { if(!i.is_valid()) return false; return is_root(i.root()); } void set_root(wrapper* w) { assert(!_vptr && "use attach method."); _vptr = w; } void erase(iterator i) { if(!i.is_valid()) return; if(is_root(i)) { _erase(i); _vptr = nullptr; } else { wrapper* w = i._vptr; wrapper* p = w->parent(); p->erase(w); _erase(i); } } template<class _ctor> iterator insert(iterator i) { if(!i.is_valid()) return _cvptr ? get_root() : _init<_ctor>(); wrapper* w = i._vptr; wrapper* p = w->_parent; wrapper* n = alloc::born(); n->born<_ctor>(); p->birth_before(w, n); n->_parent = p; return iterator(n); } template<class _ctor> iterator insert_after(iterator i) { if(!i.is_valid()) return _cvptr ? get_root() : _init<_ctor>(); wrapper* w = i._vptr; wrapper* p = w->_parent; wrapper* n = alloc::born(); n->born<_ctor>(); p->birth_after(w, n); n->_parent = p; return iterator(n); } template<class _ctor> iterator birth(iterator i) { if(!i.is_valid()) return _cvptr ? get_root() : _init<_ctor>(); wrapper* w = i._vptr; wrapper* n = alloc::born(); n->born<_ctor>(); w->birth_before(w->child(), n); n->_parent = w; return iterator(n); } template<class _ctor> iterator birth_tail(iterator i) { if(!i.is_valid()) return _cvptr ? get_root() : _init<_ctor>(); wrapper* w = i._vptr; wrapper* n = alloc::born(); n->born<_ctor>(); w->birth_after(w->last_child(), n); n->_parent = w; return iterator(n); } myref& detach(myref& subtree, iterator i) { if(!i.is_valid() || !is_mine(i)) return subtree; if(is_root(i)) _vptr = nullptr; else { wrapper* m = i._vptr; wrapper* p = m->_parent; p->erase(m); m->_parent = nullptr; } subtree.~tree(); new (&subtree) tree(i); return subtree; } template<class _tsftrait> void transfer(wrapper* src, wrapper* des) { } template<> void transfer<_tree_trait_copy>(wrapper* src, wrapper* des) { assert(src && des); des->copy(src); des->swap_children(*src); src->for_each([&](wrapper* w) { _erase(w); }); src->reset_children(); } template<> void transfer<_tree_trait_detach>(wrapper* src, wrapper* des) { assert(src && des); des->attach(src); des->swap_children(*src); src->for_each([&](wrapper* w) { _erase(w); }); src->reset_children(); } void attach(myref& subtree, iterator i) { assert(i.is_valid() && is_mine(i)); wrapper* w = subtree.get_root()._vptr; assert(w); transfer<wrapper::tsf_behavior>(w, i._vptr); w = i._vptr; for(wrapper* c = w->child(); c; c = c->next()) c->_parent = w; } template<class _ctor> iterator swap(iterator p, myref& that) { assert(this != &that); if(p == get_root()) { swap(that); return get_root(); } iterator prevsib, grand; prevsib = p.prev(); grand = p.parent(); assert(prevsib || grand); myref t; detach(t, p); auto pos = prevsib ? insert_after<_ctor>(prevsib) : birth<_ctor>(grand); assert(pos); attach(that, pos); that.swap(t); return pos; } public: template<class lambda> void for_each(lambda lam) { for_each(get_root(), lam); } template<class lambda> void for_each(iterator i, lambda lam) { if(i.is_valid()) { for(iterator j = i.child(); j.is_valid(); j.to_next()) for_each(j, lam); lam(i.get_ptr()); } } template<class lambda> void const_for_each(lambda lam) const { const_for_each(get_root(), lam); } template<class lambda> void const_for_each(const_iterator i, lambda lam) const { if(i.is_valid()) { for(const_iterator j = i.child(); j.is_valid(); j = j.next()) for_each(j, lam); lam(i.get_ptr()); } } protected: tree(iterator i) { _vptr = i._vptr; } void _erase(iterator i) { _erase(i.get_wrapper()); } void _erase(wrapper* w) { assert(w); for(auto* c = w->child(); c;) { auto* n = c->next(); _erase(c); c = n; } w->kill(); alloc::kill(w); } template<class _ctor> iterator _init() { _vptr = alloc::born(); _vptr->born<_ctor>(); _vptr->_parent = nullptr; return iterator(_vptr); } public: bool debug_check(iterator i) { iterator f = i.prev(), b = i.next(); if(f.is_valid() && f.next() != i) { assert(0); return false; } if(b.is_valid() && b.prev() != i) { assert(0); return false; } for(iterator j = i.child(); j.is_valid(); j.to_next()) if(j.parent() != i) { assert(0); return false; } return true; } }; template<class _tree> class _print_tree { public: typedef _tree tree; typedef typename tree::value value; typedef typename tree::iterator iterator; typedef typename tree::const_iterator const_iterator; protected: tree& _inst; string _src; public: _print_tree(tree& t): _inst(t) { } const gchar* print() { _src.clear(); append(_inst.get_root(), 0); return _src.c_str(); } protected: string decorate(const_iterator i, int level) { if(!i.is_valid()) return string(); string r, a; for(int j = 0; j < level; j ++) r.append(_t(" ")); i.is_leaf() ? r.append(_t("+ ")) : r.append(_t("- ")); i.is_root() ? r.append(_t("root(")) : a.format(_t("level%d("), level); r.append(a); r.append(i->to_string()); r.append(_t(")\n")); return r; } void append(const_iterator i, int level) { if(!i.is_valid()) return; _src.append(decorate(i, level).c_str()); level ++; for(i.to_child(); i.is_valid(); i.to_next()) append(i, level); } }; __gslib_end__ #endif
{ "alphanum_fraction": 0.5685575643, "avg_line_length": 31.554200542, "ext": "h", "hexsha": "9ce4e5bffdeb28937b8b42b663730725b8194de2", "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/gslib/tree.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/gslib/tree.h", "max_line_length": 98, "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/gslib/tree.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": 5908, "size": 23287 }
#include <gsl/gsl_math.h> #include "gsl_cblas.h" #include "cblas.h" void cblas_srotm (const int N, float *X, const int incX, float *Y, const int incY, const float *P) { #define BASE float #include "source_rotm.h" #undef BASE }
{ "alphanum_fraction": 0.6965811966, "avg_line_length": 18, "ext": "c", "hexsha": "a037d76aa18f3a84fd65fcdfca380628e2a5d643", "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/srotm.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/srotm.c", "max_line_length": 77, "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/srotm.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": 75, "size": 234 }
// lu2tlub.c // // blocked LU decomposition library for column-major version // // Time-stamp: <11/05/13 11:35:56 makino> #include <stdio.h> #include <stdlib.h> #include <math.h> #ifndef NOBLAS #ifdef MKL #include <mkl_cblas.h> #else #include <cblas.h> #endif #endif #include <lu2lib.h> typedef double v2df __attribute__((vector_size(16))); typedef union {v2df v; double s[2];}v2u; void timer_init(); #define MAXTHREADS 4 static int findpivot0(int n, double a[][n], int current) { double amax = fabs(a[0][current]); int i; int p=current; BEGIN_TSC; for(i=current+1;i<n;i++){ if (fabs(a[0][i]) > amax){ amax = fabs(a[0][i]); p = i; } } END_TSC(t,7); return p; } static int findpivot(int n, double a[][n], int current) { int p; int p2; BEGIN_TSC; p = cblas_idamax(n-current, a[0]+current, 1)+current; // p2 = findpivot0( n, a, current); // printf("n, current, p, p2 = %d %d %d %d\n",n, current,p, p2); END_TSC(t,7); return p; } static int findpivot_sequentical(int n, double a[][n], int current) { double amax = fabs(a[0][current]); int i; int p=current; for(i=current+1;i<n;i++){ if (fabs(a[0][i]) > amax){ amax = fabs(a[0][i]); p = i; } } return p; } static int findpivot_omp(int n, double a[][n], int current) // factor 2 slower than sequential code even for n=8k.... // on Core i7 920 { double amax[MAXTHREADS]={-1.0,-1.0,-1.0,-1.0}; int p[MAXTHREADS]; double am; int pm; int di= (n-current-1)/4; int k; BEGIN_TSC; if (di > 1024){ //#pragma omp parallel for private(k) for (k=0;k<MAXTHREADS; k++){ int i; int istart = current+1+k*di; int iend = current+1+(k+1)*di; if (iend > n) iend = n; for(i=istart;i<iend;i++){ if (fabs(a[0][i]) > amax[k]){ amax[k] = fabs(a[0][i]); p[k] = i; } } } pm =p[0]; am = amax[0]; for (k=1;k<MAXTHREADS; k++){ if(amax[k]>am){ am = amax[k]; pm=p[k]; } } }else{ pm=findpivot_sequentical( n, a, current); } END_TSC(t,7); return pm; } static void swaprows(int n, double a[][n], int row1, int row2, int cstart, int cend) { int j; if (row1 != row2){ for(j=cstart;j<cend;j++){ double tmp = a[j][row1]; a[j][row1] = a[j][row2]; a[j][row2]=tmp; } } } static void scalerow( int n, double a[n+1][n], double scale, int row, int cstart, int cend) { int j; for(j=cstart;j<cend;j++) a[j][row]*= scale; } static void vsmulandsub(int n, double a[n+1][n], int cr, int cc, int c0, int r0,int r1) { int j,k; double * ar = a[cr]; k=c0; double s = a[c0][cc]; double *al = a[c0]; while (r0 & 7){ al[r0] -= ar[r0]*s; r0++; } while (r1 & 7){ al[r1-1] -= ar[r1-1]*s; r1--; } v2df * arv = (v2df*) (ar+r0); v2df * alv = (v2df*) (al+r0); v2df ss = (v2df){s,s}; // for(j=r0;j<r1;j++) // al[j] -= ar[j]*s; for(j=0;j<(r1-r0)/2;j+=4){ alv[j] -= arv[j]*ss; alv[j+1] -= arv[j+1]*ss; alv[j+2] -= arv[j+2]*ss; alv[j+3] -= arv[j+3]*ss; __builtin_prefetch(alv+j+32,1,3); __builtin_prefetch(arv+j+32,0,0); } } static void vvmulandsub(int n, double a[n+1][n], int cr, int cc, int c0, int c1, int r0,int r1) { int j,k; double * ar = a[cr]; #ifdef TIMETEST BEGIN_TSC; #endif if (c1-c0 == 1){ vsmulandsub(n,a, cr, cc,c0, r0,r1); }else{ for (k=c0;k<c1;k++){ double s = a[k][cc]; double *al = a[k]; for(j=r0;j<r1;j++) al[j] -= ar[j]*s; } } #ifdef TIMETEST END_TSC(t,6); #endif } static void mmmulandsub_old(int n, double a[n+1][n], int m0, int m1, int c0, int c1, int r0,int r1) { int j,k,l; printf("Enter mmul\n"); #ifndef NOBLAS cblas_dgemm( CblasColMajor, CblasNoTrans, CblasNoTrans, r1-r0, c1-c0, m1-m0, -1.0, &(a[m0][r0]), n, &(a[c0][m0]), n, 1, &(a[c0][r0]), n ); // example: // r0, m0 = i+m,i // m0, c0 = i, i+m // r0, c0 = i+m, i+m //r1-r0 = n-i-m // c1-c0 = iend-i-m // m1-m0 = m #else for(j=r0;j<r1;j++) for (k=c0;k<c1;k++) for (l=m0; l<m1; l++) a[k][j] -= a[l][j]*a[k][l]; #endif } static void matmul_for_nk4_0(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int n) { int j,k,l; for(l=0;l<4;l+=2){ for(k=0;k<4;k+=2){ for(j=0;j<n;j++){ c[k][j] -= a[l][j]*b[k][l]+ a[l+1][j]*b[k][l+1]; c[k+1][j] -= a[l][j]*b[k+1][l]+ a[l+1][j]*b[k+1][l+1]; } } } } static void matmul_for_nk8_0(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int n) { int i,j,k,l; const int m=8; double btmp[m][m]; for(i=0;i<m;i++)for(j=0;j<m;j++)btmp[i][j]=b[i][j]; #pragma omp parallel for private(l,k,j) for(l=0;l<8;l+=2){ for(k=0;k<8;k+=2){ for(j=0;j<n;j++){ c[k][j] -= a[l][j]*btmp[k][l]+ a[l+1][j]*btmp[k][l+1]; c[k+1][j] -= a[l][j]*btmp[k+1][l]+ a[l+1][j]*btmp[k+1][l+1]; } } } } static void matmul_for_nk8_2(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int n) { int i,j,k,l; const int m=8; double btmp[m][m]; for(i=0;i<m;i++)for(j=0;j<m;j++)btmp[i][j]=b[i][j]; #pragma omp parallel for private(l,k,j) for(k=0;k<8;k+=2){ for(l=0;l<8;l+=4){ for(j=0;j<n;j++){ c[k][j] -= a[l][j]*btmp[k][l] + a[l+1][j]*btmp[k][l+1] + a[l+2][j]*btmp[k][l+2] + a[l+3][j]*btmp[k][l+3]; c[k+1][j] -= a[l][j]*btmp[k+1][l] + a[l+1][j]*btmp[k+1][l+1] + a[l+2][j]*btmp[k+1][l+2] + a[l+3][j]*btmp[k+1][l+3]; // c[k][j] -= a[l][j]*btmp[k][l]+ a[l+1][j]*btmp[k][l+1]; // c[k+1][j] -= a[l][j]*btmp[k+1][l]+ a[l+1][j]*btmp[k+1][l+1]; } } } } static void matmul_for_nk8_3(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int n) { int i,j,k,l; const int m=8; const int mm = 32; double btmp[m][m]; double atmp[m][mm]; for(i=0;i<m;i++)for(j=0;j<m;j++)btmp[i][j]=b[i][j]; for(j=0;j<n;j+=mm){ int jj; for(i=0;i<m;i++){ for(k=0;k<mm;k++){ atmp[i][k]=a[i][j+k]; } } for(i=0;i<m;i++){ int jjend = mm; if (jjend+j > n) jjend = n-j; for(jj=0;jj<jjend;jj+=2){ c[i][j+jj] -= atmp[0][jj]*btmp[i][0] +atmp[1][jj]*btmp[i][1] +atmp[2][jj]*btmp[i][2] +atmp[3][jj]*btmp[i][3] +atmp[4][jj]*btmp[i][4] +atmp[5][jj]*btmp[i][5] +atmp[6][jj]*btmp[i][6] +atmp[7][jj]*btmp[i][7]; c[i][j+jj+1] -= atmp[0][jj+1]*btmp[i][0] +atmp[1][jj+1]*btmp[i][1] +atmp[2][jj+1]*btmp[i][2] +atmp[3][jj+1]*btmp[i][3] +atmp[4][jj+1]*btmp[i][4] +atmp[5][jj+1]*btmp[i][5] +atmp[6][jj+1]*btmp[i][6] +atmp[7][jj+1]*btmp[i][7]; } } } } static void matmul_for_nk8_4(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int n) { int i,j,k,l; const int m=8; const int mm = 16; double btmp[m][m]; v2df b2tmp[m][m]; double atmp[m][mm]; for(i=0;i<m;i++)for(j=0;j<m;j++)b2tmp[i][j]=(v2df){b[i][j],b[i][j]}; //#pragma omp parallel for private(j,i,atmp) //use of OMP here does not speed things up for(j=0;j<n;j+=mm){ int jj; for(i=0;i<m;i++){ v2df * dest = (v2df*)(atmp[i]); v2df * src = (v2df*)(a[i]+j); dest[0]=src[0]; dest[ 1]=src[ 1]; dest[ 2]=src[ 2]; dest[ 3]=src[ 3]; dest[ 4]=src[ 4]; dest[ 5]=src[ 5]; dest[ 6]=src[ 6]; dest[ 7]=src[ 7]; } for(i=0;i<m;i++){ int jjend = mm; __builtin_prefetch(c[i]+j+64,1,0); __builtin_prefetch(c[i]+j+80,1,0); if (jjend+j > n) jjend = n-j; for(jj=0;jj<jjend;jj+=4){ v2df* cp = (v2df*)(&c[i][j+jj]); v2df* ap = (v2df*)(atmp[0]+jj); v2df* cpp = (v2df*)(&c[i][j+jj+2]); v2df* app = (v2df*)(atmp[0]+jj+2); *cp -= (*ap)*b2tmp[i][0] +(*(ap+16))*b2tmp[i][1] +(*(ap+32))*b2tmp[i][2] +(*(ap+48))*b2tmp[i][3] +(*(ap+64))*b2tmp[i][4] +(*(ap+80))*b2tmp[i][5] +(*(ap+96))*b2tmp[i][6] +(*(ap+112))*b2tmp[i][7]; *cpp -= (*app)*b2tmp[i][0] +(*(app+16))*b2tmp[i][1] +(*(app+32))*b2tmp[i][2] +(*(app+48))*b2tmp[i][3] +(*(app+64))*b2tmp[i][4] +(*(app+80))*b2tmp[i][5] +(*(app+96))*b2tmp[i][6] +(*(app+112))*b2tmp[i][7]; } } } } static void matmul_for_nk8_5(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int n) { int i,j,k,l; const int m=8; const int mm = 32; double btmp[m][m]; v2df b2tmp[m][m]; for(i=0;i<m;i++)for(j=0;j<m;j++)b2tmp[i][j]=(v2df){b[i][j],b[i][j]}; //#pragma omp parallel for private(j,i) //use of OMP here does not speed things up for(j=0;j<n;j+=mm){ double atmp[m][mm]; int jj; for(i=0;i<m;i++){ v2df * dest = (v2df*)(atmp[i]); v2df * src = (v2df*)(a[i]+j); dest[0]=src[0]; dest[ 1]=src[ 1]; dest[ 2]=src[ 2]; dest[ 3]=src[ 3]; dest[ 4]=src[ 4]; dest[ 5]=src[ 5]; dest[ 6]=src[ 6]; dest[ 7]=src[ 7]; dest[ 8]=src[ 8]; dest[ 9]=src[ 9]; dest[ 10]=src[ 10]; dest[ 11]=src[ 11]; dest[ 12]=src[ 12]; dest[ 13]=src[ 13]; dest[ 14]=src[ 14]; dest[ 15]=src[ 15]; } for(i=0;i<m;i++){ int jjend = mm; __builtin_prefetch(c[i]+j+64,1,0); __builtin_prefetch(c[i]+j+80,1,0); if (jjend+j > n) jjend = n-j; for(jj=0;jj<jjend;jj+=4){ v2df* cp = (v2df*)(&c[i][j+jj]); v2df* ap = (v2df*)(atmp[0]+jj); v2df* cpp = (v2df*)(&c[i][j+jj+2]); v2df* app = (v2df*)(atmp[0]+jj+2); *cp -= (*ap)*b2tmp[i][0] +(*(ap+16))*b2tmp[i][1] +(*(ap+32))*b2tmp[i][2] +(*(ap+48))*b2tmp[i][3] +(*(ap+64))*b2tmp[i][4] +(*(ap+80))*b2tmp[i][5] +(*(ap+96))*b2tmp[i][6] +(*(ap+112))*b2tmp[i][7]; *cpp -= (*app)*b2tmp[i][0] +(*(app+16))*b2tmp[i][1] +(*(app+32))*b2tmp[i][2] +(*(app+48))*b2tmp[i][3] +(*(app+64))*b2tmp[i][4] +(*(app+80))*b2tmp[i][5] +(*(app+96))*b2tmp[i][6] +(*(app+112))*b2tmp[i][7]; } } } } static void matmul_for_nk8(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int n) { int m0,m1,m2,m3; int s1, s2, s3; int ds = (n/64)*16; s1 = ds; s2 = ds*2; s3 = ds*3; m0 = ds; m1 = ds; m2 = ds; m3 = n-s3; // fprintf(stderr,"n, s, m = %d %d %d %d %d %d %d %d\n", // n,s1,s2,s3,m0,m1,m2,m3); #pragma omp parallel #pragma omp sections { #pragma omp section matmul_for_nk8_5(n1,a,n2,b,n3,c,m0); #pragma omp section matmul_for_nk8_5(n1,((double*)a)+s1 ,n2,b,n3,((double*)c)+s1,m1); #pragma omp section matmul_for_nk8_5(n1,((double*)a)+s2 ,n2,b,n3,((double*)c)+s2,m2); #pragma omp section matmul_for_nk8_5(n1,((double*)a)+s3 ,n2,b,n3,((double*)c)+s3,m3); } } static void matmul_for_nk4_3(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int n) { int i,j,k,l; const int m=4; const int mm = 16; double btmp[m][m]; v2df b2tmp[m][m]; double atmp[m][mm]; v2df atmpt[mm/2][m]; for(i=0;i<m;i++)for(j=0;j<m;j++)b2tmp[i][j]=(v2df){b[i][j],b[i][j]}; //#pragma omp parallel for private(j,i,atmp) //use of OMP here does not speed things up for(j=0;j<n;j+=mm){ int jj; for(i=0;i<m;i++){ v2df * dest = (v2df*)(atmp[i]); v2df * src = (v2df*)(a[i]+j); atmpt[ 0][i]=src[0]; atmpt[ 1][i]=src[ 1]; atmpt[ 2][i]=src[ 2]; atmpt[ 3][i]=src[ 3]; atmpt[ 4][i]=src[ 4]; atmpt[ 5][i]=src[ 5]; atmpt[ 6][i]=src[ 6]; atmpt[ 7][i]=src[ 7]; } for(i=0;i<m;i++){ int jjend = mm; if (jjend+j > n) jjend = n-j; v2df* cp = (v2df*)(&c[i][j]); v2df* ap = (v2df*)(atmpt[0]); v2df* cpp = (v2df*)(&c[i][j+2]); v2df* app = (v2df*)(atmpt[1]); v2df* bp = b2tmp[i]; for(jj=0;jj<jjend;jj+=4){ *cp -= ap[0]*bp[0] +ap[1]*bp[1] +ap[2]*bp[2] +ap[3]*bp[3]; *cpp -= app[0]*bp[0] +app[1]*bp[1] +app[2]*bp[2] +app[3]*bp[3]; cp += 2; cpp+= 2; ap += m*2; app+= m*2; } } } } static void matmul_for_nk4_4(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int n) { int i,j,k,l; const int m=4; const int mm = 32; double btmp[m][m]; v2df b2tmp[m][m]; double atmp[m][mm]; for(i=0;i<m;i++)for(j=0;j<m;j++)b2tmp[i][j]=(v2df){b[i][j],b[i][j]}; //#pragma omp parallel for private(j,i,atmp) // use of OMP does not speed things up here... for(j=0;j<n;j+=mm){ int jj; for(i=0;i<m;i++){ v2df * dest = (v2df*)(atmp[i]); v2df * src = (v2df*)(a[i]+j); #if 0 for(k=0;k<mm;k++)atmp[i][k]=a[i][j+k]; #endif #if 0 for(k=0;k<mm/2;k++)dest[k]=src[k]; #endif for(k=0;k<mm/2;k+=2){ dest[k]=src[k]; dest[k+1]=src[k+1]; } } for(i=0;i<m;i++){ int jjend = mm; v2df * bp = b2tmp[i]; if (jjend+j > n) jjend = n-j; for(jj=0;jj<jjend;jj+=2){ v2df* cp = (v2df*)(&c[i][j+jj]); v2df* ap = (v2df*)(atmp[0]+jj); v2df* cpp = (v2df*)(&c[i][j+jj+2]); v2df* app = (v2df*)(atmp[0]+jj+2); *cp -= (*ap)*bp[0] +(*(ap+16))*bp[1] +(*(ap+32))*bp[2] +(*(ap+48))*bp[3]; #if 0 *cpp -= (*app)*bp[0] +(*(app+16))*bp[1] +(*(app+32))*bp[2] +(*(app+48))*bp[3]; #endif } } } } static void matmul_for_nk4_1(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int n) { int i,j,k,l; const int m=4; const int mm = 32; double btmp[m][m]; v2df b2tmp[m][m]; for(i=0;i<m;i++)for(j=0;j<m;j++)b2tmp[i][j]=(v2df){b[i][j],b[i][j]}; #pragma omp parallel for private(j,i) // use of OMP does not speed things up here... for(j=0;j<n;j+=mm){ double atmp[m][mm]; int jj; for(i=0;i<m;i++){ v2df * dest = (v2df*)(atmp[i]); v2df * src = (v2df*)(a[i]+j); #if 0 for(k=0;k<mm;k++)atmp[i][k]=a[i][j+k]; #endif #if 0 for(k=0;k<mm/2;k++)dest[k]=src[k]; #endif for(k=0;k<mm/2;k+=4){ dest[k]=src[k]; dest[k+1]=src[k+1]; dest[k+2]=src[k+2]; dest[k+3]=src[k+3]; } } for(i=0;i<m;i++){ int jjend = mm; v2df * bp = b2tmp[i]; if (jjend+j > n) jjend = n-j; for(jj=0;jj<jjend;jj+=4){ v2df* cp = (v2df*)(&c[i][j+jj]); v2df* ap = (v2df*)(atmp[0]+jj); v2df* cpp = (v2df*)(&c[i][j+jj+2]); v2df* app = (v2df*)(atmp[0]+jj+2); *cp -= (*ap)*bp[0] +(*(ap+16))*bp[1] +(*(ap+32))*bp[2] +(*(ap+48))*bp[3]; *cpp -= (*app)*bp[0] +(*(app+16))*bp[1] +(*(app+32))*bp[2] +(*(app+48))*bp[3]; } } } } static void matmul_for_nk2_0(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int n) { int j,k,l; for(j=0;j<n;j++){ c[0][j] -= a[0][j]*b[0][0]+a[1][j]*b[0][1]; c[1][j] -= a[0][j]*b[1][0]+a[1][j]*b[1][1]; } } static void matmul_for_nk2_1(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int n) { int j,k,l; for(j=0;j<n;j+=2){ c[0][j] -= a[0][j]*b[0][0]+a[1][j]*b[0][1]; c[1][j] -= a[0][j]*b[1][0]+a[1][j]*b[1][1]; c[0][j+1] -= a[0][j+1]*b[0][0]+a[1][j+1]*b[0][1]; c[1][j+1] -= a[0][j+1]*b[1][0]+a[1][j+1]*b[1][1]; } } static void matmul_for_nk2_2(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int n) { int j,k,l; register double b00 = b[0][0]; register double b01 = b[0][1]; register double b10 = b[1][0]; register double b11 = b[1][1]; for(j=0;j<n;j+=2){ c[0][j] -= a[0][j]*b00+a[1][j]*b01; c[0][j+1] -= a[0][j+1]*b00+a[1][j+1]*b01; c[1][j] -= a[0][j]*b10+a[1][j]*b11; c[1][j+1] -= a[0][j+1]*b10+a[1][j+1]*b11; } } static void matmul_for_nk2(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int n) { int j,k,l; register v2df b00 = (v2df){b[0][0],b[0][0]}; register v2df b01 = (v2df){b[0][1],b[0][1]}; register v2df b10 = (v2df){b[1][0],b[1][0]}; register v2df b11 = (v2df){b[1][1],b[1][1]}; v2df * a0 = (v2df*) a[0]; v2df * a1 = (v2df*) a[1]; v2df * c0 = (v2df*) c[0]; v2df * c1 = (v2df*) c[1]; int nh = n>>1; if (nh & 1){ j=nh-1; c0[j] -= a0[j]*b00+a1[j]*b01; c1[j] -= a0[j]*b10+a1[j]*b11; nh = nh-1; } for(j=0;j<nh;j+=2){ c0[j] -= a0[j]*b00+a1[j]*b01; c0[j+1] -= a0[j+1]*b00+a1[j+1]*b01; c1[j] -= a0[j]*b10+a1[j]*b11; c1[j+1] -= a0[j+1]*b10+a1[j+1]*b11; // __builtin_prefetch((double*)&a0[j+32],0); // __builtin_prefetch((double*)&a1[j+32],0); // __builtin_prefetch((double*)&c0[j+32],1); // __builtin_prefetch((double*)&c1[j+32],1); // asm("prefetcht2 %0"::"m"(a0[j+32]):"memory"); // asm("prefetcht2 %0"::"m"(a1[j+32]):"memory"); } } static void matmul_for_nk4_5(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int n) { matmul_for_nk2(n1, a, n2, b, n3,c, n); matmul_for_nk2(n1, (double(*)[]) (a[2]), n2, (double(*)[]) &(b[0][2]), n3,c, n); matmul_for_nk2(n1, a, n2, (double(*)[]) b[2], n3, (double(*)[]) c[2], n); matmul_for_nk2(n1, (double(*)[]) &(a[2]), n2, (double(*)[]) &(b[2][2]), n3, (double(*)[]) c[2], n); } static void matmul_for_nk4_6(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int n) { register v2df b00 = (v2df){b[0][0],b[0][0]}; register v2df b01 = (v2df){b[0][1],b[0][1]}; register v2df b02 = (v2df){b[0][2],b[0][2]}; register v2df b03 = (v2df){b[0][3],b[0][3]}; register v2df b10 = (v2df){b[1][0],b[1][0]}; register v2df b11 = (v2df){b[1][1],b[1][1]}; register v2df b12 = (v2df){b[1][2],b[1][2]}; register v2df b13 = (v2df){b[1][3],b[1][3]}; register v2df b20 = (v2df){b[2][0],b[2][0]}; register v2df b21 = (v2df){b[2][1],b[2][1]}; register v2df b22 = (v2df){b[2][2],b[2][2]}; register v2df b23 = (v2df){b[2][3],b[2][3]}; register v2df b30 = (v2df){b[3][0],b[3][0]}; register v2df b31 = (v2df){b[3][1],b[3][1]}; register v2df b32 = (v2df){b[3][2],b[3][2]}; register v2df b33 = (v2df){b[3][3],b[3][3]}; v2df * a0 = (v2df*) a[0]; v2df * a1 = (v2df*) a[1]; v2df * a2 = (v2df*) a[2]; v2df * a3 = (v2df*) a[3]; v2df * c0 = (v2df*) c[0]; v2df * c1 = (v2df*) c[1]; v2df * c2 = (v2df*) c[2]; v2df * c3 = (v2df*) c[3]; int nh = n>>1; //#pragma omp parallel { //#pragma omp section { int j; //#pragma omp for private (j) for(j=0;j<nh;j++){ c0[j] -= a0[j]*b00+a1[j]*b01+a2[j]*b02+a3[j]*b03; c1[j] -= a0[j]*b10+a1[j]*b11+a2[j]*b12+a3[j]*b13; } } //#pragma omp section { int j; //#pragma omp for private (j) for(j=0;j<nh;j++){ c2[j] -= a0[j]*b20+a1[j]*b21+a2[j]*b22+a3[j]*b23; c3[j] -= a0[j]*b30+a1[j]*b31+a2[j]*b32+a3[j]*b33; } } } } static void matmul_for_nk4_7(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int n) { v2df * a0 = (v2df*) a[0]; v2df * a1 = (v2df*) a[1]; v2df * a2 = (v2df*) a[2]; v2df * a3 = (v2df*) a[3]; int j; { int nh = n>>1; v2df * c0 = (v2df*) c[0]; v2df * c1 = (v2df*) c[1]; v2df b00 = (v2df){b[0][0],b[0][0]}; v2df b01 = (v2df){b[0][1],b[0][1]}; v2df b02 = (v2df){b[0][2],b[0][2]}; v2df b03 = (v2df){b[0][3],b[0][3]}; v2df b10 = (v2df){b[1][0],b[1][0]}; v2df b11 = (v2df){b[1][1],b[1][1]}; v2df b12 = (v2df){b[1][2],b[1][2]}; v2df b13 = (v2df){b[1][3],b[1][3]}; if (nh & 1){ j=nh-1; c0[j] -= a0[j]*b00+a1[j]*b01+a2[j]*b02+a3[j]*b03; c1[j] -= a0[j]*b10+a1[j]*b11+a2[j]*b12+a3[j]*b13; nh--; } for(j=0;j<nh;j+=2){ c0[j] -= a0[j]*b00+a1[j]*b01+a2[j]*b02+a3[j]*b03; c1[j] -= a0[j]*b10+a1[j]*b11+a2[j]*b12+a3[j]*b13; c0[j+1] -= a0[j+1]*b00+a1[j+1]*b01+a2[j+1]*b02+a3[j+1]*b03; c1[j+1] -= a0[j+1]*b10+a1[j+1]*b11+a2[j+1]*b12+a3[j+1]*b13; } } { int nh = n>>1; v2df * c2 = (v2df*) c[2]; v2df * c3 = (v2df*) c[3]; v2df b20 = (v2df){b[2][0],b[2][0]}; v2df b21 = (v2df){b[2][1],b[2][1]}; v2df b22 = (v2df){b[2][2],b[2][2]}; v2df b23 = (v2df){b[2][3],b[2][3]}; register v2df b30 = (v2df){b[3][0],b[3][0]}; register v2df b31 = (v2df){b[3][1],b[3][1]}; register v2df b32 = (v2df){b[3][2],b[3][2]}; register v2df b33 = (v2df){b[3][3],b[3][3]}; for(j=0;j<nh;j++){ c2[j] -= a0[j]*b20+a1[j]*b21+a2[j]*b22+a3[j]*b23; c3[j] -= a0[j]*b30+a1[j]*b31+a2[j]*b32+a3[j]*b33; } } } static void matmul_for_nk4_8(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int n) { v2df * a0 = (v2df*) a[0]; v2df * a1 = (v2df*) a[1]; v2df * a2 = (v2df*) a[2]; v2df * a3 = (v2df*) a[3]; int nh = n>>1; int j; int k; v2df * cv; v2df * cvv; register v2df b0; register v2df b1; register v2df b2; register v2df b3; register v2df b4; register v2df b5; register v2df b6; register v2df b7; for(k=0;k<4;k+=2){ cv = (v2df*) c[k]; cvv = (v2df*) c[k+1]; b0 = (v2df){b[k][0],b[k][0]}; b1 = (v2df){b[k][1],b[k][1]}; b2 = (v2df){b[k][2],b[k][2]}; b3 = (v2df){b[k][3],b[k][3]}; b4 = (v2df){b[k+1][0],b[k+1][0]}; b5 = (v2df){b[k+1][1],b[k+1][1]}; b6 = (v2df){b[k+1][2],b[k+1][2]}; b7 = (v2df){b[k+1][3],b[k+1][3]}; for(j=0;j<nh;j++){ register v2df aa0 = a0[j]; register v2df aa1 = a1[j]; register v2df aa2 = a2[j]; register v2df aa3 = a3[j]; register v2df x = aa0*b0; x+= aa1*b1; x+= aa2*b2; x+= aa3*b3; cv[j]-=x; x = aa0*b4; x+= aa1*b5; x+= aa2*b6; x+= aa3*b7; cvv[j] -= x; } } } static void matmul_for_nk4(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int n) { int m0,m1,m2,m3; int s1, s2, s3; int ds = (n/32)*8; s1 = ds; s2 = ds*2; s3 = ds*3; m0 = ds; m1 = ds; m2 = ds; m3 = n-s3; // fprintf(stderr,"n, s, m = %d %d %d %d %d %d %d %d\n", // n,s1,s2,s3,m0,m1,m2,m3); #pragma omp parallel #pragma omp sections { #pragma omp section matmul_for_nk4_7(n1,a,n2,b,n3,c,m0); #pragma omp section matmul_for_nk4_7(n1,((double*)a)+s1 ,n2,b,n3,((double*)c)+s1,m1); #pragma omp section matmul_for_nk4_7(n1,((double*)a)+s2 ,n2,b,n3,((double*)c)+s2,m2); #pragma omp section matmul_for_nk4_7(n1,((double*)a)+s3 ,n2,b,n3,((double*)c)+s3,m3); } } static void matmul_for_nk8_9(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int n) { matmul_for_nk4(n1, a, n2, b, n3,c, n); matmul_for_nk4(n1, (double(*)[]) (a[4]), n2, (double(*)[]) &(b[0][4]), n3,c, n); matmul_for_nk4(n1, a, n2, (double(*)[]) b[4], n3, (double(*)[]) c[4], n); matmul_for_nk4(n1, (double(*)[]) &(a[4]), n2, (double(*)[]) &(b[4][4]), n3, (double(*)[]) c[4], n); } #if 0 static void matmul_for_nk8(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int n) { int i; int nb=384; for (i=0;i<n;i+=nb){ int iend = i+nb; if (iend > n) iend = n; matmul_for_nk8_worker(n1, (double(*)[]) (a[0]+i), n2, (double(*)[]) (b[0]+i), n3, (double(*)[]) (c[0]+i), iend-i); } } #endif static void matmul_for_small_nk_local(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int kk, int n) { // simplest version int j,k,l; BEGIN_TSC; if (kk == 2){ matmul_for_nk2(n1, a, n2, b, n3,c, n); END_TSC(t,16); return; } if (kk == 4){ matmul_for_nk4(n1, a, n2, b, n3,c, n); END_TSC(t,13); return; } if (kk == 8){ matmul_for_nk8(n1, a, n2, b, n3,c, n); END_TSC(t,12); return; } for(j=0;j<n;j++) for(k=0;k<m;k++) for(l=0;l<kk;l++) c[k][j] -= a[l][j]*b[k][l]; } static void mmmulandsub(int n, double a[n+1][n], int rshift, int m0, int m1, int c0, int c1, int r0,int r1) { int j,k,l; #ifdef TIMETEST BEGIN_TSC; #endif #ifndef NOBLAS if ((m1-m0)<=8){ // =4 is slighly faster than =8 on Ci7 matmul_for_small_nk_local(n, (double(*)[]) &(a[m0-rshift][r0]), n, (double(*)[]) &(a[c0-rshift][m0]), n, (double(*)[]) &(a[c0-rshift][r0]), c1-c0,m1-m0,r1-r0); }else{ cblas_dgemm( CblasColMajor, CblasNoTrans, CblasNoTrans, r1-r0, c1-c0, m1-m0, -1.0, &(a[m0-rshift][r0]), n, &(a[c0-rshift][m0]), n, 1, &(a[c0-rshift][r0]), n ); } // example: // r0, m0 = i+m,i // m0, c0 = i, i+m // r0, c0 = i+m, i+m //r1-r0 = n-i-m // c1-c0 = iend-i-m // m1-m0 = m #else for(j=r0;j<r1;j++) for (k=c0;k<c1;k++) for (l=m0; l<m1; l++) a[k-rshift][j] -= a[l-rshift][j]*a[k-rshift][l]; #endif #ifdef TIMETEST END_TSC(t,4); #endif } static int nswap; static void column_decomposition(int n, double a[][n], int m, int pv[], int i) { // shift a so that partial array is okay int j, k; int ip,ii; double ainv; #ifdef TIMETEST BEGIN_TSC; #endif for(ip=0;ip<m;ip++){ ii=i+ip; int p = findpivot(n,a,ii); pv[ip]=p; swaprows(n,a,p,ii,0,m); nswap++; // normalize row ii ainv = 1.0/a[ip][ii]; scalerow(n,a,ainv,ii,0,ip); scalerow(n,a,ainv,ii,ip+1,m); // subtract row ii from all lower rows vvmulandsub(n, a, ip,ii, ip+1, m, ii+1, n); } #ifdef TIMETEST END_TSC(t,5); #endif } static void process_right_part(int n, double a[n+1][n], int m, int pv[], int i, int iend) { int ii; // exchange rows for(ii=i;ii<i+m;ii++){ swaprows(n,a,pv[ii-i],ii,m,iend-i); } // normalize rows for(ii=i;ii<i+m;ii++){ scalerow(n,a,1.0/a[ii-i][ii] ,ii,m,iend-i); } // subtract rows (within i-i+m-1) for(ii=i;ii<i+m;ii++){ vvmulandsub(n, a, ii-i,ii, m, iend-i, ii+1, i+m); } // subtract rows i-i+m-1 from all lower rows mmmulandsub(n, a, i, i,i+m, i+m, iend, i+m, n); // fprintf(stderr,"process_r, end\n"); // usleep(1); } static void column_decomposition_recursive(int n, double a[n+1][n], int m, int pv[], int i) { int j, k; int ip,ii; double ainv; // fprintf(stderr,"enter t column recursive %d %d\n", i, m); if (m <= 2){ // perform non-recursive direct decomposition column_decomposition(n, a, m, pv,i); }else{ // process the left half by recursion // fprintf(stderr,"call column recursive %d %d\n", i, m); column_decomposition_recursive(n, a, m/2, pv,i); // process the right half // fprintf(stderr,"call right part %d %d\n", i, m); process_right_part(n,a,m/2,pv,i,i+m); // fprintf(stderr,"call right recursive %d %d\n", i, m); column_decomposition_recursive(n, a+m/2, m/2, pv+m/2,i+m/2); // process the swap of rows for the left half // fprintf(stderr,"call swaprowse %d %d\n", i, m); for(ii=i+m/2;ii<i+m;ii++){ swaprows(n,a,pv[ii-i],ii,0,m/2); } // fprintf(stderr,"call scalerows %d %d\n", i, m); // normalize rows for(ii=i+m/2;ii<i+m;ii++){ scalerow(n,a,1.0/a[ii-i][ii] ,ii,0,m/2); } } } void cm_column_decomposition_recursive(int n, double a[n+1][n], int m, int pv[], int i) { column_decomposition_recursive( n, a, m, pv, i); } void cm_column_decomposition(int n, double a[n+1][n], int m, int pv[], int i) { column_decomposition( n, a, m, pv, i); } void cm_process_right_part(int n, double a[n+1][n], int m, int pv[], int i, int iend) { process_right_part(n, a, m, pv, i,iend); }
{ "alphanum_fraction": 0.48862491, "avg_line_length": 24.0311418685, "ext": "c", "hexsha": "bb929044f1b5d873fb51f751e5efaea2c65d29e7", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-12-13T15:31:32.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-13T15:31:32.000Z", "max_forks_repo_head_hexsha": "5c9447c142e91dc03e351d47920a7c5e22126dbf", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jmakino/lu2", "max_forks_repo_path": "lu2tlib.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5c9447c142e91dc03e351d47920a7c5e22126dbf", "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": "jmakino/lu2", "max_issues_repo_path": "lu2tlib.c", "max_line_length": 79, "max_stars_count": 2, "max_stars_repo_head_hexsha": "5c9447c142e91dc03e351d47920a7c5e22126dbf", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jmakino/lu2", "max_stars_repo_path": "lu2tlib.c", "max_stars_repo_stars_event_max_datetime": "2020-05-04T05:00:16.000Z", "max_stars_repo_stars_event_min_datetime": "2017-03-07T09:18:43.000Z", "num_tokens": 12193, "size": 27780 }
/** * * @file example_strsmpl.c * * PLASMA testing routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @brief Example for solving a system of linear equations using * LU factorization and PLASMA_strsmpl routine * * @version 2.6.0 * @author Bilel Hadri * @date 2010-11-15 * @generated s Tue Jan 7 11:45:21 2014 * **/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <plasma.h> #include <cblas.h> #include <lapacke.h> #include <core_blas.h> int check_solution(int, int , float *, int, float *, float *, int); int IONE=1; int ISEED[4] = {0,0,0,1}; /* initial seed for slarnv() */ int main () { int cores = 2; int N = 10; int LDA = 10; int NRHS = 5; int LDB = 10; int info; int info_solution; int i,j; int LDAxN = LDA*N; int LDBxNRHS = LDB*NRHS; float *A1 = (float *)malloc(LDA*N*(sizeof*A1)); float *A2 = (float *)malloc(LDA*N*(sizeof*A2)); float *B1 = (float *)malloc(LDB*NRHS*(sizeof*B1)); float *B2 = (float *)malloc(LDB*NRHS*(sizeof*B2)); PLASMA_desc *L; int *IPIV; /* Check if unable to allocate memory */ if ((!A1)||(!A2)||(!B1)||(!B2)){ printf("Out of Memory \n "); return EXIT_SUCCESS; } /*Plasma Initialize*/ PLASMA_Init(cores); printf("-- PLASMA is initialized to run on %d cores. \n",cores); /* Initialize A1 and A2 Matrix */ LAPACKE_slarnv_work(IONE, ISEED, LDAxN, A1); for ( i = 0; i < N; i++) for ( j = 0; j < N; j++) A2[LDA*j+i] = A1[LDA*j+i]; /* Initialize B1 and B2 */ LAPACKE_slarnv_work(IONE, ISEED, LDBxNRHS, B1); for ( i = 0; i < N; i++) for ( j = 0; j < NRHS; j++) B2[LDB*j+i] = B1[LDB*j+i]; /* Allocate L and IPIV */ info = PLASMA_Alloc_Workspace_sgetrf_incpiv(N, N, &L, &IPIV); /* LU factorization of the matrix A */ info = PLASMA_sgetrf_incpiv(N, N, A2, LDA, L, IPIV); /* Solve the problem */ info = PLASMA_strsmpl(N, NRHS, A2, LDA, L, IPIV, B2, LDB); info = PLASMA_strsm(PlasmaLeft, PlasmaUpper, PlasmaNoTrans, PlasmaNonUnit, N, NRHS, (float)1.0, A2, LDA, B2, LDB); /* Check the solution */ info_solution = check_solution(N, NRHS, A1, LDA, B1, B2, LDB); if ((info_solution != 0)|(info != 0)) printf("-- Error in SGETRS example ! \n"); else printf("-- Run of SGETRS example successful ! \n"); free(A1); free(A2); free(B1); free(B2); free(IPIV); free(L); PLASMA_Finalize(); return EXIT_SUCCESS; } /*------------------------------------------------------------------------ * Check the accuracy of the solution of the linear system */ int check_solution(int N, int NRHS, float *A1, int LDA, float *B1, float *B2, int LDB) { int info_solution; float Rnorm, Anorm, Xnorm, Bnorm; float alpha, beta; float *work = (float *)malloc(N*sizeof(float)); float eps; eps = LAPACKE_slamch_work('e'); alpha = 1.0; beta = -1.0; Xnorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, NRHS, B2, LDB, work); Anorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, N, A1, LDA, work); Bnorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, NRHS, B1, LDB, work); cblas_sgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, N, NRHS, N, (alpha), A1, LDA, B2, LDB, (beta), B1, LDB); Rnorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, NRHS, B1, LDB, work); printf("============\n"); printf("Checking the Residual of the solution \n"); printf("-- ||Ax-B||_oo/((||A||_oo||x||_oo+||B||_oo).N.eps) = %e \n",Rnorm/((Anorm*Xnorm+Bnorm)*N*eps)); if ( isnan(Rnorm/((Anorm*Xnorm+Bnorm)*N*eps)) || (Rnorm/((Anorm*Xnorm+Bnorm)*N*eps) > 10.0) ){ printf("-- The solution is suspicious ! \n"); info_solution = 1; } else{ printf("-- The solution is CORRECT ! \n"); info_solution = 0; } free(work); return info_solution; }
{ "alphanum_fraction": 0.587571977, "avg_line_length": 28.9444444444, "ext": "c", "hexsha": "cfe8fe41f5af12e20920ee06af4d6fc24f90046f", "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": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "examples/example_strsmpl.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "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": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "examples/example_strsmpl.c", "max_line_length": 115, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "examples/example_strsmpl.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1409, "size": 4168 }
#include <stdio.h> #include <gsl/gsl_sf_bessel.h> int main(void) { double x = 5.0; double y = gsl_sf_bessel_J0(x); printf("J0(%g) = %.18e\n", x, y); return 0; }
{ "alphanum_fraction": 0.6094674556, "avg_line_length": 16.9, "ext": "c", "hexsha": "f87c49b4c5263382284660bd7637de98c92f1afd", "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": "0fab83dea364f0a3850c52c8c607908676573a2e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "jbelmont/algorithms-workshop", "max_forks_repo_path": "numericalAnalysis/gnulibrary/bessel.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0fab83dea364f0a3850c52c8c607908676573a2e", "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": "jbelmont/algorithms-workshop", "max_issues_repo_path": "numericalAnalysis/gnulibrary/bessel.c", "max_line_length": 35, "max_stars_count": 2, "max_stars_repo_head_hexsha": "0fab83dea364f0a3850c52c8c607908676573a2e", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "jbelmont/algorithms-workshop", "max_stars_repo_path": "numericalAnalysis/gnulibrary/bessel.c", "max_stars_repo_stars_event_max_datetime": "2019-04-17T01:57:43.000Z", "max_stars_repo_stars_event_min_datetime": "2019-03-23T00:36:34.000Z", "num_tokens": 66, "size": 169 }
#pragma once #include <emerald/util/foundation.h> #define gsl_FEATURE_MAKE_SPAN_TO_STD 20 #include <gsl/gsl-lite.hpp> #include <array> namespace emerald::shallow_weaver { using namespace emerald::util; template <typename T> using span = gsl::span<T>; enum class Time_integration { FIRST_ORDER, RUNGE_KUTTA_2, RUNGE_KUTTA_4 }; using int2 = std::array<int, 2>; using int4 = std::array<int, 4>; using float2 = std::array<float, 2>; using float4 = std::array<float, 4>; } // namespace emerald::shallow_weaver
{ "alphanum_fraction": 0.7392996109, "avg_line_length": 21.4166666667, "ext": "h", "hexsha": "fe9174369d129d812106e2d58f1a7aff29a82641", "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": "3c4823dbdeff7c63007ff359d262608227f5433f", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "blackencino/emerald", "max_forks_repo_path": "emerald/shallow_weaver/foundation.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "3c4823dbdeff7c63007ff359d262608227f5433f", "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": "blackencino/emerald", "max_issues_repo_path": "emerald/shallow_weaver/foundation.h", "max_line_length": 74, "max_stars_count": 3, "max_stars_repo_head_hexsha": "3c4823dbdeff7c63007ff359d262608227f5433f", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "blackencino/emerald", "max_stars_repo_path": "emerald/shallow_weaver/foundation.h", "max_stars_repo_stars_event_max_datetime": "2021-02-25T21:55:39.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-16T17:56:25.000Z", "num_tokens": 148, "size": 514 }
/* * 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 Sun Nov 7 20:43:58 EST 1999 */ #include <fftw-int.h> #include <fftw.h> /* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -real2hc 16 */ /* * This function contains 58 FP additions, 12 FP multiplications, * (or, 54 additions, 8 multiplications, 4 fused multiply/add), * 30 stack variables, and 32 memory accesses */ static const fftw_real K707106781 = FFTW_KONST(+0.707106781186547524400844362104849039284835938); static const fftw_real K923879532 = FFTW_KONST(+0.923879532511286756128183189396788286822416626); static const fftw_real K382683432 = FFTW_KONST(+0.382683432365089771728459984030398866761344562); /* * Generator Id's : * $Id: exprdag.ml,v 1.41 1999/05/26 15:44:14 fftw Exp $ * $Id: fft.ml,v 1.43 1999/05/17 19:44:18 fftw Exp $ * $Id: to_c.ml,v 1.25 1999/10/26 21:41:32 stevenj Exp $ */ void fftw_real2hc_16(const fftw_real *input, fftw_real *real_output, fftw_real *imag_output, int istride, int real_ostride, int imag_ostride) { fftw_real tmp3; fftw_real tmp6; fftw_real tmp7; fftw_real tmp35; fftw_real tmp18; fftw_real tmp33; fftw_real tmp40; fftw_real tmp48; fftw_real tmp56; fftw_real tmp10; fftw_real tmp13; fftw_real tmp14; fftw_real tmp36; fftw_real tmp17; fftw_real tmp26; fftw_real tmp41; fftw_real tmp51; fftw_real tmp57; fftw_real tmp16; fftw_real tmp15; fftw_real tmp43; fftw_real tmp44; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp1; fftw_real tmp2; fftw_real tmp4; fftw_real tmp5; ASSERT_ALIGNED_DOUBLE; tmp1 = input[0]; tmp2 = input[8 * istride]; tmp3 = tmp1 + tmp2; tmp4 = input[4 * istride]; tmp5 = input[12 * istride]; tmp6 = tmp4 + tmp5; tmp7 = tmp3 + tmp6; tmp35 = tmp1 - tmp2; tmp18 = tmp4 - tmp5; } { fftw_real tmp29; fftw_real tmp46; fftw_real tmp32; fftw_real tmp47; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp27; fftw_real tmp28; fftw_real tmp30; fftw_real tmp31; ASSERT_ALIGNED_DOUBLE; tmp27 = input[istride]; tmp28 = input[9 * istride]; tmp29 = tmp27 - tmp28; tmp46 = tmp27 + tmp28; tmp30 = input[5 * istride]; tmp31 = input[13 * istride]; tmp32 = tmp30 - tmp31; tmp47 = tmp30 + tmp31; } tmp33 = (K382683432 * tmp29) + (K923879532 * tmp32); tmp40 = (K923879532 * tmp29) - (K382683432 * tmp32); tmp48 = tmp46 - tmp47; tmp56 = tmp46 + tmp47; } { fftw_real tmp8; fftw_real tmp9; fftw_real tmp11; fftw_real tmp12; ASSERT_ALIGNED_DOUBLE; tmp8 = input[2 * istride]; tmp9 = input[10 * istride]; tmp10 = tmp8 + tmp9; tmp16 = tmp8 - tmp9; tmp11 = input[14 * istride]; tmp12 = input[6 * istride]; tmp13 = tmp11 + tmp12; tmp15 = tmp11 - tmp12; } tmp14 = tmp10 + tmp13; tmp36 = K707106781 * (tmp16 + tmp15); tmp17 = K707106781 * (tmp15 - tmp16); { fftw_real tmp22; fftw_real tmp49; fftw_real tmp25; fftw_real tmp50; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp20; fftw_real tmp21; fftw_real tmp23; fftw_real tmp24; ASSERT_ALIGNED_DOUBLE; tmp20 = input[15 * istride]; tmp21 = input[7 * istride]; tmp22 = tmp20 - tmp21; tmp49 = tmp20 + tmp21; tmp23 = input[3 * istride]; tmp24 = input[11 * istride]; tmp25 = tmp23 - tmp24; tmp50 = tmp23 + tmp24; } tmp26 = (K382683432 * tmp22) - (K923879532 * tmp25); tmp41 = (K923879532 * tmp22) + (K382683432 * tmp25); tmp51 = tmp49 - tmp50; tmp57 = tmp49 + tmp50; } { fftw_real tmp55; fftw_real tmp58; fftw_real tmp53; fftw_real tmp54; ASSERT_ALIGNED_DOUBLE; real_output[4 * real_ostride] = tmp7 - tmp14; tmp55 = tmp7 + tmp14; tmp58 = tmp56 + tmp57; real_output[8 * real_ostride] = tmp55 - tmp58; real_output[0] = tmp55 + tmp58; imag_output[4 * imag_ostride] = tmp57 - tmp56; tmp53 = tmp13 - tmp10; tmp54 = K707106781 * (tmp51 - tmp48); imag_output[2 * imag_ostride] = tmp53 + tmp54; imag_output[6 * imag_ostride] = tmp54 - tmp53; } { fftw_real tmp45; fftw_real tmp52; fftw_real tmp39; fftw_real tmp42; ASSERT_ALIGNED_DOUBLE; tmp45 = tmp3 - tmp6; tmp52 = K707106781 * (tmp48 + tmp51); real_output[6 * real_ostride] = tmp45 - tmp52; real_output[2 * real_ostride] = tmp45 + tmp52; tmp39 = tmp35 + tmp36; tmp42 = tmp40 + tmp41; real_output[7 * real_ostride] = tmp39 - tmp42; real_output[real_ostride] = tmp39 + tmp42; } tmp43 = tmp18 + tmp17; tmp44 = tmp41 - tmp40; imag_output[3 * imag_ostride] = tmp43 + tmp44; imag_output[5 * imag_ostride] = tmp44 - tmp43; { fftw_real tmp19; fftw_real tmp34; fftw_real tmp37; fftw_real tmp38; ASSERT_ALIGNED_DOUBLE; tmp19 = tmp17 - tmp18; tmp34 = tmp26 - tmp33; imag_output[imag_ostride] = tmp19 + tmp34; imag_output[7 * imag_ostride] = tmp34 - tmp19; tmp37 = tmp35 - tmp36; tmp38 = tmp33 + tmp26; real_output[5 * real_ostride] = tmp37 - tmp38; real_output[3 * real_ostride] = tmp37 + tmp38; } } fftw_codelet_desc fftw_real2hc_16_desc = { "fftw_real2hc_16", (void (*)()) fftw_real2hc_16, 16, FFTW_FORWARD, FFTW_REAL2HC, 354, 0, (const int *) 0, };
{ "alphanum_fraction": 0.6448850119, "avg_line_length": 28.7899543379, "ext": "c", "hexsha": "aa82ddaab6e1562b0f5256aa5e855e1e8840569e", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-29T02:59:10.000Z", "max_forks_repo_forks_event_min_datetime": "2017-11-20T07:52:01.000Z", "max_forks_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "albertsgrc/ftdock-opt", "max_forks_repo_path": "original/lib/fftw-2.1.3/rfftw/frc_16.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "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": "albertsgrc/ftdock-opt", "max_issues_repo_path": "original/lib/fftw-2.1.3/rfftw/frc_16.c", "max_line_length": 141, "max_stars_count": 9, "max_stars_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "albertsgrc/ftdock-opt", "max_stars_repo_path": "original/lib/fftw-2.1.3/rfftw/frc_16.c", "max_stars_repo_stars_event_max_datetime": "2022-01-08T14:37:24.000Z", "max_stars_repo_stars_event_min_datetime": "2018-10-03T19:57:47.000Z", "num_tokens": 2055, "size": 6305 }
/* specfunc/legendre_Qn.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., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include "gsl_sf_bessel.h" #include "gsl_sf_elementary.h" #include "gsl_sf_exp.h" #include "gsl_sf_pow_int.h" #include "gsl_sf_legendre.h" #include "error.h" /* Evaluate f_{ell+1}/f_ell * f_ell := Q^{b}_{a+ell}(x) * x > 1 */ static int legendreQ_CF1_xgt1(int ell, double a, double b, double x, double * result) { const double RECUR_BIG = GSL_SQRT_DBL_MAX; const int maxiter = 5000; int n = 1; double Anm2 = 1.0; double Bnm2 = 0.0; double Anm1 = 0.0; double Bnm1 = 1.0; double a1 = ell + 1.0 + a + b; double b1 = (2.0*(ell+1.0+a) + 1.0) * x; double An = b1*Anm1 + a1*Anm2; double Bn = b1*Bnm1 + a1*Bnm2; double an, bn; double fn = An/Bn; while(n < maxiter) { double old_fn; double del; double lna; n++; Anm2 = Anm1; Bnm2 = Bnm1; Anm1 = An; Bnm1 = Bn; lna = ell + n + a; an = b*b - lna*lna; bn = (2.0*lna + 1.0) * x; An = bn*Anm1 + an*Anm2; Bn = bn*Bnm1 + an*Bnm2; if(fabs(An) > RECUR_BIG || fabs(Bn) > RECUR_BIG) { An /= RECUR_BIG; Bn /= RECUR_BIG; Anm1 /= RECUR_BIG; Bnm1 /= RECUR_BIG; Anm2 /= RECUR_BIG; Bnm2 /= RECUR_BIG; } old_fn = fn; fn = An/Bn; del = old_fn/fn; if(fabs(del - 1.0) < 4.0*GSL_DBL_EPSILON) break; } *result = fn; if(n == maxiter) GSL_ERROR ("error", GSL_EMAXITER); else return GSL_SUCCESS; } /* Uniform asymptotic for Q_l(x). * Assumes x > -1.0 and x != 1.0. * Discards second order and higher terms. */ static int legendre_Ql_asymp_unif(const double ell, const double x, gsl_sf_result * result) { if(x < 1.0) { double u = ell + 0.5; double th = acos(x); gsl_sf_result Y0, Y1; int stat_Y0, stat_Y1; int stat_m; double pre; double B00; double sum; /* B00 = 1/8 (1 - th cot(th) / th^2 * pre = sqrt(th/sin(th)) */ if(th < GSL_ROOT4_DBL_EPSILON) { B00 = (1.0 + th*th/15.0)/24.0; pre = 1.0 + th*th/12.0; } else { double sin_th = sqrt(1.0 - x*x); double cot_th = x / sin_th; B00 = 1.0/8.0 * (1.0 - th * cot_th) / (th*th); pre = sqrt(th/sin_th); } stat_Y0 = gsl_sf_bessel_Y0_e(u*th, &Y0); stat_Y1 = gsl_sf_bessel_Y1_e(u*th, &Y1); sum = -0.5*M_PI * (Y0.val + th/u * Y1.val * B00); stat_m = gsl_sf_multiply_e(pre, sum, result); result->err += 0.5*M_PI * fabs(pre) * (Y0.err + fabs(th/u*B00)*Y1.err); result->err += GSL_DBL_EPSILON * fabs(result->val); return GSL_ERROR_SELECT_3(stat_m, stat_Y0, stat_Y1); } else { double u = ell + 0.5; double xi = acosh(x); gsl_sf_result K0_scaled, K1_scaled; int stat_K0, stat_K1; int stat_e; double pre; double B00; double sum; /* B00 = -1/8 (1 - xi coth(xi) / xi^2 * pre = sqrt(xi/sinh(xi)) */ if(xi < GSL_ROOT4_DBL_EPSILON) { B00 = (1.0-xi*xi/15.0)/24.0; pre = 1.0 - xi*xi/12.0; } else { double sinh_xi = sqrt(x*x - 1.0); double coth_xi = x / sinh_xi; B00 = -1.0/8.0 * (1.0 - xi * coth_xi) / (xi*xi); pre = sqrt(xi/sinh_xi); } stat_K0 = gsl_sf_bessel_K0_scaled_e(u*xi, &K0_scaled); stat_K1 = gsl_sf_bessel_K1_scaled_e(u*xi, &K1_scaled); sum = K0_scaled.val - xi/u * K1_scaled.val * B00; stat_e = gsl_sf_exp_mult_e(-u*xi, pre * sum, result); result->err = GSL_DBL_EPSILON * fabs(result->val) * fabs(u*xi); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_ERROR_SELECT_3(stat_e, stat_K0, stat_K1); } } /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_legendre_Q0_e(const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x <= -1.0 || x == 1.0) { DOMAIN_ERROR(result); } else if(x*x < GSL_ROOT6_DBL_EPSILON) { /* |x| <~ 0.05 */ const double c3 = 1.0/3.0; const double c5 = 1.0/5.0; const double c7 = 1.0/7.0; const double c9 = 1.0/9.0; const double c11 = 1.0/11.0; const double y = x * x; const double series = 1.0 + y*(c3 + y*(c5 + y*(c7 + y*(c9 + y*c11)))); result->val = x * series; result->err = 2.0 * GSL_DBL_EPSILON * fabs(x); return GSL_SUCCESS; } else if(x < 1.0) { result->val = 0.5 * log((1.0+x)/(1.0-x)); result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x < 10.0) { result->val = 0.5 * log((x+1.0)/(x-1.0)); result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x*GSL_DBL_MIN < 2.0) { const double y = 1.0/(x*x); const double c1 = 1.0/3.0; const double c2 = 1.0/5.0; const double c3 = 1.0/7.0; const double c4 = 1.0/9.0; const double c5 = 1.0/11.0; const double c6 = 1.0/13.0; const double c7 = 1.0/15.0; result->val = (1.0/x) * (1.0 + y*(c1 + y*(c2 + y*(c3 + y*(c4 + y*(c5 + y*(c6 + y*c7))))))); result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { UNDERFLOW_ERROR(result); } } int gsl_sf_legendre_Q1_e(const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x <= -1.0 || x == 1.0) { DOMAIN_ERROR(result); } else if(x*x < GSL_ROOT6_DBL_EPSILON) { /* |x| <~ 0.05 */ const double c3 = 1.0/3.0; const double c5 = 1.0/5.0; const double c7 = 1.0/7.0; const double c9 = 1.0/9.0; const double c11 = 1.0/11.0; const double y = x * x; const double series = 1.0 + y*(c3 + y*(c5 + y*(c7 + y*(c9 + y*c11)))); result->val = x * x * series - 1.0; result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x < 1.0){ result->val = 0.5 * x * (log((1.0+x)/(1.0-x))) - 1.0; result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x < 6.0) { result->val = 0.5 * x * log((x+1.0)/(x-1.0)) - 1.0; result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x*GSL_SQRT_DBL_MIN < 0.99/M_SQRT3) { const double y = 1/(x*x); const double c1 = 3.0/5.0; const double c2 = 3.0/7.0; const double c3 = 3.0/9.0; const double c4 = 3.0/11.0; const double c5 = 3.0/13.0; const double c6 = 3.0/15.0; const double c7 = 3.0/17.0; const double c8 = 3.0/19.0; const double sum = 1.0 + y*(c1 + y*(c2 + y*(c3 + y*(c4 + y*(c5 + y*(c6 + y*(c7 + y*c8))))))); result->val = sum / (3.0*x*x); result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { UNDERFLOW_ERROR(result); } } int gsl_sf_legendre_Ql_e(const int l, const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x <= -1.0 || x == 1.0 || l < 0) { DOMAIN_ERROR(result); } else if(l == 0) { return gsl_sf_legendre_Q0_e(x, result); } else if(l == 1) { return gsl_sf_legendre_Q1_e(x, result); } else if(l > 100000) { return legendre_Ql_asymp_unif(l, x, result); } else if(x < 1.0){ /* Forward recurrence. */ gsl_sf_result Q0, Q1; int stat_Q0 = gsl_sf_legendre_Q0_e(x, &Q0); int stat_Q1 = gsl_sf_legendre_Q1_e(x, &Q1); double Qellm1 = Q0.val; double Qell = Q1.val; double Qellp1; int ell; for(ell=1; ell<l; ell++) { Qellp1 = (x*(2.0*ell + 1.0) * Qell - ell * Qellm1) / (ell + 1.0); Qellm1 = Qell; Qell = Qellp1; } result->val = Qell; result->err = GSL_DBL_EPSILON * l * fabs(result->val); return GSL_ERROR_SELECT_2(stat_Q0, stat_Q1); } else { /* x > 1.0 */ double rat; int stat_CF1 = legendreQ_CF1_xgt1(l, 0.0, 0.0, x, &rat); int stat_Q; double Qellp1 = rat * GSL_SQRT_DBL_MIN; double Qell = GSL_SQRT_DBL_MIN; double Qellm1; int ell; for(ell=l; ell>0; ell--) { Qellm1 = (x * (2.0*ell + 1.0) * Qell - (ell+1.0) * Qellp1) / ell; Qellp1 = Qell; Qell = Qellm1; } if(fabs(Qell) > fabs(Qellp1)) { gsl_sf_result Q0; stat_Q = gsl_sf_legendre_Q0_e(x, &Q0); result->val = GSL_SQRT_DBL_MIN * Q0.val / Qell; result->err = l * GSL_DBL_EPSILON * fabs(result->val); } else { gsl_sf_result Q1; stat_Q = gsl_sf_legendre_Q1_e(x, &Q1); result->val = GSL_SQRT_DBL_MIN * Q1.val / Qellp1; result->err = l * GSL_DBL_EPSILON * fabs(result->val); } return GSL_ERROR_SELECT_2(stat_Q, stat_CF1); } } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_legendre_Q0(const double x) { EVAL_RESULT(gsl_sf_legendre_Q0_e(x, &result)); } double gsl_sf_legendre_Q1(const double x) { EVAL_RESULT(gsl_sf_legendre_Q1_e(x, &result)); } double gsl_sf_legendre_Ql(const int l, const double x) { EVAL_RESULT(gsl_sf_legendre_Ql_e(l, x, &result)); }
{ "alphanum_fraction": 0.5819553535, "avg_line_length": 26.3651226158, "ext": "c", "hexsha": "5b12356bd5d98fe4bb46180f7847621b0f1db45a", "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/specfunc/legendre_Qn.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/specfunc/legendre_Qn.c", "max_line_length": 97, "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/specfunc/legendre_Qn.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": 3660, "size": 9676 }
/* * 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 Sun Nov 7 20:44:26 EST 1999 */ #include <fftw-int.h> #include <fftw.h> /* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -hc2real 15 */ /* * This function contains 64 FP additions, 31 FP multiplications, * (or, 47 additions, 14 multiplications, 17 fused multiply/add), * 36 stack variables, and 30 memory accesses */ static const fftw_real K1_118033988 = FFTW_KONST(+1.118033988749894848204586834365638117720309180); static const fftw_real K1_902113032 = FFTW_KONST(+1.902113032590307144232878666758764286811397268); static const fftw_real K1_175570504 = FFTW_KONST(+1.175570504584946258337411909278145537195304875); static const fftw_real K500000000 = FFTW_KONST(+0.500000000000000000000000000000000000000000000); static const fftw_real K866025403 = FFTW_KONST(+0.866025403784438646763723170752936183471402627); static const fftw_real K2_000000000 = FFTW_KONST(+2.000000000000000000000000000000000000000000000); static const fftw_real K1_732050807 = FFTW_KONST(+1.732050807568877293527446341505872366942805254); /* * Generator Id's : * $Id: exprdag.ml,v 1.41 1999/05/26 15:44:14 fftw Exp $ * $Id: fft.ml,v 1.43 1999/05/17 19:44:18 fftw Exp $ * $Id: to_c.ml,v 1.25 1999/10/26 21:41:32 stevenj Exp $ */ void fftw_hc2real_15(const fftw_real *real_input, const fftw_real *imag_input, fftw_real *output, int real_istride, int imag_istride, int ostride) { fftw_real tmp3; fftw_real tmp30; fftw_real tmp18; fftw_real tmp37; fftw_real tmp61; fftw_real tmp62; fftw_real tmp45; fftw_real tmp40; fftw_real tmp23; fftw_real tmp31; fftw_real tmp42; fftw_real tmp28; fftw_real tmp32; fftw_real tmp8; fftw_real tmp13; fftw_real tmp14; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp17; fftw_real tmp1; fftw_real tmp2; fftw_real tmp15; fftw_real tmp16; ASSERT_ALIGNED_DOUBLE; tmp16 = imag_input[5 * imag_istride]; tmp17 = K1_732050807 * tmp16; tmp1 = real_input[0]; tmp2 = real_input[5 * real_istride]; tmp15 = tmp1 - tmp2; tmp3 = tmp1 + (K2_000000000 * tmp2); tmp30 = tmp15 - tmp17; tmp18 = tmp15 + tmp17; } { fftw_real tmp4; fftw_real tmp39; fftw_real tmp5; fftw_real tmp6; fftw_real tmp7; fftw_real tmp22; fftw_real tmp38; fftw_real tmp9; fftw_real tmp44; fftw_real tmp10; fftw_real tmp11; fftw_real tmp12; fftw_real tmp27; fftw_real tmp43; fftw_real tmp19; fftw_real tmp24; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp20; fftw_real tmp21; fftw_real tmp25; fftw_real tmp26; ASSERT_ALIGNED_DOUBLE; tmp4 = real_input[3 * real_istride]; tmp39 = imag_input[3 * imag_istride]; tmp5 = real_input[7 * real_istride]; tmp6 = real_input[2 * real_istride]; tmp7 = tmp5 + tmp6; tmp20 = imag_input[7 * imag_istride]; tmp21 = imag_input[2 * imag_istride]; tmp22 = K866025403 * (tmp20 - tmp21); tmp38 = tmp20 + tmp21; tmp9 = real_input[6 * real_istride]; tmp44 = imag_input[6 * imag_istride]; tmp10 = real_input[4 * real_istride]; tmp11 = real_input[real_istride]; tmp12 = tmp10 + tmp11; tmp25 = imag_input[4 * imag_istride]; tmp26 = imag_input[imag_istride]; tmp27 = K866025403 * (tmp25 + tmp26); tmp43 = tmp25 - tmp26; } tmp37 = K866025403 * (tmp5 - tmp6); tmp61 = tmp39 - tmp38; tmp62 = tmp44 - tmp43; tmp45 = (K500000000 * tmp43) + tmp44; tmp40 = (K500000000 * tmp38) + tmp39; tmp19 = tmp4 - (K500000000 * tmp7); tmp23 = tmp19 - tmp22; tmp31 = tmp19 + tmp22; tmp42 = K866025403 * (tmp10 - tmp11); tmp24 = tmp9 - (K500000000 * tmp12); tmp28 = tmp24 - tmp27; tmp32 = tmp24 + tmp27; tmp8 = tmp4 + tmp7; tmp13 = tmp9 + tmp12; tmp14 = tmp8 + tmp13; } output[0] = tmp3 + (K2_000000000 * tmp14); { fftw_real tmp63; fftw_real tmp65; fftw_real tmp60; fftw_real tmp64; fftw_real tmp58; fftw_real tmp59; ASSERT_ALIGNED_DOUBLE; tmp63 = (K1_175570504 * tmp61) - (K1_902113032 * tmp62); tmp65 = (K1_902113032 * tmp61) + (K1_175570504 * tmp62); tmp58 = tmp3 - (K500000000 * tmp14); tmp59 = K1_118033988 * (tmp8 - tmp13); tmp60 = tmp58 - tmp59; tmp64 = tmp59 + tmp58; output[12 * ostride] = tmp60 - tmp63; output[3 * ostride] = tmp60 + tmp63; output[6 * ostride] = tmp64 - tmp65; output[9 * ostride] = tmp64 + tmp65; } { fftw_real tmp51; fftw_real tmp29; fftw_real tmp50; fftw_real tmp55; fftw_real tmp57; fftw_real tmp53; fftw_real tmp54; fftw_real tmp56; fftw_real tmp52; ASSERT_ALIGNED_DOUBLE; tmp51 = K1_118033988 * (tmp23 - tmp28); tmp29 = tmp23 + tmp28; tmp50 = tmp18 - (K500000000 * tmp29); tmp53 = tmp40 - tmp37; tmp54 = tmp45 - tmp42; tmp55 = (K1_175570504 * tmp53) - (K1_902113032 * tmp54); tmp57 = (K1_902113032 * tmp53) + (K1_175570504 * tmp54); output[5 * ostride] = tmp18 + (K2_000000000 * tmp29); tmp56 = tmp51 + tmp50; output[11 * ostride] = tmp56 - tmp57; output[14 * ostride] = tmp56 + tmp57; tmp52 = tmp50 - tmp51; output[2 * ostride] = tmp52 - tmp55; output[8 * ostride] = tmp52 + tmp55; } { fftw_real tmp35; fftw_real tmp33; fftw_real tmp34; fftw_real tmp47; fftw_real tmp49; fftw_real tmp41; fftw_real tmp46; fftw_real tmp48; fftw_real tmp36; ASSERT_ALIGNED_DOUBLE; tmp35 = K1_118033988 * (tmp31 - tmp32); tmp33 = tmp31 + tmp32; tmp34 = tmp30 - (K500000000 * tmp33); tmp41 = tmp37 + tmp40; tmp46 = tmp42 + tmp45; tmp47 = (K1_175570504 * tmp41) - (K1_902113032 * tmp46); tmp49 = (K1_902113032 * tmp41) + (K1_175570504 * tmp46); output[10 * ostride] = tmp30 + (K2_000000000 * tmp33); tmp48 = tmp35 + tmp34; output[ostride] = tmp48 - tmp49; output[4 * ostride] = tmp48 + tmp49; tmp36 = tmp34 - tmp35; output[7 * ostride] = tmp36 - tmp47; output[13 * ostride] = tmp36 + tmp47; } } fftw_codelet_desc fftw_hc2real_15_desc = { "fftw_hc2real_15", (void (*)()) fftw_hc2real_15, 15, FFTW_BACKWARD, FFTW_HC2REAL, 345, 0, (const int *) 0, };
{ "alphanum_fraction": 0.6657330906, "avg_line_length": 31.4581497797, "ext": "c", "hexsha": "6cc9acb7c1099ef690ba91a0883a336b3d21acb0", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-29T02:59:10.000Z", "max_forks_repo_forks_event_min_datetime": "2017-11-20T07:52:01.000Z", "max_forks_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "albertsgrc/ftdock-opt", "max_forks_repo_path": "original/lib/fftw-2.1.3/rfftw/fcr_15.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "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": "albertsgrc/ftdock-opt", "max_issues_repo_path": "original/lib/fftw-2.1.3/rfftw/fcr_15.c", "max_line_length": 146, "max_stars_count": 9, "max_stars_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "albertsgrc/ftdock-opt", "max_stars_repo_path": "original/lib/fftw-2.1.3/rfftw/fcr_15.c", "max_stars_repo_stars_event_max_datetime": "2022-01-08T14:37:24.000Z", "max_stars_repo_stars_event_min_datetime": "2018-10-03T19:57:47.000Z", "num_tokens": 2447, "size": 7141 }
/* dht/dht.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., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: G. Jungman */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_sf_bessel.h> #include "gsl_dht.h" gsl_dht * gsl_dht_alloc (size_t size) { gsl_dht * t; if(size == 0) { GSL_ERROR_VAL("size == 0", GSL_EDOM, 0); } t = (gsl_dht *)malloc(sizeof(gsl_dht)); if(t == 0) { GSL_ERROR_VAL("out of memory", GSL_ENOMEM, 0); } t->size = size; t->xmax = -1.0; /* Make it clear that this needs to be calculated. */ t->nu = -1.0; t->j = (double *)malloc((size+2)*sizeof(double)); if(t->j == 0) { free(t); GSL_ERROR_VAL("could not allocate memory for j", GSL_ENOMEM, 0); } t->Jjj = (double *)malloc(size*(size+1)/2 * sizeof(double)); if(t->Jjj == 0) { free(t->j); free(t); GSL_ERROR_VAL("could not allocate memory for Jjj", GSL_ENOMEM, 0); } t->J2 = (double *)malloc((size+1)*sizeof(double)); if(t->J2 == 0) { free(t->Jjj); free(t->j); free(t); GSL_ERROR_VAL("could not allocate memory for J2", GSL_ENOMEM, 0); } return t; } /* Handle internal calculation of Bessel zeros. */ static int dht_bessel_zeros(gsl_dht * t) { unsigned int s; gsl_sf_result z; int stat_z = 0; t->j[0] = 0.0; for(s=1; s < t->size + 2; s++) { stat_z += gsl_sf_bessel_zero_Jnu_e(t->nu, s, &z); t->j[s] = z.val; } if(stat_z != 0) { GSL_ERROR("could not compute bessel zeroes", GSL_EFAILED); } else { return GSL_SUCCESS; } } gsl_dht * gsl_dht_new (size_t size, double nu, double xmax) { int status; gsl_dht * dht = gsl_dht_alloc (size); if (dht == 0) return 0; status = gsl_dht_init(dht, nu, xmax); if (status) return 0; return dht; } int gsl_dht_init(gsl_dht * t, double nu, double xmax) { if(xmax <= 0.0) { GSL_ERROR ("xmax is not positive", GSL_EDOM); } else if(nu < 0.0) { GSL_ERROR ("nu is negative", GSL_EDOM); } else { size_t n, m; int stat_bz = GSL_SUCCESS; int stat_J = 0; double jN; if(nu != t->nu) { /* Recalculate Bessel zeros if necessary. */ t->nu = nu; stat_bz = dht_bessel_zeros(t); } jN = t->j[t->size+1]; t->xmax = xmax; t->kmax = jN / xmax; t->J2[0] = 0.0; for(m=1; m<t->size+1; m++) { gsl_sf_result J; stat_J += gsl_sf_bessel_Jnu_e(nu + 1.0, t->j[m], &J); t->J2[m] = J.val * J.val; } /* J_nu(j[n] j[m] / j[N]) = Jjj[n(n-1)/2 + m - 1], 1 <= n,m <= size */ for(n=1; n<t->size+1; n++) { for(m=1; m<=n; m++) { double arg = t->j[n] * t->j[m] / jN; gsl_sf_result J; stat_J += gsl_sf_bessel_Jnu_e(nu, arg, &J); t->Jjj[n*(n-1)/2 + m - 1] = J.val; } } if(stat_J != 0) { GSL_ERROR("error computing bessel function", GSL_EFAILED); } else { return stat_bz; } } } double gsl_dht_x_sample(const gsl_dht * t, int n) { return t->j[n+1]/t->j[t->size+1] * t->xmax; } double gsl_dht_k_sample(const gsl_dht * t, int n) { return t->j[n+1] / t->xmax; } void gsl_dht_free(gsl_dht * t) { free(t->J2); free(t->Jjj); free(t->j); free(t); } int gsl_dht_apply(const gsl_dht * t, double * f_in, double * f_out) { const double jN = t->j[t->size + 1]; const double r = t->xmax / jN; size_t m; size_t i; for(m=0; m<t->size; m++) { double sum = 0.0; double Y; for(i=0; i<t->size; i++) { /* Need to find max and min so that we * address the symmetric Jjj matrix properly. * FIXME: we can presumably optimize this * by just running over the elements of Jjj * in a deterministic manner. */ size_t m_local; size_t n_local; if(i < m) { m_local = i; n_local = m; } else { m_local = m; n_local = i; } Y = t->Jjj[n_local*(n_local+1)/2 + m_local] / t->J2[i+1]; sum += Y * f_in[i]; } f_out[m] = sum * 2.0 * r*r; } return GSL_SUCCESS; }
{ "alphanum_fraction": 0.5773195876, "avg_line_length": 21.0309734513, "ext": "c", "hexsha": "b82266c70cc09650b4b8c99fdf2b7b411fcbfc10", "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/dht/dht.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/dht/dht.c", "max_line_length": 72, "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/dht/dht.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": 1626, "size": 4753 }
/* ODE: a program to get optime Runge-Kutta and multi-steps methods. Copyright 2011-2019, Javier Burguete Tolosa. 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. THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``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 Javier Burguete Tolosa 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. */ /** * \file rk.c * \brief Source file with common variables and functions to optimize * Runge-Kutta methods. * \author Javier Burguete Tolosa. * \copyright Copyright 2011-2019. */ #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> #include <float.h> #include <math.h> #include <libxml/parser.h> #include <glib.h> #include <libintl.h> #include <gsl/gsl_rng.h> #if HAVE_MPI #include <mpi.h> #endif #include "config.h" #include "utils.h" #include "optimize.h" #include "rk.h" #include "rk_2_2.h" #include "rk_3_2.h" #include "rk_3_3.h" #include "rk_4_2.h" #include "rk_4_3.h" #include "rk_4_4.h" #include "rk_5_2.h" #include "rk_5_3.h" #include "rk_5_4.h" #include "rk_6_2.h" #include "rk_6_3.h" #include "rk_6_4.h" #define DEBUG_RK 0 ///< macro to debug. /** * Function to print the t-b Runge-Kutta coefficients. */ void rk_print_tb (Optimize * tb, ///< Optimize struct. char *label, ///< label. FILE * file) ///< file. { long double *x; unsigned int i, j, k; x = tb->coefficient; fprintf (file, "%s: t1=%.19Le\n", label, x[0]); for (i = 2, k = 0; i <= tb->nsteps; ++i) { fprintf (file, "%s: t%u=%.19Le\n", label, i, x[++k]); for (j = 0; j < i; ++j) fprintf (file, "%s: b%u%u=%.19Le\n", label, i, j, x[++k]); } } /** * Function to print the e Runge-Kutta coefficients. */ void rk_print_e (Optimize * tb, ///< Optimize struct. char *label, ///< label. FILE * file) ///< file. { long double *x; unsigned int i, k, nsteps; x = tb->coefficient; nsteps = tb->nsteps; k = (nsteps + 2) * (nsteps + 1) / 2 - 2; for (i = 0; i < nsteps - 1; ++i) fprintf (file, "%s: e%u%u=%.19Le\n", label, nsteps, i, x[k++]); } /** * Function to print in a maxima file the Runge-Kutta coefficients. */ static void rk_print (RK * rk, ///< RK struct. FILE * file) ///< file. { Optimize *tb, *ac; long double *x, *y; unsigned int i, j, k, l, nsteps; tb = rk->tb; ac = rk->ac; x = tb->coefficient; y = ac->coefficient; fprintf (file, "t1:%.19Le;\n", x[0]); nsteps = tb->nsteps; for (i = 2, k = l = 0; i <= nsteps; ++i) { fprintf (file, "t%u:%.19Le;\n", i, x[++k]); for (j = 0; j < i; ++j) fprintf (file, "b%u%u:%.19Le;\n", i, j, x[++k]); if (!rk->strong) continue; for (j = 0; j < i; ++j) fprintf (file, "a%u%u:%.19Le;\n", i, j, y[l++]); for (j = 0; j < i; ++j) fprintf (file, "c%u%u:%.19Le;\n", i, j, y[l++]); } if (rk->pair) for (i = 0; i < nsteps - 1; ++i) fprintf (file, "e%u%u:%.19Le;\n", nsteps, i, x[++k]); } /** * Function to print a maxima format file to check the accuracy order of the * Runge-Kutta simple stable methods. */ static void rk_print_maxima (FILE * file, ///< file. unsigned int nsteps, ///< steps number. unsigned int ncoefficients, ///< coefficients number. unsigned int order, ///< accuracy order. char label) ///< coefficient label. { unsigned int i, j, k, l; // b_{ij}=1 (1st order) for (i = 0; i < ncoefficients; ++i) fprintf (file, "%c%u%u+", label, nsteps, i); fprintf (file, "-1;\n"); // b_{ij}t_j=1/2 (2nd order) for (i = 1; i < ncoefficients; ++i) fprintf (file, "%c%u%u*t%u+", label, nsteps, i, i); fprintf (file, "-1/2;\n"); if (order < 2) return; // b_{ij}t_j^2=1/3 (3rd order) for (i = 1; i < ncoefficients; ++i) fprintf (file, "%c%u%u*t%u^2+", label, nsteps, i, i); fprintf (file, "-1/3;\n"); if (order < 3) return; // b_{ij}b_{jk}t_k=1/6 (3rd order) for (i = 2; i < ncoefficients; ++i) { fprintf (file, "%c%u%u*(", label, nsteps, i); for (j = 1; j < i; ++j) fprintf (file, "b%u%u*t%u+", i, j, j); fprintf (file, "0)+"); } fprintf (file, "-1/6;\n"); // b_{ij}t_j^3=1/4 (4th order) for (i = 1; i < ncoefficients; ++i) fprintf (file, "%c%u%u*t%u^3+", label, nsteps, i, i); fprintf (file, "-1/4;\n"); if (order < 4) return; // b_{ij}b_{jk}b_{kl}t_l=1/24 (4th order) for (i = 3; i < ncoefficients; ++i) { fprintf (file, "%c%u%u*(", label, nsteps, i); for (j = 2; j < i; ++j) { fprintf (file, "b%u%u*(", i, j); for (k = 1; k < j; ++k) fprintf (file, "b%u%u*t%u+", j, k, k); fprintf (file, "0)+"); } fprintf (file, "0)+"); } fprintf (file, "-1/24;\n"); // b_{ij}b_{jk}t_k^2=1/12 (4th order) for (i = 2; i < ncoefficients; ++i) { fprintf (file, "%c%u%u*(", label, nsteps, i); for (j = 1; j < i; ++j) fprintf (file, "b%u%u*t%u^2+", i, j, j); fprintf (file, "0)+"); } fprintf (file, "-1/12;\n"); // b_{ij}t_jb_{jk}t_k=1/8 (4th order) for (i = 2; i < ncoefficients; ++i) { fprintf (file, "%c%u%u*t%u*(", label, nsteps, i, i); for (j = 1; j < i; ++j) fprintf (file, "b%u%u*t%u+", i, j, j); fprintf (file, "0)+"); } fprintf (file, "-1/8;\n"); // b_{ij}t_j^4=1/5 (5th order) for (i = 1; i < ncoefficients; ++i) fprintf (file, "%c%u%u*t%u^4+", label, nsteps, i, i); fprintf (file, "-1/5;\n"); if (order < 5) return; // b_{ij}t_j^2b_{jk}t_k^2=1/10 (5th order) for (i = 2; i < ncoefficients; ++i) { fprintf (file, "%c%u%u*t%u^2*(", label, nsteps, i, i); for (j = 1; j < i; ++j) fprintf (file, "b%u%u*t%u+", i, j, j); fprintf (file, "0)+"); } fprintf (file, "-1/10;\n"); // b_{ij}b_{jk}t_k^3=1/20 (5th order) for (i = 2; i < ncoefficients; ++i) { fprintf (file, "%c%u%u*(", label, nsteps, i); for (j = 1; j < i; ++j) fprintf (file, "b%u%u*t%u^3+", i, j, j); fprintf (file, "0)+"); } fprintf (file, "-1/20;\n"); // b_{ij}(b_{jk}t_k)^2=1/20 (5th order) for (i = 2; i < ncoefficients; ++i) { fprintf (file, "%c%u%u*(", label, nsteps, i); for (j = 1; j < i; ++j) fprintf (file, "b%u%u*t%u+", i, j, j); fprintf (file, "0)^2+"); } fprintf (file, "-1/20;\n"); // b_{ij}t_jb_{jk}t_k^2=1/15 (5th order) for (i = 2; i < ncoefficients; ++i) { fprintf (file, "%c%u%u*t%u*(", label, nsteps, i, i); for (j = 1; j < i; ++j) fprintf (file, "b%u%u*t%u^2+", i, j, j); fprintf (file, "0)+"); } fprintf (file, "-1/8;\n"); // b_{ij}t_jb_{jk}b_{kl}t_l=1/24 (5th order) for (i = 3; i < ncoefficients; ++i) { fprintf (file, "%c%u%u*t%u*(", label, nsteps, i, i); for (j = 2; j < i; ++j) { fprintf (file, "b%u%u*(", i, j); for (k = 1; k < j; ++k) fprintf (file, "b%u%u*t%u+", j, k, k); fprintf (file, "0)+"); } fprintf (file, "0)+"); } fprintf (file, "-7/120;\n"); // b_{ij}b_{jk}b_{kl}t_l^2=1/60 (5th order) for (i = 3; i < ncoefficients; ++i) { fprintf (file, "%c%u%u*(", label, nsteps, i); for (j = 2; j < i; ++j) { fprintf (file, "b%u%u*(", i, j); for (k = 1; k < j; ++k) fprintf (file, "b%u%u*t%u^2+", j, k, k); fprintf (file, "0)+"); } fprintf (file, "0)+"); } fprintf (file, "-1/60;\n"); // b_{ij}b_{jk}b_{kl}b_{lm}t_m=1/120 (5th order) for (i = 4; i < ncoefficients; ++i) { fprintf (file, "%c%u%u*(", label, nsteps, i); for (j = 3; j < i; ++j) { fprintf (file, "b%u%u*(", i, j); for (k = 2; k < j; ++k) { fprintf (file, "b%u%u*(", j, k); for (l = 1; l < k; ++l) fprintf (file, "b%u%u*t%u+", k, l, l); fprintf (file, "0)+"); } fprintf (file, "0)+"); } fprintf (file, "0)+"); } fprintf (file, "-1/120;\n"); // b_{ij}t_j^5=1/6 (6th order) for (i = 1; i < ncoefficients; ++i) fprintf (file, "%c%u%u*t%u^5+", label, nsteps, i, i); fprintf (file, "-1/6;\n"); } /** * Function to print in a maxima file the a-c Runge-Kutta equations. */ static void ac_print_maxima (FILE * file, ///< file. unsigned int nsteps) ///< steps number. { unsigned int i, j, k; for (i = 2; i <= nsteps; ++i) { // a_{i,j}=1 for (j = 0; j < i; ++j) fprintf (file, "a%u%u+", i, j); fprintf (file, "-1;\n"); // a_{i0}c_{i0}+a_{ij}b_{j0}=b_{i0} fprintf (file, "a%u0*c%u0+a%u1*t1+", i, i, i); for (j = 2; j < i; ++j) fprintf (file, "a%u%u*b%u0+", i, j, j); fprintf (file, "-b%u0;\n", i); // a_{ij}c_{ij}+a_{ik}b_{kj}=b_{ij} for (j = 1; j < i; ++j) { fprintf (file, "a%u%u*c%u%u+", i, j, i, j); for (k = j; ++k < i;) fprintf (file, "a%u%u*b%u%u+", i, k, k, j); fprintf (file, "-b%u%u;\n", i, j); } } } /** * Function to get \f$a_{ij}\f$ and \f$c_{ij}\f$ coefficients of the Runge-Kutta * 2nd step. */ static int rk_ac_2 (RK * rk) ///< RK struct. { long double *tb, *ac, *r; register long double ac0; #if DEBUG_RK fprintf (stderr, "rk_ac_2: start\n"); #endif tb = rk->tb->coefficient; ac = rk->ac->coefficient; r = rk->ac->random_data; c21 (ac) = r[0]; a21 (ac) = b21 (tb) / c21 (ac); a20 (ac) = 1.L - a21 (ac); ac0 = b20 (tb) - a21 (ac) * t1 (tb); c20 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / a20 (ac); #if DEBUG_RK fprintf (stderr, "rk_ac_2: a20=%Lg c20=%Lg\n", a20 (ac), c20 (ac)); fprintf (stderr, "rk_ac_2: a21=%Lg c21=%Lg\n", a21 (ac), c21 (ac)); fprintf (stderr, "rk_ac_2: end\n"); #endif if (isnan (c20 (ac)) || isnan (a21 (ac))) return 0; return 1; } /** * Function to get \f$a_{ij}\f$ and \f$c_{ij}\f$ coefficients of the Runge-Kutta * 3rd step. */ static int rk_ac_3 (RK * rk) ///< RK struct. { long double *tb, *ac, *r; register long double ac0; #if DEBUG_RK fprintf (stderr, "rk_ac_3: start\n"); #endif if (!rk_ac_2 (rk)) { #if DEBUG_RK fprintf (stderr, "rk_ac_3: end\n"); #endif return 0; } tb = rk->tb->coefficient; ac = rk->ac->coefficient; r = rk->ac->random_data; c31 (ac) = r[1]; c32 (ac) = r[2]; a32 (ac) = b32 (tb) / c32 (ac); ac0 = b31 (tb) - a32 (ac) * b21 (tb); a31 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / c31 (ac); a30 (ac) = 1.L - a31 (ac) - a32 (ac); ac0 = b30 (tb) - a31 (ac) * t1 (tb) - a32 (ac) * b20 (tb); c30 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / a30 (ac); #if DEBUG_RK fprintf (stderr, "rk_ac_3: a30=%Lg c30=%Lg\n", a30 (ac), c30 (ac)); fprintf (stderr, "rk_ac_3: a31=%Lg c31=%Lg\n", a31 (ac), c31 (ac)); fprintf (stderr, "rk_ac_3: a32=%Lg c32=%Lg\n", a32 (ac), c32 (ac)); fprintf (stderr, "rk_ac_3: end\n"); #endif if (isnan (c30 (ac)) || isnan (a31 (ac)) || isnan (a32 (ac))) return 0; return 1; } /** * Function to get \f$a_{ij}\f$ and \f$c_{ij}\f$ coefficients of the Runge-Kutta * 4th step. */ static int rk_ac_4 (RK * rk) ///< RK struct. { long double *tb, *ac, *r; register long double ac0; #if DEBUG_RK fprintf (stderr, "rk_ac_4: start\n"); #endif if (!rk_ac_3 (rk)) { #if DEBUG_RK fprintf (stderr, "rk_ac_4: end\n"); #endif return 0; } tb = rk->tb->coefficient; ac = rk->ac->coefficient; r = rk->ac->random_data; c41 (ac) = r[3]; c42 (ac) = r[4]; c43 (ac) = r[5]; a43 (ac) = b43 (tb) / c43 (ac); ac0 = b42 (tb) - a43 (ac) * b32 (tb); a42 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / c42 (ac); ac0 = b41 (tb) - a42 (ac) * b21 (tb) - a43 (ac) * b31 (tb); a41 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / c41 (ac); a40 (ac) = 1.L - a41 (ac) - a42 (ac) - a43 (ac); ac0 = b40 (tb) - a41 (ac) * t1 (tb) - a42 (ac) * b20 (tb) - a43 (ac) * b30 (tb); c40 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / a40 (ac); #if DEBUG_RK fprintf (stderr, "rk_ac_4: a40=%Lg c40=%Lg\n", a40 (ac), c40 (ac)); fprintf (stderr, "rk_ac_4: a41=%Lg c41=%Lg\n", a41 (ac), c41 (ac)); fprintf (stderr, "rk_ac_4: a42=%Lg c42=%Lg\n", a42 (ac), c42 (ac)); fprintf (stderr, "rk_ac_4: a43=%Lg c43=%Lg\n", a43 (ac), c43 (ac)); fprintf (stderr, "rk_ac_4: end\n"); #endif if (isnan (c40 (ac)) || isnan (a41 (ac)) || isnan (a42 (ac)) || isnan (a43 (ac))) return 0; return 1; } /** * Function to get \f$a_{ij}\f$ and \f$c_{ij}\f$ coefficients of the Runge-Kutta * 5th step. */ static int rk_ac_5 (RK * rk) ///< RK struct. { long double *tb, *ac, *r; register long double ac0; #if DEBUG_RK fprintf (stderr, "rk_ac_5: start\n"); #endif if (!rk_ac_4 (rk)) { #if DEBUG_RK fprintf (stderr, "rk_ac_5: end\n"); #endif return 0; } tb = rk->tb->coefficient; ac = rk->ac->coefficient; r = rk->ac->random_data; c51 (ac) = r[6]; c52 (ac) = r[7]; c53 (ac) = r[8]; c54 (ac) = r[9]; a54 (ac) = b54 (tb) / c54 (ac); ac0 = b53 (tb) - a54 (ac) * b43 (tb); a53 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / c53 (ac); ac0 = b52 (tb) - a53 (ac) * b32 (tb) - a54 (ac) * b42 (tb); a52 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / c52 (ac); ac0 = b51 (tb) - a52 (ac) * b21 (tb) - a53 (ac) * b31 (tb) - a54 (ac) * b41 (tb); a51 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / c51 (ac); a50 (ac) = 1.L - a51 (ac) - a52 (ac) - a53 (ac) - a54 (ac); ac0 = b50 (tb) - a51 (ac) * t1 (tb) - a52 (ac) * b20 (tb) - a53 (ac) * b30 (tb) - a54 (ac) * b40 (tb); c50 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / a50 (ac); #if DEBUG_RK fprintf (stderr, "rk_ac_5: a50=%Lg c50=%Lg\n", a50 (ac), c50 (ac)); fprintf (stderr, "rk_ac_5: a51=%Lg c51=%Lg\n", a51 (ac), c51 (ac)); fprintf (stderr, "rk_ac_5: a52=%Lg c52=%Lg\n", a52 (ac), c52 (ac)); fprintf (stderr, "rk_ac_5: a53=%Lg c53=%Lg\n", a53 (ac), c53 (ac)); fprintf (stderr, "rk_ac_5: a54=%Lg c54=%Lg\n", a54 (ac), c54 (ac)); fprintf (stderr, "rk_ac_5: end\n"); #endif if (isnan (c50 (ac)) || isnan (a51 (ac)) || isnan (a52 (ac)) || isnan (a53 (ac)) || isnan (a54 (ac))) return 0; return 1; } /** * Function to get \f$a_{ij}\f$ and \f$c_{ij}\f$ coefficients of the Runge-Kutta * 6th step. */ static int rk_ac_6 (RK * rk) ///< RK struct. { long double *tb, *ac, *r; register long double ac0; #if DEBUG_RK fprintf (stderr, "rk_ac_6: start\n"); #endif if (!rk_ac_5 (rk)) { #if DEBUG_RK fprintf (stderr, "rk_ac_6: end\n"); #endif return 0; } tb = rk->tb->coefficient; ac = rk->ac->coefficient; r = rk->ac->random_data; c61 (ac) = r[10]; c62 (ac) = r[11]; c63 (ac) = r[12]; c64 (ac) = r[13]; c65 (ac) = r[14]; a65 (ac) = b65 (tb) / c65 (ac); ac0 = b64 (tb) - a65 (ac) * b54 (tb); a64 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / c64 (ac); ac0 = b63 (tb) - a64 (ac) * b43 (tb) - a65 (ac) * b53 (tb); a63 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / c63 (ac); ac0 = b62 (tb) - a63 (ac) * b32 (tb) - a64 (ac) * b42 (tb) - a65 (ac) * b52 (tb); a62 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / c62 (ac); ac0 = b61 (tb) - a62 (ac) * b21 (tb) - a63 (ac) * b31 (tb) - a64 (ac) * b41 (tb) - a65 (ac) * b51 (tb); a61 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / c61 (ac); a60 (ac) = 1.L - a61 (ac) - a62 (ac) - a63 (ac) - a64 (ac) - a65 (ac); ac0 = b60 (tb) - a61 (ac) * t1 (tb) - a62 (ac) * b20 (tb) - a63 (ac) * b30 (tb) - a64 (ac) * b40 (tb) - a65 (ac) * b50 (tb); c60 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / a60 (ac); #if DEBUG_RK fprintf (stderr, "rk_ac_6: a60=%Lg c60=%Lg\n", a60 (ac), c60 (ac)); fprintf (stderr, "rk_ac_6: a61=%Lg c61=%Lg\n", a61 (ac), c61 (ac)); fprintf (stderr, "rk_ac_6: a62=%Lg c62=%Lg\n", a62 (ac), c62 (ac)); fprintf (stderr, "rk_ac_6: a63=%Lg c63=%Lg\n", a63 (ac), c63 (ac)); fprintf (stderr, "rk_ac_6: a64=%Lg c64=%Lg\n", a64 (ac), c64 (ac)); fprintf (stderr, "rk_ac_6: a65=%Lg c65=%Lg\n", a65 (ac), c65 (ac)); fprintf (stderr, "rk_ac_6: end\n"); #endif if (isnan (c60 (ac)) || isnan (a61 (ac)) || isnan (a62 (ac)) || isnan (a63 (ac)) || isnan (a64 (ac)) || isnan (a65 (ac))) return 0; return 1; } /** * Function to get the objective function of 2 steps Runge-Kutta methods. * * \return objective function value. */ static long double rk_objective_ac_2 (RK * rk) ///< RK struct. { long double *tb, *ac; long double k; #if DEBUG_RK fprintf (stderr, "rk_objective ac_2: start\n"); #endif tb = rk->tb->coefficient; ac = rk->ac->coefficient; k = fminl (0.L, a20 (ac)); if (a21 (ac) < 0.L) k += a21 (ac); if (k < 0.L) { k = 20.L - k; goto end; } k = fminl (0.L, c20 (ac)); if (c21 (ac) < 0.L) k += c21 (ac); if (k < 0.L) { k = 10.L - k; goto end; } k = 1.L / rk_cfl_2 (tb, ac); end: #if DEBUG_RK fprintf (stderr, "rk_objective ac_2: objective=%Lg\n", k); fprintf (stderr, "rk_objective ac_2: end\n"); #endif return k; } /** * Function to get the objective function of 3 steps Runge-Kutta methods. * * \return objective function value. */ static long double rk_objective_ac_3 (RK * rk) ///< RK struct. { long double *tb, *ac; long double k; #if DEBUG_RK fprintf (stderr, "rk_objective ac_3: start\n"); #endif tb = rk->tb->coefficient; ac = rk->ac->coefficient; k = fminl (0.L, a20 (ac)); if (a21 (ac) < 0.L) k += a21 (ac); if (a30 (ac) < 0.L) k += a30 (ac); if (a31 (ac) < 0.L) k += a31 (ac); if (a32 (ac) < 0.L) k += a32 (ac); if (k < 0.L) { k = 20.L - k; goto end; } k = fminl (0.L, c20 (ac)); if (c21 (ac) < 0.L) k += c21 (ac); if (c30 (ac) < 0.L) k += c30 (ac); if (c31 (ac) < 0.L) k += c31 (ac); if (c32 (ac) < 0.L) k += c32 (ac); if (k < 0.L) { k = 10.L - k; goto end; } k = 1.L / rk_cfl_3 (tb, ac); end: #if DEBUG_RK fprintf (stderr, "rk_objective ac_3: objective=%Lg\n", k); fprintf (stderr, "rk_objective ac_3: end\n"); #endif return k; } /** * Function to get the objective function of 4 steps Runge-Kutta methods. * * \return objective function value. */ static long double rk_objective_ac_4 (RK * rk) ///< RK struct. { long double *tb, *ac; long double k; #if DEBUG_RK fprintf (stderr, "rk_objective ac_4: start\n"); #endif tb = rk->tb->coefficient; ac = rk->ac->coefficient; k = fminl (0.L, a20 (ac)); if (a21 (ac) < 0.L) k += a21 (ac); if (a30 (ac) < 0.L) k += a30 (ac); if (a31 (ac) < 0.L) k += a31 (ac); if (a32 (ac) < 0.L) k += a32 (ac); if (a40 (ac) < 0.L) k += a40 (ac); if (a41 (ac) < 0.L) k += a41 (ac); if (a42 (ac) < 0.L) k += a42 (ac); if (a43 (ac) < 0.L) k += a43 (ac); if (k < 0.L) { k = 20.L - k; goto end; } k = fminl (0.L, c20 (ac)); if (c21 (ac) < 0.L) k += c21 (ac); if (c30 (ac) < 0.L) k += c30 (ac); if (c31 (ac) < 0.L) k += c31 (ac); if (c32 (ac) < 0.L) k += c32 (ac); if (c40 (ac) < 0.L) k += c40 (ac); if (c41 (ac) < 0.L) k += c41 (ac); if (c42 (ac) < 0.L) k += c42 (ac); if (c43 (ac) < 0.L) k += c43 (ac); if (k < 0.L) { k = 10.L - k; goto end; } k = 1.L / rk_cfl_4 (tb, ac); end: #if DEBUG_RK fprintf (stderr, "rk_objective ac_4: objective=%Lg\n", k); fprintf (stderr, "rk_objective ac_4: end\n"); #endif return k; } /** * Function to get the objective function of 5 steps Runge-Kutta methods. * * \return objective function value. */ static long double rk_objective_ac_5 (RK * rk) ///< RK struct. { long double *tb, *ac; long double k; #if DEBUG_RK fprintf (stderr, "rk_objective ac_5: start\n"); #endif tb = rk->tb->coefficient; ac = rk->ac->coefficient; k = fminl (0.L, a20 (ac)); if (a21 (ac) < 0.L) k += a21 (ac); if (a30 (ac) < 0.L) k += a30 (ac); if (a31 (ac) < 0.L) k += a31 (ac); if (a32 (ac) < 0.L) k += a32 (ac); if (a40 (ac) < 0.L) k += a40 (ac); if (a41 (ac) < 0.L) k += a41 (ac); if (a42 (ac) < 0.L) k += a42 (ac); if (a43 (ac) < 0.L) k += a43 (ac); if (a50 (ac) < 0.L) k += a50 (ac); if (a51 (ac) < 0.L) k += a51 (ac); if (a52 (ac) < 0.L) k += a52 (ac); if (a53 (ac) < 0.L) k += a53 (ac); if (a54 (ac) < 0.L) k += a54 (ac); if (k < 0.L) { k = 20.L - k; goto end; } k = fminl (0.L, c20 (ac)); if (c21 (ac) < 0.L) k += c21 (ac); if (c30 (ac) < 0.L) k += c30 (ac); if (c31 (ac) < 0.L) k += c31 (ac); if (c32 (ac) < 0.L) k += c32 (ac); if (c40 (ac) < 0.L) k += c40 (ac); if (c41 (ac) < 0.L) k += c41 (ac); if (c42 (ac) < 0.L) k += c42 (ac); if (c43 (ac) < 0.L) k += c43 (ac); if (c50 (ac) < 0.L) k += c50 (ac); if (c51 (ac) < 0.L) k += c51 (ac); if (c52 (ac) < 0.L) k += c52 (ac); if (c53 (ac) < 0.L) k += c53 (ac); if (c54 (ac) < 0.L) k += c54 (ac); if (k < 0.L) { k = 10.L - k; goto end; } k = 1.L / rk_cfl_5 (tb, ac); end: #if DEBUG_RK fprintf (stderr, "rk_objective ac_5: objective=%Lg\n", k); fprintf (stderr, "rk_objective ac_5: end\n"); #endif return k; } /** * Function to get the objective function of 6 steps Runge-Kutta methods. * * \return objective function value. */ static long double rk_objective_ac_6 (RK * rk) ///< RK struct. { long double *tb, *ac; long double k; #if DEBUG_RK fprintf (stderr, "rk_objective ac_6: start\n"); #endif tb = rk->tb->coefficient; ac = rk->ac->coefficient; k = fminl (0.L, a20 (ac)); if (a21 (ac) < 0.L) k += a21 (ac); if (a30 (ac) < 0.L) k += a30 (ac); if (a31 (ac) < 0.L) k += a31 (ac); if (a32 (ac) < 0.L) k += a32 (ac); if (a40 (ac) < 0.L) k += a40 (ac); if (a41 (ac) < 0.L) k += a41 (ac); if (a42 (ac) < 0.L) k += a42 (ac); if (a43 (ac) < 0.L) k += a43 (ac); if (a50 (ac) < 0.L) k += a50 (ac); if (a51 (ac) < 0.L) k += a51 (ac); if (a52 (ac) < 0.L) k += a52 (ac); if (a53 (ac) < 0.L) k += a53 (ac); if (a54 (ac) < 0.L) k += a54 (ac); if (a60 (ac) < 0.L) k += a60 (ac); if (a61 (ac) < 0.L) k += a61 (ac); if (a62 (ac) < 0.L) k += a62 (ac); if (a63 (ac) < 0.L) k += a63 (ac); if (a64 (ac) < 0.L) k += a64 (ac); if (a65 (ac) < 0.L) k += a65 (ac); if (k < 0.L) { k = 20.L - k; goto end; } k = fminl (0.L, c20 (ac)); if (c21 (ac) < 0.L) k += c21 (ac); if (c30 (ac) < 0.L) k += c30 (ac); if (c31 (ac) < 0.L) k += c31 (ac); if (c32 (ac) < 0.L) k += c32 (ac); if (c40 (ac) < 0.L) k += c40 (ac); if (c41 (ac) < 0.L) k += c41 (ac); if (c42 (ac) < 0.L) k += c42 (ac); if (c43 (ac) < 0.L) k += c43 (ac); if (c50 (ac) < 0.L) k += c50 (ac); if (c51 (ac) < 0.L) k += c51 (ac); if (c52 (ac) < 0.L) k += c52 (ac); if (c53 (ac) < 0.L) k += c53 (ac); if (c54 (ac) < 0.L) k += c54 (ac); if (c60 (ac) < 0.L) k += c60 (ac); if (c61 (ac) < 0.L) k += c61 (ac); if (c62 (ac) < 0.L) k += c62 (ac); if (c63 (ac) < 0.L) k += c63 (ac); if (c64 (ac) < 0.L) k += c64 (ac); if (c65 (ac) < 0.L) k += c65 (ac); if (k < 0.L) { k = 10.L - k; goto end; } k = 1.L / rk_cfl_6 (tb, ac); end: #if DEBUG_RK fprintf (stderr, "rk_objective ac_6: objective=%Lg\n", k); fprintf (stderr, "rk_objective ac_6: end\n"); #endif return k; } /** * Function to init required variables on a RK struct data. */ static inline void rk_init (RK * rk, ///< RK struct. gsl_rng * rng, ///< GSL pseudo-random number generator struct. unsigned int thread) ///< thread number. { optimize_init (rk->tb, rng, thread); if (rk->strong) optimize_init (rk->ac0, rng, 0); } /** * Function to free the memory allocated by a RK struct. */ static inline void rk_delete (RK * rk) ///< RK struct. { if (rk->strong) optimize_delete (rk->ac0); optimize_delete (rk->tb); } /** * Function to perform every optimization step for the a-c Runge-Kutta * coefficients. */ static inline void rk_step_ac (RK * rk) ///< RK struct. { Optimize *tb, *ac; long double *is, *vo, *vo2; long double o, o2, v, f; unsigned long long int ii, nsimulations; unsigned int i, j, k, n, nfree; #if DEBUG_RK fprintf (stderr, "rk_step_ac: start\n"); #endif // save optimal values #if DEBUG_RK fprintf (stderr, "rk_step_ac: save optimal values\n"); #endif tb = rk->tb; ac = rk->ac; nfree = ac->nfree; o2 = INFINITY; vo = (long double *) alloca (nfree * sizeof (long double)); vo2 = (long double *) alloca (nfree * sizeof (long double)); memcpy (vo, ac->value_optimal, nfree * sizeof (long double)); // optimzation algorithm sampling #if DEBUG_RK fprintf (stderr, "rk_step_ac: optimization algorithm sampling\n"); fprintf (stderr, "rk_step_ac: nsimulations=%Lu nclimbings=%u nfree=%u\n", ac->nsimulations, ac->nclimbings, ac->nfree); #endif nsimulations = ac->nsimulations; for (ii = 0L; ii < nsimulations; ++ii) { // random freedom degrees #if DEBUG_RK fprintf (stderr, "rk_step_ac: random freedom degrees\n"); #endif optimize_generate_freedom (ac, ii); // method coefficients #if DEBUG_RK fprintf (stderr, "rk_step_ac: method coefficients\n"); #endif if (!ac->method ((Optimize *) rk)) o = INFINITY; else o = ac->objective ((Optimize *) rk); #if DEBUG_RK fprintf (stderr, "rk_step_ac: objective=%Lg o2=%Lg\n", o, o2); #endif if (o < o2) { o2 = o; memcpy (vo, ac->random_data, nfree * sizeof (long double)); } if (file_variables) { g_mutex_lock (mutex); print_variables (tb->random_data, tb->nfree, file_variables); print_variables (ac->random_data, nfree, file_variables); fprintf (file_variables, "%.19Le\n", o); g_mutex_unlock (mutex); } } // array of intervals to climb around the optimal #if DEBUG_RK fprintf (stderr, "rk_step_ac: array of intervals to climb around the optimal\n"); fprintf (stderr, "rk_step_ac: nclimbings=%u climbing_factor=%Lg\n", ac->nclimbings, ac->climbing_factor); #endif is = (long double *) alloca (nfree * sizeof (long double)); for (j = 0; j < nfree; ++j) is[j] = ac->interval0[j] * ac->climbing_factor; #if DEBUG_RK for (j = 0; j < nfree; ++j) fprintf (stderr, "rk_step_ac: i=%u is=%Lg\n", j, is[j]); #endif // hill climbing algorithm bucle #if DEBUG_RK fprintf (stderr, "rk_step_ac: hill climbing algorithm bucle\n"); #endif memcpy (vo2, vo, nfree * sizeof (long double)); memcpy (ac->random_data, vo, nfree * sizeof (long double)); n = ac->nclimbings; for (i = 0; i < n; ++i) { #if DEBUG_RK for (j = 0; j < nfree; ++j) fprintf (stderr, "rk_step_ac: j=%u is=%Lg\n", j, is[j]); #endif for (j = k = 0; j < nfree; ++j) { v = vo[j]; ac->random_data[j] = v + is[j]; #if DEBUG_RK fprintf (stderr, "rk_step_ac: j=%u random=%Lg\n", j, ac->random_data[j]); #endif if (!ac->method ((Optimize *) rk)) o = INFINITY; else o = ac->objective ((Optimize *) rk); #if DEBUG_RK fprintf (stderr, "rk_step_ac: k=%u objective=%Lg o2=%Lg\n", k, o, o2); #endif if (o < o2) { k = 1; o2 = o; memcpy (vo2, ac->random_data, nfree * sizeof (long double)); } if (file_variables) { g_mutex_lock (mutex); print_variables (tb->random_data, tb->nfree, file_variables); print_variables (ac->random_data, nfree, file_variables); fprintf (file_variables, "%.19Le\n", o); g_mutex_unlock (mutex); } ac->random_data[j] = fmaxl (0.L, v - is[j]); if (!ac->method ((Optimize *) rk)) o = INFINITY; else o = ac->objective ((Optimize *) rk); #if DEBUG_RK fprintf (stderr, "rk_step_ac: k=%u objective=%Lg o2=%Lg\n", k, o, o2); #endif if (o < o2) { k = 1; o2 = o; memcpy (vo2, ac->random_data, nfree * sizeof (long double)); } if (file_variables) { g_mutex_lock (mutex); print_variables (tb->random_data, tb->nfree, file_variables); print_variables (ac->random_data, nfree, file_variables); fprintf (file_variables, "%.19Le\n", o); g_mutex_unlock (mutex); } ac->random_data[j] = v; } // update optimal values and increase or reduce intervals if converging or // not if (!k) f = 0.5L; else { f = 1.2L; memcpy (vo, vo2, nfree * sizeof (long double)); } for (j = 0; j < nfree; ++j) is[j] *= f; } // update optimal values #if DEBUG_RK fprintf (stderr, "rk_step_ac: update optimal values\n"); fprintf (stderr, "rk_step_ac: optimal=%Lg o2=%Lg\n", *ac->optimal, o2); #endif if (o2 < *ac->optimal) { *ac->optimal = o2; memcpy (ac->value_optimal, vo2, nfree * sizeof (long double)); } #if DEBUG_RK fprintf (stderr, "rk_step_ac: end\n"); #endif } /** * Function to do the optimization bucle for the a-c Runge-Kutta coefficients. */ void rk_bucle_ac (RK * rk) ///< RK struct. { Optimize *tb, *ac, *ac0; long double *vo; long double optimal; unsigned int i, nfree; #if DEBUG_RK fprintf (stderr, "rk_bucle_ac: start\n"); #endif tb = rk->tb; ac = rk->ac; ac0 = rk->ac0; nfree = ac0->nfree; vo = (long double *) alloca (nfree * sizeof (long double)); // Init some parameters #if DEBUG_RK fprintf (stderr, "rk_bucle_ac: nfree=%u optimal=%Lg\n", nfree, *tb->optimal); #endif *ac0->optimal = optimal = *tb->optimal; for (i = 0; i < nfree; ++i) vo[i] = ac0->minimum[i] + 0.5L * ac0->interval[i]; memcpy (ac, ac0, sizeof (Optimize)); ac->optimal = &optimal; ac->value_optimal = vo; optimize_init (ac, ac0->rng, 0); #if DEBUG_RK for (i = 0; i < tb->nfree; ++i) fprintf (stderr, "rk_bucle_ac: i=%u random=%Lg\n", i, tb->random_data[i]); for (i = 0; i < nfree; ++i) fprintf (stderr, "rk_bucle_ac: i=%u minimum=%Lg interval=%Lg type=%u\n", i, ac->minimum[i], ac->interval[i], ac->random_type[i]); #endif // Iterate #if DEBUG_RK fprintf (stderr, "rk_bucle_ac: iterate\n"); #endif for (i = 0; i < ac->niterations; ++i) { // Optimization step rk_step_ac (rk); // Updating coefficient intervals to converge optimize_converge (ac); // Iterate #if DEBUG_RK fprintf (stderr, "Iteration ac %u\n", i); #endif } // Check and save optimal if (optimal < *ac0->optimal) { #if DEBUG_RK fprintf (stderr, "rk_bucle_ac: optimal=%Lg\n", *ac0->optimal); #endif g_mutex_lock (mutex); *ac0->optimal = optimal; memcpy (ac0->value_optimal, vo, nfree * sizeof (long double)); g_mutex_unlock (mutex); #if DEBUG_RK fprintf (stderr, "rk_bucle_ac: optimal=%Lg\n", *ac0->optimal); for (i = 0; i < ac0->nfree; ++i) fprintf (stderr, "rk_bucle_ac: vo%u=%Lg\n", i, ac0->value_optimal[i]); #endif } // Free memory optimize_delete (ac); #if DEBUG_RK fprintf (stderr, "rk_bucle_ac: end\n"); #endif } /** * Function to perform every optimization step for the t-b Runge-Kutta * coefficients. */ static inline void rk_step_tb (RK * rk) ///< RK struct. { Optimize *tb; long double *is, *vo; long double o, v, f; unsigned long long int ii, nrandom; unsigned int b, i, j, k, n, nfree; #if DEBUG_RK fprintf (stderr, "rk_step_tb: start\n"); #endif // save optimal values #if DEBUG_RK fprintf (stderr, "rk_step_tb: save optimal values\n"); #endif tb = rk->tb; nfree = tb->nfree; vo = (long double *) alloca (nfree * sizeof (long double)); b = (file_variables && !rk->strong) ? 1 : 0; // optimization algorithm sampling #if DEBUG_RK fprintf (stderr, "rk_step_tb: optimization algorithm sampling\n"); fprintf (stderr, "rk_step_tb: nsimulations=%Lu nclimbings=%u\n", tb->nsimulations, tb->nclimbings); #endif ii = tb->nsimulations * (rank * nthreads + tb->thread) / (nnodes * nthreads); nrandom = tb->nsimulations * (rank * nthreads + tb->thread + 1) / (nnodes * nthreads); for (; ii < nrandom; ++ii) { // random freedom degrees #if DEBUG_RK fprintf (stderr, "rk_step_tb: random freedom degrees\n"); #endif optimize_generate_freedom (tb, ii); // method coefficients #if DEBUG_RK fprintf (stderr, "rk_step_tb: method coefficients\n"); #endif if (!tb->method (tb)) o = INFINITY; else o = tb->objective (tb); if (o < *tb->optimal) { g_mutex_lock (mutex); *tb->optimal = o; memcpy (tb->value_optimal, tb->random_data, nfree * sizeof (long double)); g_mutex_unlock (mutex); } if (b) { g_mutex_lock (mutex); print_variables (tb->random_data, nfree, file_variables); fprintf (file_variables, "%.19Le\n", o); g_mutex_unlock (mutex); } } // array of intervals to climb around the optimal #if DEBUG_RK fprintf (stderr, "rk_step_tb: array of intervals to climb around the optimal\n"); #endif is = (long double *) alloca (nfree * sizeof (long double)); for (j = 0; j < nfree; ++j) is[j] = tb->interval0[j] * tb->climbing_factor; // hill climbing algorithm bucle #if DEBUG_RK fprintf (stderr, "rk_step_tb: hill climbing algorithm bucle\n"); #endif memcpy (tb->random_data, tb->value_optimal, nfree * sizeof (long double)); memcpy (vo, tb->value_optimal, nfree * sizeof (long double)); n = tb->nclimbings; for (i = 0; i < n; ++i) { for (j = k = 0; j < nfree; ++j) { v = vo[j]; tb->random_data[j] = v + is[j]; if (!tb->method (tb)) o = INFINITY; else o = tb->objective (tb); if (o < *tb->optimal) { k = 1; g_mutex_lock (mutex); *tb->optimal = o; memcpy (tb->value_optimal, tb->random_data, nfree * sizeof (long double)); g_mutex_unlock (mutex); } if (b) { g_mutex_lock (mutex); print_variables (tb->random_data, nfree, file_variables); fprintf (file_variables, "%.19Le\n", o); g_mutex_unlock (mutex); } tb->random_data[j] = fmaxl (0.L, v - is[j]); if (!tb->method (tb)) o = INFINITY; else o = tb->objective (tb); if (o < *tb->optimal) { k = 1; g_mutex_lock (mutex); *tb->optimal = o; memcpy (tb->value_optimal, tb->random_data, nfree * sizeof (long double)); g_mutex_unlock (mutex); } if (b) { g_mutex_lock (mutex); print_variables (tb->random_data, nfree, file_variables); fprintf (file_variables, "%.19Le\n", o); g_mutex_unlock (mutex); } tb->random_data[j] = v; } // increase or reduce intervals if converging or not if (!k) f = 0.5L; else { f = 1.2L; memcpy (vo, tb->value_optimal, nfree * sizeof (long double)); } for (j = 0; j < nfree; ++j) is[j] *= f; } #if DEBUG_RK fprintf (stderr, "rk_step_tb: end\n"); #endif } /** * Function to do the optimization bucle. */ static inline void rk_bucle_tb (RK * rk) ///< RK struct. { GThread *thread[nthreads]; Optimize *tb, *ac; #if HAVE_MPI long double *vo; MPI_Status status; #endif unsigned int i, j, nfree, nfree2, strong; #if DEBUG_RK fprintf (stderr, "rk_bucle_tb: start\n"); #endif // Allocate local array of optimal values #if DEBUG_RK fprintf (stderr, "rk_bucle_tb: allocate local array of optimal values\n"); #endif tb = rk->tb; nfree = tb->nfree; strong = rk->strong; if (strong) { ac = rk->ac0; nfree2 = ac->nfree; } else nfree2 = 0; #if HAVE_MPI vo = (long double *) alloca ((1 + nfree + nfree2) * sizeof (long double)); #endif // Init some parameters #if DEBUG_RK fprintf (stderr, "rk_bucle_tb: init some parameters\n"); fprintf (stderr, "rk_bucle_tb: nfree=%u\n", nfree); #endif *tb->optimal = INFINITY; for (i = 0; i < nfree; ++i) tb->value_optimal[i] = tb->minimum[i] + 0.5L * tb->interval[i]; if (strong) for (i = 0; i < nfree2; ++i) ac->value_optimal[i] = ac->minimum[i] + 0.5L * ac->interval[i]; // Iterate #if DEBUG_RK fprintf (stderr, "rk_bucle_tb: iterate\n"); #endif for (i = 0; i < tb->niterations; ++i) { // Optimization step parallelized for every node by GThreads if (nthreads > 1) { for (j = 0; j < nthreads; ++j) thread[j] = g_thread_new (NULL, (GThreadFunc) (void (*)(void)) rk_step_tb, (void *) (rk + j)); for (j = 0; j < nthreads; ++j) g_thread_join (thread[j]); } else rk_step_tb (rk); #if HAVE_MPI if (rank > 0) { // Secondary nodes send the optimal coefficients to the master node vo[0] = *tb->optimal; memcpy (vo + 1, tb->value_optimal, nfree * sizeof (long double)); if (strong) memcpy (vo + 1 + nfree, ac->value_optimal, nfree2 * sizeof (long double)); MPI_Send (vo, 1 + nfree + nfree2, MPI_LONG_DOUBLE, 0, 1, MPI_COMM_WORLD); // Secondary nodes receive the optimal coefficients MPI_Recv (vo, 1 + nfree + nfree2, MPI_LONG_DOUBLE, 0, 1, MPI_COMM_WORLD, &status); *tb->optimal = *ac->optimal = vo[0]; memcpy (tb->value_optimal, vo + 1, nfree * sizeof (long double)); if (strong) memcpy (ac->value_optimal, vo + 1 + nfree, nfree2 * sizeof (long double)); } else { printf ("rank=%d optimal=%.19Le\n", rank, *tb->optimal); for (j = 1; j < nnodes; ++j) { // Master node receives the optimal coefficients obtained by // secondary nodes MPI_Recv (vo, 1 + nfree + nfree2, MPI_LONG_DOUBLE, j, 1, MPI_COMM_WORLD, &status); // Master node selects the optimal coefficients if (vo[0] < *tb->optimal) { *tb->optimal = *ac->optimal = vo[0]; memcpy (tb->value_optimal, vo + 1, nfree * sizeof (long double)); if (strong) memcpy (ac->value_optimal, vo + 1 + nfree, nfree2 * sizeof (long double)); } } // Master node sends the optimal coefficients to secondary nodes vo[0] = *tb->optimal; memcpy (vo + 1, tb->value_optimal, nfree * sizeof (long double)); if (strong) memcpy (vo + 1 + nfree, ac->value_optimal, nfree2 * sizeof (long double)); for (j = 1; j < nnodes; ++i) MPI_Send (vo, 1 + nfree + nfree2, MPI_LONG_DOUBLE, j, 1, MPI_COMM_WORLD); } #endif // Print the optimal coefficients #if DEBUG_RK optimize_print_random (tb, stderr); if (strong) optimize_print_random (ac, stderr); fprintf (stderr, "optimal=%.19Le\n", *tb->optimal); #endif // Updating coefficient intervals to converge optimize_converge (tb); // Iterate printf ("Iteration %u Optimal %.19Le\n", i, *tb->optimal); } #if DEBUG_RK fprintf (stderr, "rk_bucle_tb: end\n"); #endif } /** * Function to select the Runge-Kutta method. * * \return 1 on success, 0 on error. */ static inline int rk_select (RK * rk, ///< RK struct. unsigned int nsteps, ///< steps number. unsigned int order) ///< accuracy order. { static int (*tb_method[7][6]) (Optimize *) = { { NULL, NULL, NULL, NULL, NULL, NULL}, { NULL, NULL, NULL, NULL, NULL, NULL}, { NULL, NULL, &rk_tb_2_2, NULL, NULL, NULL}, { NULL, NULL, &rk_tb_3_2, &rk_tb_3_3, NULL, NULL}, { NULL, NULL, &rk_tb_4_2, &rk_tb_4_3, &rk_tb_4_4, NULL}, { NULL, NULL, &rk_tb_5_2, &rk_tb_5_3, &rk_tb_5_4, NULL}, { NULL, NULL, &rk_tb_6_2, &rk_tb_6_3, &rk_tb_6_4, NULL} }; static int (*tb_method_t[7][6]) (Optimize *) = { { NULL, NULL, NULL, NULL, NULL, NULL}, { NULL, NULL, NULL, NULL, NULL, NULL}, { NULL, NULL, &rk_tb_2_2t, NULL, NULL, NULL}, { NULL, NULL, &rk_tb_3_2t, &rk_tb_3_3t, NULL, NULL}, { NULL, NULL, &rk_tb_4_2t, &rk_tb_4_3t, &rk_tb_4_4t, NULL}, { NULL, NULL, &rk_tb_5_2t, &rk_tb_5_3t, &rk_tb_5_4t, NULL}, { NULL, NULL, &rk_tb_6_2t, &rk_tb_6_3t, &rk_tb_6_4t, NULL} }; static int (*tb_method_p[7][6]) (Optimize *) = { { NULL, NULL, NULL, NULL, NULL, NULL}, { NULL, NULL, NULL, NULL, NULL, NULL}, { NULL, NULL, &rk_tb_2_2p, NULL, NULL, NULL}, { NULL, NULL, &rk_tb_3_2p, &rk_tb_3_3p, NULL, NULL}, { NULL, NULL, &rk_tb_4_2p, &rk_tb_4_3p, NULL, NULL}, { NULL, NULL, &rk_tb_5_2p, &rk_tb_5_3p, &rk_tb_5_4p, NULL}, { NULL, NULL, &rk_tb_6_2p, &rk_tb_6_3p, &rk_tb_6_4p, NULL} }; static int (*tb_method_tp[7][6]) (Optimize *) = { { NULL, NULL, NULL, NULL, NULL, NULL}, { NULL, NULL, NULL, NULL, NULL, NULL}, { NULL, NULL, &rk_tb_2_2tp, NULL, NULL, NULL}, { NULL, NULL, &rk_tb_3_2tp, &rk_tb_3_3tp, NULL, NULL}, { NULL, NULL, &rk_tb_4_2tp, &rk_tb_4_3tp, NULL, NULL}, { NULL, NULL, &rk_tb_5_2tp, &rk_tb_5_3tp, &rk_tb_5_4tp, NULL}, { NULL, NULL, &rk_tb_6_2tp, &rk_tb_6_3tp, &rk_tb_6_4tp, NULL} }; static long double (*tb_objective[7][6]) (RK *) = { { NULL, NULL, NULL, NULL, NULL, NULL}, { NULL, NULL, &rk_objective_tb_2_2, NULL, NULL, NULL}, { NULL, NULL, &rk_objective_tb_2_2, NULL, NULL, NULL}, { NULL, NULL, &rk_objective_tb_3_2, &rk_objective_tb_3_3, NULL, NULL}, { NULL, NULL, &rk_objective_tb_4_2, &rk_objective_tb_4_3, &rk_objective_tb_4_4, NULL}, { NULL, NULL, &rk_objective_tb_5_2, &rk_objective_tb_5_3, &rk_objective_tb_5_4, NULL}, { NULL, NULL, &rk_objective_tb_6_2, &rk_objective_tb_6_3, &rk_objective_tb_6_4, NULL} }; static long double (*tb_objective_t[7][6]) (RK *) = { { NULL, NULL, NULL, NULL, NULL, NULL}, { NULL, NULL, &rk_objective_tb_2_2t, NULL, NULL, NULL}, { NULL, NULL, &rk_objective_tb_2_2t, NULL, NULL, NULL}, { NULL, NULL, &rk_objective_tb_3_2t, &rk_objective_tb_3_3t, NULL, NULL}, { NULL, NULL, &rk_objective_tb_4_2t, &rk_objective_tb_4_3t, &rk_objective_tb_4_4t, NULL}, { NULL, NULL, &rk_objective_tb_5_2t, &rk_objective_tb_5_3t, &rk_objective_tb_5_4t, NULL}, { NULL, NULL, &rk_objective_tb_6_2t, &rk_objective_tb_6_3t, &rk_objective_tb_6_4t, NULL} }; static long double (*tb_objective_p[7][6]) (RK *) = { { NULL, NULL, NULL, NULL, NULL, NULL}, { NULL, NULL, NULL, NULL, NULL, NULL}, { NULL, NULL, &rk_objective_tb_2_2, NULL, NULL, NULL}, { NULL, NULL, &rk_objective_tb_3_2, &rk_objective_tb_3_3p, NULL, NULL}, { NULL, NULL, &rk_objective_tb_4_2, &rk_objective_tb_4_3p, NULL, NULL}, { NULL, NULL, &rk_objective_tb_5_2, &rk_objective_tb_5_3p, &rk_objective_tb_5_4p, NULL}, { NULL, NULL, &rk_objective_tb_6_2, &rk_objective_tb_6_3p, &rk_objective_tb_6_4p, NULL} }; static long double (*tb_objective_tp[7][6]) (RK *) = { { NULL, NULL, NULL, NULL, NULL, NULL}, { NULL, NULL, NULL, NULL, NULL, NULL}, { NULL, NULL, &rk_objective_tb_2_2t, NULL, NULL, NULL}, { NULL, NULL, &rk_objective_tb_3_2t, &rk_objective_tb_3_3tp, NULL, NULL}, { NULL, NULL, &rk_objective_tb_4_2t, &rk_objective_tb_4_3tp, NULL, NULL}, { NULL, NULL, &rk_objective_tb_5_2t, &rk_objective_tb_5_3tp, &rk_objective_tb_5_4tp, NULL}, { NULL, NULL, &rk_objective_tb_6_2t, &rk_objective_tb_6_3tp, &rk_objective_tb_6_4tp, NULL} }; static int (*ac_method[7]) (RK *) = { NULL, NULL, &rk_ac_2, &rk_ac_3, &rk_ac_4, &rk_ac_5, &rk_ac_6}; static long double (*ac_objective[7]) (RK * rk) = { NULL, NULL, &rk_objective_ac_2, &rk_objective_ac_3, &rk_objective_ac_4, &rk_objective_ac_5, &rk_objective_ac_6}; const unsigned int nequations[6] = { 0, 1, 2, 4, 8, 16 }; Optimize *tb, *ac; #if DEBUG_RK fprintf (stderr, "rk_select: start\n"); #endif tb = rk->tb; ac = rk->ac; tb->nsteps = nsteps; tb->order = order; tb->size = nsteps * (nsteps + 3) / 2 - 1; tb->nfree = tb->size - nsteps + 1 - nequations[order]; if (rk->pair) { tb->size += nsteps - 1; if (rk->time_accuracy) { tb->method = tb_method_tp[nsteps][order]; tb->objective = (OptimizeObjective) tb_objective_tp[nsteps][order]; } else { tb->method = tb_method_p[nsteps][order]; tb->objective = (OptimizeObjective) tb_objective_p[nsteps][order]; } } else { if (rk->time_accuracy) { tb->method = tb_method_t[nsteps][order]; tb->objective = (OptimizeObjective) tb_objective_t[nsteps][order]; } else { tb->method = tb_method[nsteps][order]; tb->objective = (OptimizeObjective) tb_objective[nsteps][order]; } } if (!tb->method) goto exit_on_error; if (rk->time_accuracy) { --tb->nfree; if (rk->pair) switch (nsteps) { case 5: switch (order) { case 4: --tb->nfree; } break; case 6: switch (order) { case 4: --tb->nfree; } break; } } tb->minimum0 = (long double *) g_slice_alloc (tb->nfree * sizeof (long double)); tb->interval0 = (long double *) g_slice_alloc (tb->nfree * sizeof (long double)); tb->random_type = (unsigned int *) g_slice_alloc (tb->nfree * sizeof (unsigned int)); if (rk->strong) { ac = rk->ac0; ac->size = nsteps * (nsteps + 1) - 2; ac->nfree = nsteps * (nsteps - 1) / 2; ac->minimum0 = (long double *) g_slice_alloc (ac->nfree * sizeof (long double)); ac->interval0 = (long double *) g_slice_alloc (ac->nfree * sizeof (long double)); ac->random_type = (unsigned int *) g_slice_alloc (ac->nfree * sizeof (unsigned int)); ac->method = (OptimizeMethod) ac_method[nsteps]; if (!ac->method) goto exit_on_error; ac->objective = (OptimizeObjective) ac_objective[nsteps]; } #if DEBUG_RK fprintf (stderr, "rk_select: end\n"); #endif return 1; exit_on_error: error_message = g_strdup (_("Unknown method")); #if DEBUG_RK fprintf (stderr, "rk_select: end\n"); #endif return 0; } /** * Function to read the Runge-Kutta method data on a XML node. * * \return 1 on success, 0 on error. */ int rk_run (xmlNode * node, ///< XML node. gsl_rng ** rng) ///< array of gsl_rng structs. { RK rk[nthreads]; char filename[64]; Optimize *tb, *ac; gchar *buffer; xmlChar *prop; FILE *file; long double *value_optimal, *value_optimal2; long double optimal, optimal2; int code; unsigned int i, j, nsteps, order, nfree, nfree2; #if DEBUG_RK fprintf (stderr, "rk_run: start\n"); #endif tb = rk->tb; nsteps = xml_node_get_uint (node, XML_STEPS, &code); if (code) { error_message = g_strdup (_("Bad steps number")); goto exit_on_error; } order = xml_node_get_uint (node, XML_ORDER, &code); if (code) { error_message = g_strdup (_("Bad order")); goto exit_on_error; } prop = xmlGetProp (node, XML_STRONG); if (!prop || !xmlStrcmp (prop, XML_NO)) rk->strong = 0; else if (!xmlStrcmp (prop, XML_YES)) rk->strong = 1; else { error_message = g_strdup (_("Bad strong stability")); goto exit_on_error; } xmlFree (prop); prop = xmlGetProp (node, XML_PAIR); if (!prop || !xmlStrcmp (prop, XML_NO)) rk->pair = 0; else if (!xmlStrcmp (prop, XML_YES)) rk->pair = 1; else { error_message = g_strdup (_("Bad pair")); goto exit_on_error; } xmlFree (prop); prop = xmlGetProp (node, XML_TIME_ACCURACY); if (!prop || !xmlStrcmp (prop, XML_NO)) rk->time_accuracy = 0; else if (!xmlStrcmp (prop, XML_YES)) rk->time_accuracy = 1; else { error_message = g_strdup (_("Bad time accuracy")); goto exit_on_error; } xmlFree (prop); if (!rk_select (rk, nsteps, order)) goto exit_on_error; if (!optimize_read (tb, node)) goto exit_on_error; nfree = tb->nfree; value_optimal = (long double *) g_slice_alloc (nfree * sizeof (long double)); optimize_create (tb, &optimal, value_optimal); node = node->children; for (i = 0; i < nfree; ++i, node = node->next) if (!read_variable (node, tb->minimum0, tb->interval0, tb->random_type, i)) goto exit_on_error; if (rk->strong) { ac = rk->ac0; if (!node) { error_message = g_strdup (_("No a-c coefficients data")); goto exit_on_error; } if (xmlStrcmp (node->name, XML_AC)) { error_message = g_strdup (_("Bad a-c coefficients XML node")); goto exit_on_error; } if (!optimize_read (ac, node)) { buffer = error_message; error_message = g_strconcat (_("a-c coefficients"), ":\n", error_message, NULL); g_free (buffer); goto exit_on_error; } nfree2 = ac->nfree; value_optimal2 = (long double *) g_slice_alloc (nfree2 * sizeof (long double)); optimize_create (ac, &optimal2, value_optimal2); for (i = 0; i < nfree2; ++i) { node = node->next; if (!read_variable (node, ac->minimum0, ac->interval0, ac->random_type, i)) goto exit_on_error; } } for (i = 1; i < nthreads; ++i) memcpy (rk + i, rk, sizeof (RK)); j = rank * nthreads; for (i = 0; i < nthreads; ++i) rk_init (rk + i, rng[j + i], i); // Method bucle printf ("Optimize bucle\n"); rk_bucle_tb (rk); // Print the optimal coefficients printf ("Print the optimal coefficients\n"); memcpy (tb->random_data, tb->value_optimal, nfree * sizeof (long double)); code = tb->method (tb); if (rk->strong) { memcpy (ac->random_data, ac->value_optimal, nfree2 * sizeof (long double)); memcpy (rk->ac, ac, sizeof (Optimize)); code = ac->method ((Optimize *) rk); } snprintf (filename, 64, "rk-%u-%u-%u-%u-%u.mc", nsteps, order, rk->time_accuracy, rk->pair, rk->strong); file = fopen (filename, "w"); print_maxima_precision (file); rk_print (rk, file); rk_print_maxima (file, nsteps, nsteps, order, 'b'); if (rk->pair) rk_print_maxima (file, nsteps, nsteps - 1, order - 1, 'e'); if (rk->strong) ac_print_maxima (file, nsteps); fclose (file); snprintf (filename, 64, "sed -i 's/e+/b+/g' rk-%u-%u-%u-%u-%u.mc", nsteps, order, rk->time_accuracy, rk->pair, rk->strong); code = system (filename); snprintf (filename, 64, "sed -i 's/e-/b-/g' rk-%u-%u-%u-%u-%u.mc", nsteps, order, rk->time_accuracy, rk->pair, rk->strong); code = system (filename); // Free memory if (rk->strong) { g_slice_free1 (nfree2 * sizeof (unsigned int), ac->random_type); g_slice_free1 (nfree2 * sizeof (long double), ac->interval0); g_slice_free1 (nfree2 * sizeof (long double), ac->minimum0); g_slice_free1 (nfree2 * sizeof (long double), value_optimal2); } for (i = 0; i < nthreads; ++i) rk_delete (rk + i); g_slice_free1 (nfree * sizeof (unsigned int), tb->random_type); g_slice_free1 (nfree * sizeof (long double), tb->interval0); g_slice_free1 (nfree * sizeof (long double), tb->minimum0); g_slice_free1 (nfree * sizeof (long double), value_optimal); #if DEBUG_RK fprintf (stderr, "rk_run: end\n"); #endif return 1; exit_on_error: buffer = error_message; error_message = g_strconcat ("Runge-Kutta:\n", buffer, NULL); g_free (buffer); #if DEBUG_RK fprintf (stderr, "rk_run: end\n"); #endif return 0; }
{ "alphanum_fraction": 0.538764158, "avg_line_length": 27.9116445352, "ext": "c", "hexsha": "a1b461ac2cdef278333faf9bc25f1ba8cbd318a8", "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": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "jburguete/ode", "max_forks_repo_path": "rk.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "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": "jburguete/ode", "max_issues_repo_path": "rk.c", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "jburguete/ode", "max_stars_repo_path": "rk.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 19362, "size": 54651 }
// gcc -msse2 -O3 -ftree-vectorize test_dcl.c dclhelpers.c os_generic.c -DFLT=double -lpthread -lcblas && valgrind // ./a.out #include "dclhelpers.h" #include "os_generic.h" #include <assert.h> #include <cblas.h> #include <math.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include "sv_matrix.h" void fill_random(FLT *A, int ld, int m, int n) { assert(ld == n); for (int y = 0; y < m; y++) for (int x = 0; x < n; x++) A[y * ld + x] = (rand()) / (double)RAND_MAX; } void test_dcldgemm_speed(const char *name, char transA, char transB, int m, int n, int k, DCL_FLOAT alpha, const DCL_FLOAT *A, int Ac, const DCL_FLOAT *B, int Bc, DCL_FLOAT beta) { printf("%s speed test:\n", name); double times[2]; FLT emo[2][m][n]; for (int z = 0; z < 2; z++) { double start = OGGetAbsoluteTime(); for (int i = 0; i < 100000; i++) { dclZero(DMS(emo[z]), m, n); if (z == 0) { dcldgemm(transA, transB, m, n, k, alpha, A, Ac, B, Bc, beta, DMS(emo[z])); } else { cblas_dgemm(CblasRowMajor, transA == 1 ? CblasTrans : CblasNoTrans, transB == 1 ? CblasTrans : CblasNoTrans, m, n, k, alpha, A, Ac, B, Bc, beta, emo[z][0], n); } } times[z] = OGGetAbsoluteTime() - start; } dclPrint(DMS(emo[0]), m, n); dclPrint(DMS(emo[1]), m, n); printf("dcl Elapsed: %f\n", times[0]); printf("cblas Elapsed: %f\n", times[1]); printf("%fx difference\n", times[0] / times[1]); for (int i = 0; i < m; i++) { for (int j = 0; j < k; j++) { assert(fabs(emo[0][i][j] - emo[1][i][j]) < .00001); } } } void compareToCblas() { srand(0); int m = 12; int n = 20; int k = 20; FLT em1[m][n]; FLT em2[n][k]; fill_random(DMS(em1), m, n); fill_random(DMS(em2), n, k); dclPrint(DMS(em1), m, n); dclPrint(DMS(em2), n, k); test_dcldgemm_speed("Simple", 0, 0, m, n, k, 1.0, DMS(em1), DMS(em2), .1); } void compareToCblasTrans() { srand(0); int m = 12; int n = 20; int k = n; FLT em1[m][n]; fill_random(DMS(em1), m, n); dclPrint(DMS(em1), m, n); SvMat Em1 = cvMat(m, n, SV_FLT, em1); FLT em1tem1[n][n]; SvMat Em1tEm1 = cvMat(n, n, SV_FLT, em1tem1); cvMulTransposed(&Em1, &Em1tEm1, 1, 0, 1); print_mat(&Em1tEm1); test_dcldgemm_speed("Trans", 0, 0, n, // # of rows in OP(A) == em1' -- 20 n, // # of cols in OP(B) == em1 -- 20 m, // # of cols in OP(A) == em1' -- 12 1.0, DMS(em1), // Note that LD stays the same DMS(em1), 0); } int main() { FLT A[2][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}}; FLT B[4][2]; dclPrint(A[0], 4, 2, 4); dclTransp(B[0], 2, A[0], 4, 2, 4); dclPrint(B[0], 2, 4, 2); int i, j; for (i = 0; i < 8; i++) { printf("%f\n", ((float *)(B[0]))[i]); } FLT M[3][3] = {{.32, 1, 0}, {0, 1, 2}, {1, 0, 1}}; FLT Mo[3][3]; dclInv(Mo[0], 3, M[0], 3, 3); dclPrint(Mo[0], 3, 3, 3); FLT MM[3][3]; dclMul(MM[0], 3, M[0], 3, Mo[0], 3, 3, 3, 3); printf("The following should be an identity matrix\n"); dclPrint(MM[0], 3, 3, 3); { FLT A[3][4]; dclIdentity(DMS(A), 3, 4); dclPrint(DMS(A), 3, 4); FLT x[4][2] = { {7, -7}, {8, -8}, {9, -9}, {10, -10}, }; FLT R[4][2]; dclZero(DMS(R), 4, 2); // dclMul(R, 1, A[0], 4, x, 1, 4, 1, 3); dcldgemm(0, 0, 3, 4, 2, 1, A[0], 4, x[0], 2, 0, R[0], 2); dclPrint(DMS(x), 4, 2); dclPrint(DMS(R), 3, 2); for (int j = 0; j < 2; j++) { for (int i = 0; i < 3; i++) { printf("[%d][%d]\n", i, j); assert(R[i][j] == x[i][j]); } assert(fabs(R[3][j]) < .0000001); } } compareToCblas(); compareToCblasTrans(); }
{ "alphanum_fraction": 0.532630379, "avg_line_length": 22.4935897436, "ext": "c", "hexsha": "d66f3e4418c58870bd0d688f046d14596c64bb49", "lang": "C", "max_forks_count": 52, "max_forks_repo_forks_event_max_datetime": "2022-03-21T07:50:56.000Z", "max_forks_repo_forks_event_min_datetime": "2020-03-26T09:09:18.000Z", "max_forks_repo_head_hexsha": "3dc35a3c5195724998cbb9e3b486e41ce6b1110d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jdavidberger/libsurvive", "max_forks_repo_path": "redist/test_dcl.c", "max_issues_count": 100, "max_issues_repo_head_hexsha": "3dc35a3c5195724998cbb9e3b486e41ce6b1110d", "max_issues_repo_issues_event_max_datetime": "2022-03-26T13:41:38.000Z", "max_issues_repo_issues_event_min_datetime": "2020-02-12T02:42:52.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jdavidberger/libsurvive", "max_issues_repo_path": "redist/test_dcl.c", "max_line_length": 114, "max_stars_count": 208, "max_stars_repo_head_hexsha": "3dc35a3c5195724998cbb9e3b486e41ce6b1110d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jdavidberger/libsurvive", "max_stars_repo_path": "redist/test_dcl.c", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:06:40.000Z", "max_stars_repo_stars_event_min_datetime": "2020-02-18T18:48:39.000Z", "num_tokens": 1564, "size": 3509 }
/* ode-initval/rkck.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., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Runge-Kutta 4(5), Cash-Karp */ /* Author: G. Jungman */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_odeiv.h> #include "odeiv_util.h" /* Cash-Karp constants */ static const double ah[] = { 1.0 / 5.0, 0.3, 3.0 / 5.0, 1.0, 7.0 / 8.0 }; static const double b21 = 1.0 / 5.0; static const double b3[] = { 3.0 / 40.0, 9.0 / 40.0 }; static const double b4[] = { 0.3, -0.9, 1.2 }; static const double b5[] = { -11.0 / 54.0, 2.5, -70.0 / 27.0, 35.0 / 27.0 }; static const double b6[] = { 1631.0 / 55296.0, 175.0 / 512.0, 575.0 / 13824.0, 44275.0 / 110592.0, 253.0 / 4096.0 }; static const double c1 = 37.0 / 378.0; static const double c3 = 250.0 / 621.0; static const double c4 = 125.0 / 594.0; static const double c6 = 512.0 / 1771.0; static const double ec[] = { 0.0, /* the first value is the same as c1, above */ 37.0 / 378.0 - 2825.0 / 27648.0, 0.0, /* the first value is the same as c3, above */ 250.0 / 621.0 - 18575.0 / 48384.0, /* the first value is the same as c4, above */ 125.0 / 594.0 - 13525.0 / 55296.0, -277.00 / 14336.0, /* the first value is the same as c6, above */ 512.0 / 1771.0 - 0.25 }; typedef struct { double *k1; double *k2; double *k3; double *k4; double *k5; double *k6; double *y0; double *ytmp; } rkck_state_t; static void * rkck_alloc (size_t dim) { rkck_state_t *state = (rkck_state_t *) malloc (sizeof (rkck_state_t)); if (state == 0) { GSL_ERROR_NULL ("failed to allocate space for rkck_state", GSL_ENOMEM); } state->k1 = (double *) malloc (dim * sizeof (double)); if (state->k1 == 0) { free (state); GSL_ERROR_NULL ("failed to allocate space for k1", GSL_ENOMEM); } state->k2 = (double *) malloc (dim * sizeof (double)); if (state->k2 == 0) { free (state->k1); free (state); GSL_ERROR_NULL ("failed to allocate space for k2", GSL_ENOMEM); } state->k3 = (double *) malloc (dim * sizeof (double)); if (state->k3 == 0) { free (state->k2); free (state->k1); free (state); GSL_ERROR_NULL ("failed to allocate space for k3", GSL_ENOMEM); } state->k4 = (double *) malloc (dim * sizeof (double)); if (state->k4 == 0) { free (state->k3); free (state->k2); free (state->k1); free (state); GSL_ERROR_NULL ("failed to allocate space for k4", GSL_ENOMEM); } state->k5 = (double *) malloc (dim * sizeof (double)); if (state->k5 == 0) { free (state->k4); free (state->k3); free (state->k2); free (state->k1); free (state); GSL_ERROR_NULL ("failed to allocate space for k5", GSL_ENOMEM); } state->k6 = (double *) malloc (dim * sizeof (double)); if (state->k6 == 0) { free (state->k5); free (state->k4); free (state->k3); free (state->k2); free (state->k1); free (state); GSL_ERROR_NULL ("failed to allocate space for k6", GSL_ENOMEM); } state->y0 = (double *) malloc (dim * sizeof (double)); if (state->y0 == 0) { free (state->k6); free (state->k5); free (state->k4); free (state->k3); free (state->k2); free (state->k1); free (state); GSL_ERROR_NULL ("failed to allocate space for y0", GSL_ENOMEM); } state->ytmp = (double *) malloc (dim * sizeof (double)); if (state->ytmp == 0) { free (state->y0); free (state->k6); free (state->k5); free (state->k4); free (state->k3); free (state->k2); free (state->k1); free (state); GSL_ERROR_NULL ("failed to allocate space for ytmp", GSL_ENOMEM); } return state; } static int rkck_apply (void *vstate, size_t dim, double t, double h, double y[], double yerr[], const double dydt_in[], double dydt_out[], const gsl_odeiv_system * sys) { rkck_state_t *state = (rkck_state_t *) vstate; size_t i; int status = 0; double *const k1 = state->k1; double *const k2 = state->k2; double *const k3 = state->k3; double *const k4 = state->k4; double *const k5 = state->k5; double *const k6 = state->k6; double *const ytmp = state->ytmp; /* k1 step */ if (dydt_in != NULL) { DBL_MEMCPY (k1, dydt_in, dim); } else { int s = GSL_ODEIV_FN_EVAL (sys, t, y, k1); GSL_STATUS_UPDATE (&status, s); } for (i = 0; i < dim; i++) ytmp[i] = y[i] + b21 * h * k1[i]; /* k2 step */ { int s = GSL_ODEIV_FN_EVAL (sys, t + ah[0] * h, ytmp, k2); GSL_STATUS_UPDATE (&status, s); } for (i = 0; i < dim; i++) ytmp[i] = y[i] + h * (b3[0] * k1[i] + b3[1] * k2[i]); /* k3 step */ { int s = GSL_ODEIV_FN_EVAL (sys, t + ah[1] * h, ytmp, k3); GSL_STATUS_UPDATE (&status, s); } for (i = 0; i < dim; i++) ytmp[i] = y[i] + h * (b4[0] * k1[i] + b4[1] * k2[i] + b4[2] * k3[i]); /* k4 step */ { int s = GSL_ODEIV_FN_EVAL (sys, t + ah[2] * h, ytmp, k4); GSL_STATUS_UPDATE (&status, s); } for (i = 0; i < dim; i++) ytmp[i] = y[i] + h * (b5[0] * k1[i] + b5[1] * k2[i] + b5[2] * k3[i] + b5[3] * k4[i]); /* k5 step */ { int s = GSL_ODEIV_FN_EVAL (sys, t + ah[3] * h, ytmp, k5); GSL_STATUS_UPDATE (&status, s); } for (i = 0; i < dim; i++) ytmp[i] = y[i] + h * (b6[0] * k1[i] + b6[1] * k2[i] + b6[2] * k3[i] + b6[3] * k4[i] + b6[4] * k5[i]); /* k6 step and final sum */ { int s = GSL_ODEIV_FN_EVAL (sys, t + ah[4] * h, ytmp, k6); GSL_STATUS_UPDATE (&status, s); } for (i = 0; i < dim; i++) { const double d_i = c1 * k1[i] + c3 * k3[i] + c4 * k4[i] + c6 * k6[i]; y[i] += h * d_i; if (dydt_out != NULL) dydt_out[i] = d_i; } /* difference between 4th and 5th order */ for (i = 0; i < dim; i++) yerr[i] = h * (ec[1] * k1[i] + ec[3] * k3[i] + ec[4] * k4[i] + ec[5] * k5[i] + ec[6] * k6[i]); return status; } static int rkck_reset (void *vstate, size_t dim) { rkck_state_t *state = (rkck_state_t *) vstate; DBL_ZERO_MEMSET (state->k1, dim); DBL_ZERO_MEMSET (state->k2, dim); DBL_ZERO_MEMSET (state->k3, dim); DBL_ZERO_MEMSET (state->k4, dim); DBL_ZERO_MEMSET (state->k5, dim); DBL_ZERO_MEMSET (state->k6, dim); DBL_ZERO_MEMSET (state->ytmp, dim); return GSL_SUCCESS; } static unsigned int rkck_order (void *vstate) { rkck_state_t *state = (rkck_state_t *) vstate; state = 0; /* prevent warnings about unused parameters */ return 5; } static void rkck_free (void *vstate) { rkck_state_t *state = (rkck_state_t *) vstate; free (state->ytmp); free (state->y0); free (state->k6); free (state->k5); free (state->k4); free (state->k3); free (state->k2); free (state->k1); free (state); } static const gsl_odeiv_step_type rkck_type = { "rkck", /* name */ 1, /* can use dydt_in */ 0, /* gives exact dydt_out */ &rkck_alloc, &rkck_apply, &rkck_reset, &rkck_order, &rkck_free }; const gsl_odeiv_step_type *gsl_odeiv_step_rkck = &rkck_type;
{ "alphanum_fraction": 0.5629444791, "avg_line_length": 24.6615384615, "ext": "c", "hexsha": "b869542b77733abbdaf298565c5d371846aada15", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2021-06-10T03:09:53.000Z", "max_forks_repo_forks_event_min_datetime": "2015-04-29T20:31:00.000Z", "max_forks_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "pvnuffel/test_repos", "max_forks_repo_path": "gsl_subset/ode-initval/rkck.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_issues_repo_issues_event_max_datetime": "2020-07-20T16:32:02.000Z", "max_issues_repo_issues_event_min_datetime": "2017-11-07T05:42:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "pvnuffel/test_repos", "max_issues_repo_path": "gsl_subset/ode-initval/rkck.c", "max_line_length": 77, "max_stars_count": 30, "max_stars_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "pvnuffel/test_repos", "max_stars_repo_path": "gsl_subset/ode-initval/rkck.c", "max_stars_repo_stars_event_max_datetime": "2022-03-21T02:07:41.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-29T05:13:02.000Z", "num_tokens": 2854, "size": 8015 }
/** @file */ #ifndef __CCL_LSST_SPECS_INCLUDED__ #define __CCL_LSST_SPECS_INCLUDED__ #include <gsl/gsl_integration.h> #include <gsl/gsl_spline.h> /** * We assume no relevant source redshift distributions exceed z= 5 */ #define Z_MIN_SOURCES 0. #define Z_MAX_SOURCES 5.0 CCL_BEGIN_DECLS /** * P(z) function. * This is a P(z) function (which can be user defined) * with a void* field to contain the parameters to that function. */ typedef struct { double (* your_pz_func)(double, double, void *, int*); /*< Function returns the likelihood of measuring a z_ph * (first double) given a z_spec (second double), with a pointer to additonal arguments and a status flag.*/ void * your_pz_params; /*< Additional parameters to be passed into your_pz_func */ } pz_info; /** * dNdz function. * This is a dNdz function (which can be user defined) * with a void* field to contain the parameters to that function. */ typedef struct { double (* your_dN_func)(double, void *, int*); /*< Function returns the differential number density of galaxies wrt redshifts, * with a pointer to additonal arguments and a status flag.*/ void * your_dN_params; /*< Additional parameters to be passed into your_dN_func */ } dNdz_info; /** * dNdz smail parmas structure. * This is a convenience parameters structure * to hold the three parameters of the Smail et al. analytic dNdz */ typedef struct{ double alpha; double beta; double z0; } smail_params; /** * Return dNdz in a particular tomographic bin, convolved with a photo-z model (defined by the user), and normalized. * @param z redshift * @param dNdz_type the choice of dN/dz from Chang+ * @param bin_zmin the minimum redshift of the tomorgraphic bin * @param bin_zmax the maximum redshift of the tomographic bin * @param photo_info the P(z) info struct * @param tomoout the output dN/dz * @param status Status flag. 0 if there are no errors, nonzero otherwise. * @return void */ void ccl_dNdz_tomog(double z, double bin_zmin, double bin_zmax, pz_info * photo_info, dNdz_info * dN_info, double *tomoout, int *status); /** * This function creates a structure amalgamating the information on an analytic true dNdz, plus some parameters. * @param params parameters for the analytic dNdz form * @param dNdz_func dNdz function * @return a structure with the dNdz and parameters */ dNdz_info* ccl_create_dNdz_info(void * params, double(*dNdz_func)(double,void*,int*)); /** * This function creates a structure containing the true dNdz for the built-in Smail-type analytic form: * dNdz ~ z^alpha exp(- (z/z0)^beta) * @param alpha * @param z0 * @param beta * @return a structure with the built-in Smail-type dNdz and parameters */ dNdz_info* ccl_create_Smail_dNdz_info(double alpha, double beta, double z0); /** Free memory holding the structure containing dNdz information. * @param dN_info that holds user-defined dNdz and parameters * @return void */ void ccl_free_dNdz_info(dNdz_info * dN_info); /** * This function creates a structure amalgamating the information on the photo-z model, P(z) plus some parameters. * @param params parameters for the P(z) function * @param pz_func P(z) function * @return a structure with the P(z) and parameters */ pz_info* ccl_create_photoz_info(void * params, double(*pz_func)(double, double,void*,int*)); /** * This function creates a structure containing the photo-z model for the built-in Gaussian photo-z pdf. * @param sigma_z0 The photo-z uncertainty at z=0. The photo-z uncertainty is assumed to scale like (1 + z). * @return a structure with the built-in Gaussian P(z) and parameters */ pz_info* ccl_create_gaussian_photoz_info(double sigma_z0); /** Free memory holding the structure containing user-input photoz information. * @param my_photoz_info that holds user-defined P(z) and parameters * @return void */ void ccl_free_photoz_info(pz_info *my_photoz_info); CCL_END_DECLS #endif
{ "alphanum_fraction": 0.7320490368, "avg_line_length": 34.7565217391, "ext": "h", "hexsha": "1710d3287c16183480bd2f4913770060cfd978b2", "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": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "vrastil/CCL", "max_forks_repo_path": "include/ccl_redshifts.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "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": "vrastil/CCL", "max_issues_repo_path": "include/ccl_redshifts.h", "max_line_length": 138, "max_stars_count": null, "max_stars_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "vrastil/CCL", "max_stars_repo_path": "include/ccl_redshifts.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1046, "size": 3997 }
#ifndef NEURAL_MATRIX_H_ #define NEURAL_MATRIX_H_ #include <vector> #include <functional> #include <iostream> #include <iomanip> #include <cmath> #include <cassert> #include <gsl/gsl_blas.h> namespace neural { class Matrix { double *_data; int _rows; int _cols; public: Matrix(int rows, int cols); Matrix(int rows, int cols, double val); Matrix(int rows, int cols, double data[]); Matrix(int rows, int cols, std::vector<double> data); Matrix(std::vector<std::vector<double>> data); /** * Copy and move semantics */ Matrix(const Matrix &rhs); Matrix(Matrix &&rhs); Matrix &operator=(const Matrix &rhs); Matrix &operator=(Matrix &&rhs); ~Matrix(); /** * Addition operator */ const Matrix operator+(const Matrix &rhs) const; /** * Subtraction operator */ const Matrix operator-(const Matrix &rhs) const; /** * Matrix multiplication */ const Matrix operator*(const Matrix &rhs) const; /** * Scale operator */ const Matrix operator*(const double factor) const; /** * Division operator */ const Matrix operator/(const double factor) const; /** * Hadamard operator */ const Matrix operator^(const Matrix &rhs) const; /** * In-place addition operator */ void operator+=(const Matrix &rhs); /** * In-place subtraction operator */ void operator-=(const Matrix &rhs); /** * In-place matrix multiplication */ void operator*=(const Matrix &rhs); /** * In-place scale operator */ void operator*=(const double factor); /** * In-place division operator */ void operator/=(const double factor); /** * In-place hadamard operator */ void operator^=(const Matrix &rhs); /** * Call a function on each item of the matrix */ void map(std::function<double(double&)> function); /** * Get the transpose of the matrix */ Matrix transpose() const; /** * Calculate the Euclidean norm of the matrix */ double norm(); /** * Make all values zero */ void zero(); /** * Fetch a value from the matrix */ inline double get_at(const int row, const int col) const { return _data[row * _cols + col]; } /** * Set a value in the matrix */ inline void set_at(const int row, const int col, const double value) { _data[row * _cols + col] = value; } /** * Get the number of rows in the matrix; */ inline int get_rows() const { return _rows; } /** * Get the number of columns in the matrix */ inline int get_cols() const { return _cols; } /** * Get the pointer to the matrix data */ inline double *data() const { return _data; } /** * Pretty print the matrix for debugging */ void print() const; }; } #endif
{ "alphanum_fraction": 0.4925629291, "avg_line_length": 22.1265822785, "ext": "h", "hexsha": "f9986502f04a8341b842fe06c356e9b76be66f7d", "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": "0309329aeda09ac2e9684a006c9a31d09027ab93", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "SirBob01/NeuralC", "max_forks_repo_path": "src/matrix.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0309329aeda09ac2e9684a006c9a31d09027ab93", "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": "SirBob01/NeuralC", "max_issues_repo_path": "src/matrix.h", "max_line_length": 78, "max_stars_count": 6, "max_stars_repo_head_hexsha": "0309329aeda09ac2e9684a006c9a31d09027ab93", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "SirBob01/NeuralC", "max_stars_repo_path": "src/matrix.h", "max_stars_repo_stars_event_max_datetime": "2020-07-31T23:20:24.000Z", "max_stars_repo_stars_event_min_datetime": "2019-04-23T10:57:07.000Z", "num_tokens": 709, "size": 3496 }
/* matrix/gsl_matrix_complex_long_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_MATRIX_COMPLEX_LONG_DOUBLE_H__ #define __GSL_MATRIX_COMPLEX_LONG_DOUBLE_H__ #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_vector_complex_long_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 size1; size_t size2; size_t tda; long double * data; gsl_block_complex_long_double * block; int owner; } gsl_matrix_complex_long_double ; typedef struct { gsl_matrix_complex_long_double matrix; } _gsl_matrix_complex_long_double_view; typedef _gsl_matrix_complex_long_double_view gsl_matrix_complex_long_double_view; typedef struct { gsl_matrix_complex_long_double matrix; } _gsl_matrix_complex_long_double_const_view; typedef const _gsl_matrix_complex_long_double_const_view gsl_matrix_complex_long_double_const_view; /* Allocation */ gsl_matrix_complex_long_double * gsl_matrix_complex_long_double_alloc (const size_t n1, const size_t n2); gsl_matrix_complex_long_double * gsl_matrix_complex_long_double_calloc (const size_t n1, const size_t n2); gsl_matrix_complex_long_double * gsl_matrix_complex_long_double_alloc_from_block (gsl_block_complex_long_double * b, const size_t offset, const size_t n1, const size_t n2, const size_t d2); gsl_matrix_complex_long_double * gsl_matrix_complex_long_double_alloc_from_matrix (gsl_matrix_complex_long_double * b, const size_t k1, const size_t k2, const size_t n1, const size_t n2); gsl_vector_complex_long_double * gsl_vector_complex_long_double_alloc_row_from_matrix (gsl_matrix_complex_long_double * m, const size_t i); gsl_vector_complex_long_double * gsl_vector_complex_long_double_alloc_col_from_matrix (gsl_matrix_complex_long_double * m, const size_t j); void gsl_matrix_complex_long_double_free (gsl_matrix_complex_long_double * m); /* Views */ _gsl_matrix_complex_long_double_view gsl_matrix_complex_long_double_submatrix (gsl_matrix_complex_long_double * m, const size_t i, const size_t j, const size_t n1, const size_t n2); _gsl_vector_complex_long_double_view gsl_matrix_complex_long_double_row (gsl_matrix_complex_long_double * m, const size_t i); _gsl_vector_complex_long_double_view gsl_matrix_complex_long_double_column (gsl_matrix_complex_long_double * m, const size_t j); _gsl_vector_complex_long_double_view gsl_matrix_complex_long_double_diagonal (gsl_matrix_complex_long_double * m); _gsl_vector_complex_long_double_view gsl_matrix_complex_long_double_subdiagonal (gsl_matrix_complex_long_double * m, const size_t k); _gsl_vector_complex_long_double_view gsl_matrix_complex_long_double_superdiagonal (gsl_matrix_complex_long_double * m, const size_t k); _gsl_vector_complex_long_double_view gsl_matrix_complex_long_double_subrow (gsl_matrix_complex_long_double * m, const size_t i, const size_t offset, const size_t n); _gsl_vector_complex_long_double_view gsl_matrix_complex_long_double_subcolumn (gsl_matrix_complex_long_double * m, const size_t j, const size_t offset, const size_t n); _gsl_matrix_complex_long_double_view gsl_matrix_complex_long_double_view_array (long double * base, const size_t n1, const size_t n2); _gsl_matrix_complex_long_double_view gsl_matrix_complex_long_double_view_array_with_tda (long double * base, const size_t n1, const size_t n2, const size_t tda); _gsl_matrix_complex_long_double_view gsl_matrix_complex_long_double_view_vector (gsl_vector_complex_long_double * v, const size_t n1, const size_t n2); _gsl_matrix_complex_long_double_view gsl_matrix_complex_long_double_view_vector_with_tda (gsl_vector_complex_long_double * v, const size_t n1, const size_t n2, const size_t tda); _gsl_matrix_complex_long_double_const_view gsl_matrix_complex_long_double_const_submatrix (const gsl_matrix_complex_long_double * m, const size_t i, const size_t j, const size_t n1, const size_t n2); _gsl_vector_complex_long_double_const_view gsl_matrix_complex_long_double_const_row (const gsl_matrix_complex_long_double * m, const size_t i); _gsl_vector_complex_long_double_const_view gsl_matrix_complex_long_double_const_column (const gsl_matrix_complex_long_double * m, const size_t j); _gsl_vector_complex_long_double_const_view gsl_matrix_complex_long_double_const_diagonal (const gsl_matrix_complex_long_double * m); _gsl_vector_complex_long_double_const_view gsl_matrix_complex_long_double_const_subdiagonal (const gsl_matrix_complex_long_double * m, const size_t k); _gsl_vector_complex_long_double_const_view gsl_matrix_complex_long_double_const_superdiagonal (const gsl_matrix_complex_long_double * m, const size_t k); _gsl_vector_complex_long_double_const_view gsl_matrix_complex_long_double_const_subrow (const gsl_matrix_complex_long_double * m, const size_t i, const size_t offset, const size_t n); _gsl_vector_complex_long_double_const_view gsl_matrix_complex_long_double_const_subcolumn (const gsl_matrix_complex_long_double * m, const size_t j, const size_t offset, const size_t n); _gsl_matrix_complex_long_double_const_view gsl_matrix_complex_long_double_const_view_array (const long double * base, const size_t n1, const size_t n2); _gsl_matrix_complex_long_double_const_view gsl_matrix_complex_long_double_const_view_array_with_tda (const long double * base, const size_t n1, const size_t n2, const size_t tda); _gsl_matrix_complex_long_double_const_view gsl_matrix_complex_long_double_const_view_vector (const gsl_vector_complex_long_double * v, const size_t n1, const size_t n2); _gsl_matrix_complex_long_double_const_view gsl_matrix_complex_long_double_const_view_vector_with_tda (const gsl_vector_complex_long_double * v, const size_t n1, const size_t n2, const size_t tda); /* Operations */ void gsl_matrix_complex_long_double_set_zero (gsl_matrix_complex_long_double * m); void gsl_matrix_complex_long_double_set_identity (gsl_matrix_complex_long_double * m); void gsl_matrix_complex_long_double_set_all (gsl_matrix_complex_long_double * m, gsl_complex_long_double x); int gsl_matrix_complex_long_double_fread (FILE * stream, gsl_matrix_complex_long_double * m) ; int gsl_matrix_complex_long_double_fwrite (FILE * stream, const gsl_matrix_complex_long_double * m) ; int gsl_matrix_complex_long_double_fscanf (FILE * stream, gsl_matrix_complex_long_double * m); int gsl_matrix_complex_long_double_fprintf (FILE * stream, const gsl_matrix_complex_long_double * m, const char * format); int gsl_matrix_complex_long_double_memcpy(gsl_matrix_complex_long_double * dest, const gsl_matrix_complex_long_double * src); int gsl_matrix_complex_long_double_swap(gsl_matrix_complex_long_double * m1, gsl_matrix_complex_long_double * m2); int gsl_matrix_complex_long_double_swap_rows(gsl_matrix_complex_long_double * m, const size_t i, const size_t j); int gsl_matrix_complex_long_double_swap_columns(gsl_matrix_complex_long_double * m, const size_t i, const size_t j); int gsl_matrix_complex_long_double_swap_rowcol(gsl_matrix_complex_long_double * m, const size_t i, const size_t j); int gsl_matrix_complex_long_double_transpose (gsl_matrix_complex_long_double * m); int gsl_matrix_complex_long_double_transpose_memcpy (gsl_matrix_complex_long_double * dest, const gsl_matrix_complex_long_double * src); int gsl_matrix_complex_long_double_equal (const gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b); int gsl_matrix_complex_long_double_isnull (const gsl_matrix_complex_long_double * m); int gsl_matrix_complex_long_double_ispos (const gsl_matrix_complex_long_double * m); int gsl_matrix_complex_long_double_isneg (const gsl_matrix_complex_long_double * m); int gsl_matrix_complex_long_double_isnonneg (const gsl_matrix_complex_long_double * m); int gsl_matrix_complex_long_double_add (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b); int gsl_matrix_complex_long_double_sub (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b); int gsl_matrix_complex_long_double_mul_elements (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b); int gsl_matrix_complex_long_double_div_elements (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b); int gsl_matrix_complex_long_double_scale (gsl_matrix_complex_long_double * a, const gsl_complex_long_double x); int gsl_matrix_complex_long_double_add_constant (gsl_matrix_complex_long_double * a, const gsl_complex_long_double x); int gsl_matrix_complex_long_double_add_diagonal (gsl_matrix_complex_long_double * a, const gsl_complex_long_double x); /***********************************************************************/ /* The functions below are obsolete */ /***********************************************************************/ int gsl_matrix_complex_long_double_get_row(gsl_vector_complex_long_double * v, const gsl_matrix_complex_long_double * m, const size_t i); int gsl_matrix_complex_long_double_get_col(gsl_vector_complex_long_double * v, const gsl_matrix_complex_long_double * m, const size_t j); int gsl_matrix_complex_long_double_set_row(gsl_matrix_complex_long_double * m, const size_t i, const gsl_vector_complex_long_double * v); int gsl_matrix_complex_long_double_set_col(gsl_matrix_complex_long_double * m, const size_t j, const gsl_vector_complex_long_double * v); /***********************************************************************/ /* inline functions if you are using GCC */ INLINE_DECL gsl_complex_long_double gsl_matrix_complex_long_double_get(const gsl_matrix_complex_long_double * m, const size_t i, const size_t j); INLINE_DECL void gsl_matrix_complex_long_double_set(gsl_matrix_complex_long_double * m, const size_t i, const size_t j, const gsl_complex_long_double x); INLINE_DECL gsl_complex_long_double * gsl_matrix_complex_long_double_ptr(gsl_matrix_complex_long_double * m, const size_t i, const size_t j); INLINE_DECL const gsl_complex_long_double * gsl_matrix_complex_long_double_const_ptr(const gsl_matrix_complex_long_double * m, const size_t i, const size_t j); #ifdef HAVE_INLINE INLINE_FUN gsl_complex_long_double gsl_matrix_complex_long_double_get(const gsl_matrix_complex_long_double * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(1)) { gsl_complex_long_double zero = {{0,0}}; if (i >= m->size1) { GSL_ERROR_VAL("first index out of range", GSL_EINVAL, zero) ; } else if (j >= m->size2) { GSL_ERROR_VAL("second index out of range", GSL_EINVAL, zero) ; } } #endif return *(gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) ; } INLINE_FUN void gsl_matrix_complex_long_double_set(gsl_matrix_complex_long_double * m, const size_t i, const size_t j, const gsl_complex_long_double 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 *(gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) = x ; } INLINE_FUN gsl_complex_long_double * gsl_matrix_complex_long_double_ptr(gsl_matrix_complex_long_double * 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 (gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) ; } INLINE_FUN const gsl_complex_long_double * gsl_matrix_complex_long_double_const_ptr(const gsl_matrix_complex_long_double * 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 gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) ; } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_MATRIX_COMPLEX_LONG_DOUBLE_H__ */
{ "alphanum_fraction": 0.7085550825, "avg_line_length": 42.7045454545, "ext": "h", "hexsha": "9e2c3dbe19c5c7f966296069dc379db9f2954dd1", "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_matrix_complex_long_double.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_matrix_complex_long_double.h", "max_line_length": 159, "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_matrix_complex_long_double.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3226, "size": 15032 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #define DECORRCRITS 1 #define SET 1 int pcl_ran_mvgaussian(gsl_rng *rseed, gsl_vector *mean, gsl_matrix *Sigma, gsl_vector *output) { int i; gsl_linalg_cholesky_decomp(Sigma); for (i = 0; i < output->size; i++){ gsl_vector_set (output, i , gsl_ran_gaussian(rseed,1)); } gsl_blas_dtrmv (CblasLower, CblasNoTrans, CblasNonUnit, Sigma, output); gsl_blas_daxpy (1.0,mean, output); return 0; } unsigned long int random_seed() { unsigned int seed; FILE *devrandom; if ((devrandom = fopen("/dev/random","r")) == NULL) { fprintf(stderr,"Cannot open /dev/random, setting seed to 0\n"); seed = 0; } else { fread(&seed,sizeof(seed),1,devrandom); fclose(devrandom); } return(seed); } double ran_inv_gamma(const gsl_rng * r, double a, double b){ return(1/gsl_ran_gamma(r, a, 1/b)); } double ran_trunc_norm_upper(const gsl_rng * r, double mu, double sigma, double a){ double u = gsl_rng_uniform_pos(r); double v = gsl_cdf_ugaussian_P((-a+mu)/sigma); return(-sigma * gsl_cdf_ugaussian_Pinv(u*v)+mu); } double ran_trunc_norm_lower(const gsl_rng * r, double mu, double sigma, double a){ double u = gsl_rng_uniform_pos(r); double v = gsl_cdf_ugaussian_P((a-mu)/sigma); return(sigma * gsl_cdf_ugaussian_Pinv(u*v)+mu); } double ran_trunc_norm_both(const gsl_rng * r, double mu, double sigma, double a, double b){ double low = gsl_cdf_ugaussian_P((a-mu)/sigma); double high = gsl_cdf_ugaussian_P((b-mu)/sigma); double u = gsl_ran_flat(r,low,high); return(sigma * gsl_cdf_ugaussian_Pinv(u)+mu); } int main(int argc, char *argv[]){ unsigned long int seed; seed = random_seed(); int ITERS,iter,i,j,k,K,I,J,nRespCat; char *fnEstimates,*fnChains,*fnInput; int yij,sij; int errs=0; char *name; double a,b,e,f,sigDecorr,mu_crits,sd_crits; double sig2mu,mumu; ////This is all data and prior entry code. if(argc<9){ fprintf(stderr,"Arguments needed: #iterations nRespCat sig2_mu a b e f sigDecorr [analysis.name] [input.file]\n"); fprintf(stderr,"\n****Not enough arguments.\n\n"); return(1); } if(argc>9){ name=argv[9]; }else{ name="analysis"; } ITERS=atoi(argv[1]); nRespCat=atoi(argv[2]); sig2mu=atof(argv[3]); a=atof(argv[4]); b=atof(argv[5]); e=atof(argv[6]); f=atof(argv[7]); sigDecorr=atof(argv[8]); //confirm and check command line arguments. printf("Name : %s\n",name); printf("nRespCat = %i\n",nRespCat); printf("sig2mu = %.2f\n",sig2mu); printf("a = %.2f\n",a); printf("b = %.2f\n",b); printf("e = %.2f\n",e); printf("f = %.2f\n",f); printf("sigDecorr= %.2f\n",sigDecorr); if(nRespCat<=0){printf("\n*****nRespCat must be greater than 0.\n");errs++;} if(sig2mu<=0){printf("\n*****sig2mu must be greater than 0.\n");errs++;} if(a<=0){printf("\n*****a must be greater than 0.\n");errs++;} if(b<=0){printf("\n*****b must be greater than 0.\n");errs++;} if(e<=0){printf("\n*****e must be greater than 0.\n");errs++;} if(f<=0){printf("\n*****f must be greater than 0.\n");errs++;} if(sigDecorr<=0){printf("\n*****sigDecorr must be greater than 0.\n");errs++;} if(errs>0){printf("Exiting...\n\n");exit(1);} asprintf(&fnEstimates,"%s.est",name); asprintf(&fnChains,"%s.chn",name); if(argc>10){ fnInput=argv[10]; }else{ asprintf(&fnInput,"%s.dat",name); } K=nRespCat-1; //open files. FILE *CHAINS; if ((CHAINS = fopen(fnChains,"w")) == NULL) { fprintf(stderr,"\n****Cannot open chain output file!\n\n"); return(1); } FILE *ESTIMATES; if ((ESTIMATES = fopen(fnEstimates,"w")) == NULL) { fprintf(stderr,"\n****Cannot open estimate output file!\n\n"); fclose(CHAINS); return(1); } FILE *INPUT; if ((INPUT = fopen(fnInput,"r")) == NULL) { fprintf(stderr,"\n****Cannot open input file %s!\n\n",fnInput); fclose(CHAINS); fclose(ESTIMATES); return(1); } //Now that we have opened the files, get the data. i=0; int newline=0,spaces=0; int got; while(!newline&&!feof(INPUT)){ i++; got=fgetc(INPUT); //printf("Character %i: %i %c\n",i,got,got); if(got==32) spaces++; if(got==10) newline=1; } rewind(INPUT); if(!newline){ printf("Could not determine number of conditions!\n"); exit(1); } J=(spaces+1)/2; i=0; int totsig=0; int totnoi=0; printf("Reading data...\n"); while(!feof(INPUT)){ for(j=0;j<J;j++){ if(j==(J-1)){ fscanf(INPUT,"%i %i\n",&yij,&sij); }else{ fscanf(INPUT,"%i %i ",&yij,&sij); } if((yij>=nRespCat)||(sij!=0&&sij!=1)){ printf("\n****Invalid data for participant %i, item %i: (yij=%i,sij=%i)\n\n",i+1,j+1,yij,sij); fclose(CHAINS); fclose(ESTIMATES); fclose(INPUT); return(1); } if(yij!=-1){ totsig+=sij; totnoi+=1-sij; } } i++; } rewind(INPUT); I=i; //printf("Read %d subjects and %d items, with %d total signal trials.\n",I,J,totsig); //initialize matrices printf("Reserving memory for matrices...\n"); int Ys[totsig],Yn[totnoi],Subs[totsig],Subn[totnoi]; gsl_vector *Ws,*Wn,*Ts,*Tn,*WsMean,*WnMean,*WsDev,*TsMean,*TnMean; gsl_matrix *Xs,*Xn,*Ss,*Sn,*TpSs,*TpSn,*XstXs,*XntXn,*Vs,*Vn; Xs = gsl_matrix_calloc(totsig, I+J+1); Xn = gsl_matrix_calloc(totnoi, I+J+1); XstXs = gsl_matrix_calloc(I+J+1, I+J+1); XntXn = gsl_matrix_calloc(I+J+1, I+J+1); Vs = gsl_matrix_calloc(I+J+1, I+J+1); Vn = gsl_matrix_calloc(I+J+1, I+J+1); gsl_matrix *Vn0 = gsl_matrix_calloc(I+J+1, I+J+1); gsl_matrix *Vs0 = gsl_matrix_calloc(I+J+1, I+J+1); Ws = gsl_vector_calloc(totsig); Wn = gsl_vector_calloc(totnoi); Ts = gsl_vector_calloc(I+J+1); Tn = gsl_vector_calloc(I+J+1); WsMean = gsl_vector_calloc(totsig); WnMean = gsl_vector_calloc(totnoi); WsDev = gsl_vector_calloc(totsig); TsMean= gsl_vector_calloc(I+J+1); TnMean= gsl_vector_calloc(I+J+1); gsl_vector *TsMean0= gsl_vector_calloc(I+J+1); gsl_vector *TnMean0= gsl_vector_calloc(I+J+1); gsl_vector *isAlph = gsl_vector_calloc(I+J+1); gsl_vector *isBeta = gsl_vector_calloc(I+J+1); TpSs = gsl_matrix_calloc(I+J+1,I+J+1); TpSn = gsl_matrix_calloc(I+J+1,I+J+1); gsl_matrix_set_identity(TpSs); gsl_matrix_set_identity(TpSn); Ss = gsl_matrix_calloc(totsig, totsig); gsl_matrix_set_identity(Ss); Sn = gsl_matrix_calloc(totnoi, totnoi); gsl_matrix_set_identity(Sn); gsl_permutation *gslPerm = gsl_permutation_alloc(I+J+1); gsl_permutation_init(gslPerm); gsl_matrix_set(TpSs,0,0,1.0/sig2mu); gsl_matrix_set(TpSn,0,0,1.0/sig2mu); //end initialize matrices printf("Creating design matrix...\n"); int y[I][J],s[I][J],sigindex=0,noiindex=0; i=0; while(!feof(INPUT)){ for(j=0;j<J;j++){ if(j==(J-1)){ fscanf(INPUT,"%i %i\n",&yij,&sij); }else{ fscanf(INPUT,"%i %i ",&yij,&sij); } y[i][j]=yij; s[i][j]=sij; if(yij!=-1){ if(sij){ Ys[sigindex] = y[i][j]; Subs[sigindex] = i; gsl_matrix_set(Xs,sigindex,0,1); gsl_matrix_set(Xs,sigindex,i+1,1); gsl_matrix_set(Xs,sigindex++,I+1+j,1); }else{ Yn[noiindex] = y[i][j]; Subn[noiindex] = i; gsl_matrix_set(Xn,noiindex,0,1); gsl_matrix_set(Xn,noiindex,i+1,1); gsl_matrix_set(Xn,noiindex++,I+1+j,1); } } } i++; } gsl_blas_dgemm(CblasTrans,CblasNoTrans,1,Xn,Xn,1,XntXn); gsl_blas_dgemm(CblasTrans,CblasNoTrans,1,Xs,Xs,1,XstXs); //gsl_vector_set(Tn,0,-.6); //gsl_vector_set(Ts,0,.6); //gsl_matrix_fprintf(stdout,Xs,"%f"); //exit(0); printf("Read %i subjects values for %i items.\n\n",I,J); fclose(INPUT); ////End data entry. //Create starting values int keq0=0; double crits[I][K],critCand[I][K],w[I][J]; double maxw[I][K+1]; double minw[I][K+1]; double sig2=1; double sumWnSqr=0,sumWsSqr=0; int nSignal[I],totSignal=0; int nRespS[I][K+1]; int nRespN[I][K+1]; double sumwN[I]; double sumwS[I]; double zDecorr[I][K]; double sig2N=1; double sig2beta0=.2,sig2beta1=.2,sig2alph0=.2,sig2alph1=.2; double bDecorr[I]; int accDecorr[I],badCrits[I]; double decorrRate=0,sumAlp20=0,sumAlp21=0,sumBet20=0,sumBet21=0; for(i=0;i<I;i++){ accDecorr[i]=0; nSignal[i]=0; nRespN[i][K]=0; nRespS[i][K]=0; crits[i][0]=0; crits[i][K-1]=SET; for(k=0;k<K;k++){ nRespS[i][k]=0; nRespN[i][k]=0; if(k!=0 && k<(K-1)){ crits[i][k]=k*SET/((float)(K-1)); //printf("i: %i k: %i crit: %f\n",i,k,crits[i][k]); } } for(j=0;j<J;j++){ nSignal[i]+=s[i][j]; totSignal+=s[i][j]; if(y[i][j]!=-1){ nRespN[i][y[i][j]]+=1-s[i][j]; nRespS[i][y[i][j]]+=s[i][j]; } } } //for(k=0;k<(K+1);k++) //{ // printf("nRespN[0][%d]=%d\n",k,nRespN[0][k]); // printf("nRespS[0][%d]=%d\n",k,nRespS[0][k]); //} //end starting values //Initialize GSL const gsl_rng_type * T; gsl_rng * r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc (T); //gsl_rng_set(r,seed); gsl_rng_set(r,0); gsl_blas_dgemv(CblasNoTrans,1,Xs,Ts,0,WsMean); gsl_blas_dgemv(CblasNoTrans,1,Xn,Tn,0,WnMean); printf("Total signal trials: %i\nTotal noise trials: %i\n\n",totsig,totnoi); //begin MCMC loop. i=0; printf("Starting %i MCMC iterations...\n",ITERS); for(iter=0;iter<ITERS;iter++){ for(i=0;i<I;i++){ sumwS[i]=0; sumwN[i]=0; for(k=0;k<(K+1);k++){ minw[i][k]=GSL_POSINF; maxw[i][k]=GSL_NEGINF; } } //sig2=1; //sample latent variables for(i=0;i<totsig;i++){ //printf("%d %d %f %f\n",Ys[i],Subs[i],crits[Subs[i]][0],crits[Subs[i]][1]); if( Ys[i]==0 ){ gsl_vector_set(Ws,i,ran_trunc_norm_lower(r, gsl_vector_get(WsMean,i), sqrt(sig2), crits[Subs[i]][0])); if(gsl_vector_get(Ws,i)>maxw[Subs[i]][0]) { maxw[Subs[i]][0]=gsl_vector_get(Ws,i);} }else if( Ys[i]==K ){ gsl_vector_set(Ws,i,ran_trunc_norm_upper(r, gsl_vector_get(WsMean,i), sqrt(sig2), crits[Subs[i]][K-1])); if(gsl_vector_get(Ws,i)<minw[Subs[i]][K]) { minw[Subs[i]][K]=gsl_vector_get(Ws,i);} }else{ gsl_vector_set(Ws,i,ran_trunc_norm_both(r, gsl_vector_get(WsMean,i), sqrt(sig2), crits[Subs[i]][Ys[i]-1],crits[Subs[i]][Ys[i]])); if(gsl_vector_get(Ws,i)>maxw[Subs[i]][Ys[i]]) { maxw[Subs[i]][Ys[i]]=gsl_vector_get(Ws,i);} if(gsl_vector_get(Ws,i)<minw[Subs[i]][Ys[i]]) { minw[Subs[i]][Ys[i]]=gsl_vector_get(Ws,i);} } } for(i=0;i<totnoi;i++){ //if(i==511) printf("%d %d %f %f\n",Yn[i],Subn[i],crits[Subn[i]][Yn[i]-1],crits[Subs[i]][Yn[i]]); if( Yn[i]==0 ){ gsl_vector_set(Wn,i,ran_trunc_norm_lower(r, gsl_vector_get(WnMean,i), sqrt(sig2N), crits[Subn[i]][0])); if(gsl_vector_get(Wn,i)>maxw[Subn[i]][0]) { maxw[Subn[i]][0]=gsl_vector_get(Wn,i);} }else if( Yn[i]==K ){ gsl_vector_set(Wn,i,ran_trunc_norm_upper(r, gsl_vector_get(WnMean,i), sqrt(sig2N), crits[Subn[i]][K-1])); if(gsl_vector_get(Wn,i)<minw[Subn[i]][K]) { minw[Subn[i]][K]=gsl_vector_get(Wn,i);} }else{ gsl_vector_set(Wn,i,ran_trunc_norm_both(r, gsl_vector_get(WnMean,i), sqrt(sig2N), crits[Subn[i]][Yn[i]-1],crits[Subn[i]][Yn[i]])); if(gsl_vector_get(Wn,i)>maxw[Subn[i]][Yn[i]]) { maxw[Subn[i]][Yn[i]]=gsl_vector_get(Wn,i);} if(gsl_vector_get(Wn,i)<minw[Subn[i]][Yn[i]]) { minw[Subn[i]][Yn[i]]=gsl_vector_get(Wn,i);} } } //printf("***\n"); //gsl_vector_fprintf(stderr,Wn,"%f"); //gsl_vector_fprintf(stderr,WnMean,"%f"); //for(i=0;i<totnoi;i++) printf("%i : %f\n",i,gsl_vector_get(WnMean,i)); gsl_blas_daxpy(-1,Ws,WsMean); gsl_blas_daxpy(-1,Wn,WnMean); gsl_blas_ddot(WsMean,WsMean,&sumWsSqr); gsl_blas_ddot(WnMean,WnMean,&sumWnSqr); //gsl_vector_fprintf(stderr,WnMean,"%f"); //for(i=0;i<totnoi;i++) printf("%i : %f\n",i,gsl_vector_get(Wn,i)); //printf("\nSS: %f,%f,%f,%d\n--------\n",sumWnSqr,a,b,totnoi); //sample sigma^2 sig2=ran_inv_gamma(r, a+.5*totsig,b+(.5*sumWsSqr)); //sig2=1; //printf("IG: %f %f\n",a0+.5*totSignal,(1.0)*b0+(.5*sumWSqr)); //sig2=1.3; fwrite(&sig2,sizeof(double),1,CHAINS); sig2N=ran_inv_gamma(r, a+.5*totnoi,b+(.5*sumWnSqr)); fwrite(&sig2N,sizeof(double),1,CHAINS); // set up variances for full conditional on parameter vector for(i=0;i<(I+J+1);i++){ if(i>I){ gsl_matrix_set(TpSs,i,i,1.0/sig2beta1); gsl_matrix_set(TpSn,i,i,1.0/sig2beta0); }else if(i>0){ gsl_matrix_set(TpSs,i,i,1.0/sig2alph1); gsl_matrix_set(TpSn,i,i,1.0/sig2alph0); } //printf("i: %d | %f\n",i,gsl_matrix_get(TpSs,i,i)); } gsl_matrix_memcpy(Vs,TpSs); gsl_matrix_memcpy(Vn,TpSn); gsl_matrix_scale(Vs,sig2); gsl_matrix_scale(Vn,sig2N); gsl_matrix_add(Vn,XntXn); gsl_matrix_add(Vs,XstXs); gsl_matrix_scale(Vs,1.0/sig2); gsl_matrix_scale(Vn,1.0/sig2N); //for(i=0;i<(I+J+1);i++){ // for(j=0;j<(I+J+1);j++){ // printf("%f ",gsl_matrix_get(Vs,i,j)); // } // printf("\n"); //} gsl_linalg_LU_decomp(Vn,gslPerm,&i); gsl_linalg_LU_invert(Vn,gslPerm,Vn0); gsl_linalg_LU_decomp(Vs,gslPerm,&i); gsl_linalg_LU_invert(Vs,gslPerm,Vs0); //for(i=0;i<(I+J+1);i++){ // for(j=0;j<(I+J+1);j++){ // printf("%f ",gsl_matrix_get(Vs0,i,j)); // } // printf("\n"); //} //sample parameter vectors gsl_blas_dgemv(CblasTrans,1.0/sig2,Xs,Ws,0,TsMean); gsl_blas_dgemv(CblasNoTrans,1,Vs0,TsMean,0,TsMean0); gsl_blas_dgemv(CblasTrans,1.0/sig2N,Xn,Wn,0,TnMean); gsl_blas_dgemv(CblasNoTrans,1,Vn0,TnMean,0,TnMean0); pcl_ran_mvgaussian(r, TsMean0, Vs0, Ts); pcl_ran_mvgaussian(r, TnMean0, Vn0, Tn); gsl_vector_fwrite(CHAINS,Ts); gsl_vector_fwrite(CHAINS,Tn); //Sample variances of parameters sumAlp20=0; sumAlp21=0; sumBet20=0; sumBet21=0; for(i=0;i<(I+J+1);i++){ if(i>I){ sumBet20+=pow(gsl_vector_get(Tn,i),2); sumBet21+=pow(gsl_vector_get(Ts,i),2); }else if(i>0){ sumAlp20+=pow(gsl_vector_get(Tn,i),2); sumAlp21+=pow(gsl_vector_get(Ts,i),2); } } //printf("%f\n",sumBet20); //sample sigma^2 sig2alph0=ran_inv_gamma(r, e+.5*I,f+(.5*sumAlp20)); sig2alph1=ran_inv_gamma(r, e+.5*I,f+(.5*sumAlp21)); sig2beta0=ran_inv_gamma(r, e+.5*J,f+(.5*sumBet20)); sig2beta1=ran_inv_gamma(r, e+.5*J,f+(.5*sumBet21)); //printf("IG: %f %f\n",a0+.5*totSignal,(1.0)*b0+(.5*sumWSqr)); //sig2=1.3; fwrite(&sig2alph0,sizeof(double),1,CHAINS); fwrite(&sig2alph1,sizeof(double),1,CHAINS); fwrite(&sig2beta0,sizeof(double),1,CHAINS); fwrite(&sig2beta1,sizeof(double),1,CHAINS); gsl_blas_dgemv(CblasNoTrans,1,Xs,Ts,0,WsMean); gsl_blas_dgemv(CblasNoTrans,1,Xn,Tn,0,WnMean); //gsl_vector_fprintf(stderr,WsMean,"%f"); //printf("\n\n"); //gsl_vector_fprintf(stderr,WnMean,"%f"); //printf("\n\n"); //gsl_vector_fprintf(stderr,WsMean,"%g"); //printf("\ns2=%f\n%f %f,%f %f\n",sig2,sumwN[i]/(1.0*(J-nSignal[i])),1.0/sqrt(1.0*(J-nSignal[i])),sumwS[i]/(1.0*nSignal[i]),sqrt(sig2/(1.0*(nSignal[i])))); //sample criteria for(i=0;i<I;i++){ //zDecorr[i]=gsl_ran_gaussian(r,sigDecorr); bDecorr[i]=1; badCrits[i]=0; crits[i][0]=0; crits[i][K-1]=SET; for(k=0;k<K;k++){ zDecorr[i][k]=gsl_ran_gaussian(r,sigDecorr); //printf("i=%d k=%i max=%f min=%f\n",i,k,maxw[i][k],minw[i][k+1]); //if((k!=0) && (k!=(K-1))) crits[i][k]=(gsl_rng_uniform_pos(r)*(minw[i][k+1]-maxw[i][k])+maxw[i][k]); //crits[i][k]=ran_trunc_norm_both(r,mu_crits,sd_crits,maxw[i][k],minw[i][k+1])*(k!=keq0); //printf("newcrit: %f\n",crits[i][k]); //for decorrelating critCand[i][k]=crits[i][k]+zDecorr[i][k]*(k!=0 && k!=(K-1)); //bDecorr[i]=bDecorr[i]*exp(-.5*pow((critCand[i][k]-mu_crits)/sd_crits,2)+.5*pow((crits[i][k]-mu_crits)/sd_crits,2)); //printf("candcrit: %f\n",critCand[i][k]); if(k>0 && critCand[i][k]<critCand[i][k-1] ) badCrits[i]=1; //printf("CRITS: %d %d d:%f s:%f : %f %f\n",iter,k,ds[i],sig2,crits[i][k],critCand[i][k]); } } if(DECORRCRITS){ for(i=0;i<totsig;i++){ if(!badCrits[Subs[i]]) if(Ys[i]==0){ bDecorr[Subs[i]]=bDecorr[Subs[i]]*( gsl_cdf_ugaussian_P((critCand[Subs[i]][0]-gsl_vector_get(WsMean,i))/sqrt(sig2)) / gsl_cdf_ugaussian_P((crits[Subs[i]][0] -gsl_vector_get(WsMean,i))/sqrt(sig2)) ); }else if(Ys[i]==K){ bDecorr[Subs[i]]=bDecorr[Subs[i]]*( (1-gsl_cdf_ugaussian_P((critCand[Subs[i]][K-1]-gsl_vector_get(WsMean,i))/sqrt(sig2))) / (1-gsl_cdf_ugaussian_P((crits[Subs[i]][K-1] -gsl_vector_get(WsMean,i))/sqrt(sig2))) ); }else{ bDecorr[Subs[i]]=bDecorr[Subs[i]]*( (gsl_cdf_ugaussian_P((critCand[Subs[i]][Ys[i]]-gsl_vector_get(WsMean,i))/sqrt(sig2)) - gsl_cdf_ugaussian_P((critCand[Subs[i]][Ys[i]-1]-gsl_vector_get(WsMean,i))/sqrt(sig2))) / (gsl_cdf_ugaussian_P((crits[Subs[i]][Ys[i]] -gsl_vector_get(WsMean,i))/sqrt(sig2)) - gsl_cdf_ugaussian_P((crits[Subs[i]][Ys[i]-1] -gsl_vector_get(WsMean,i))/sqrt(sig2))) ); } } for(i=0;i<totnoi;i++){ if(!badCrits[Subn[i]]) if(Yn[i]==0){ bDecorr[Subn[i]]=bDecorr[Subn[i]]*( gsl_cdf_ugaussian_P((critCand[Subn[i]][0]-gsl_vector_get(WnMean,i))/sqrt(sig2N)) / gsl_cdf_ugaussian_P((crits[Subn[i]][0] -gsl_vector_get(WnMean,i))/sqrt(sig2N)) ); }else if(Yn[i]==K){ bDecorr[Subn[i]]=bDecorr[Subn[i]]*( (1-gsl_cdf_ugaussian_P((critCand[Subn[i]][K-1]-gsl_vector_get(WnMean,i))/sqrt(sig2N))) / (1-gsl_cdf_ugaussian_P((crits[Subn[i]][K-1] -gsl_vector_get(WnMean,i))/sqrt(sig2N))) ); }else{ bDecorr[Subn[i]]=bDecorr[Subn[i]]*( (gsl_cdf_ugaussian_P((critCand[Subn[i]][Yn[i]]-gsl_vector_get(WnMean,i))/sqrt(sig2N)) - gsl_cdf_ugaussian_P((critCand[Subn[i]][Yn[i]-1]-gsl_vector_get(WnMean,i))/sqrt(sig2N))) / (gsl_cdf_ugaussian_P((crits[Subn[i]][Yn[i]] -gsl_vector_get(WnMean,i))/sqrt(sig2N)) - gsl_cdf_ugaussian_P((crits[Subn[i]][Yn[i]-1] -gsl_vector_get(WnMean,i))/sqrt(sig2N))) ); } } //for(i=0;i<I;i++) //for(k=0;k<K;k++) //printf("m: %d, i: %d, k: %d, z: %f crit: %f cand: %f, BAD: %d\n",iter,i,k,zDecorr[i][k],crits[i][k],critCand[i][k],badCrits[i]); for(i=0;i<I;i++){ if(!badCrits[i]){ accDecorr[i]=gsl_ran_bernoulli(r,(bDecorr[i]>1)?1:bDecorr[i]); //printf("BDECORR: m%d i%d bdecorr %f\n",iter,i,bDecorr[i]); if(accDecorr[i]){ decorrRate+=1/(1.0*I*ITERS); for(k=0;k<K;k++){ //printf("m: %d, i: %d, k: %d, z: %f crit: %f cand: %f\n",iter,i,k,zDecorr[i][k],crits[i][k],critCand[i][k]); crits[i][k]=critCand[i][k]; } } } } } fwrite(crits,sizeof(double),I*K,CHAINS); if(!((iter+1)%25)) { printf("Iteration %i\n",iter+1); } }//End MCMC loop printf("\nDone. Decorrelating step acceptance rate: %f\n\n",decorrRate); //close files fclose(ESTIMATES); fclose(CHAINS); return 0; }
{ "alphanum_fraction": 0.580840103, "avg_line_length": 30.4036144578, "ext": "c", "hexsha": "62d643be81daa79f9dfde084f492303eb16858a1", "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": "0f8c473961c4c7979599f579a2e7bbabb010a2e9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "richarddmorey/ConfidenceRatingsSigDet", "max_forks_repo_path": "sd2.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0f8c473961c4c7979599f579a2e7bbabb010a2e9", "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": "richarddmorey/ConfidenceRatingsSigDet", "max_issues_repo_path": "sd2.c", "max_line_length": 190, "max_stars_count": null, "max_stars_repo_head_hexsha": "0f8c473961c4c7979599f579a2e7bbabb010a2e9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "richarddmorey/ConfidenceRatingsSigDet", "max_stars_repo_path": "sd2.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 7521, "size": 20188 }
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch 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, 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 _SYMBOLS_H #define _SYMBOLS_H #include <gsl/gsl_complex.h> #include "liboct_parser.h" typedef enum{ S_CMPLX, S_STR, S_BLOCK, S_FNCT } symrec_type; /* Data type for links in the chain of symbols. */ typedef struct symrec{ char *name; /* name of symbol */ symrec_type type; /* type of symbol: complex, string, block, or function */ int def; /* has this symbol been defined */ int used; /* this symbol has been used before */ int nargs; /* if type==S_FNCT contains the number of arguments of the function */ union { gsl_complex c; /* value of a S_CMPLX */ char *str; /* value of a S_STR */ sym_block *block; /* to store blocks */ gsl_complex (*fnctptr)(); /* value of a S_FNCT */ } value; struct symrec *next; /* link field */ } symrec; /* The symbol table: a chain of struct symrec. */ extern symrec *sym_table; extern char *reserved_symbols[]; symrec *putsym (const char *sym_name, symrec_type sym_type); symrec *getsym (const char *sym_name); int rmsym (const char *sym_name); void sym_notdef(symrec *sym); void sym_redef(symrec *sym); void sym_wrong_arg(symrec *sym); void sym_init_table(void); void sym_end_table(void); void sym_output_table(int only_unused, int mpiv_node); void str_tolower(char *in); void sym_mark_table_used(); void sym_print(FILE *f, const symrec *ptr); #endif
{ "alphanum_fraction": 0.6842105263, "avg_line_length": 32.2173913043, "ext": "h", "hexsha": "26ba3cf7b81311208d36a75d0f26dfcb1e03b950", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2020-05-29T23:24:51.000Z", "max_forks_repo_forks_event_min_datetime": "2016-11-22T20:30:46.000Z", "max_forks_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "shunsuke-sato/octopus", "max_forks_repo_path": "liboct_parser/symbols.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_issues_repo_issues_event_max_datetime": "2020-08-11T19:14:06.000Z", "max_issues_repo_issues_event_min_datetime": "2020-08-11T19:14:06.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "shunsuke-sato/octopus", "max_issues_repo_path": "liboct_parser/symbols.h", "max_line_length": 101, "max_stars_count": 4, "max_stars_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "shunsuke-sato/octopus", "max_stars_repo_path": "liboct_parser/symbols.h", "max_stars_repo_stars_event_max_datetime": "2019-10-17T06:31:08.000Z", "max_stars_repo_stars_event_min_datetime": "2016-11-17T09:03:11.000Z", "num_tokens": 551, "size": 2223 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_statistics_double.h> #include <math.h> #include "tz_error.h" #include "tz_constant.h" #include "tz_voxel_linked_list.h" #include "tz_stack_sampling.h" #include "tz_voxel_graphics.h" #include "tz_neurotrace.h" #include "tz_stack_math.h" #include "tz_stack_utils.h" #include "tz_objdetect.h" #include "tz_voxeltrans.h" #include "tz_stack_stat.h" #include "tz_stack_draw.h" #include "tz_geo3d_vector.h" #include "tz_stack_bwmorph.h" #include "tz_stack_bwdist.h" #include "tz_stack_threshold.h" INIT_EXCEPTION_MAIN(e) int main(int argc, char* argv[]) { char neuron_name[100]; if (argc == 1) { strcpy(neuron_name, "fly_neuron"); } else { strcpy(neuron_name, argv[1]); } char file_path[100]; sprintf(file_path, "../data/%s/traced.tif", neuron_name); Stack *stack = Read_Stack(file_path); sprintf(file_path, "../data/%s/soma.tif", neuron_name); Stack *label = Read_Stack(file_path); Stack *label2 = Copy_Stack(label); Rgb_Color color; Set_Color(&color, 0, 255, 0); Stack_Threshold(label, 2); Stack_Binarize(label); Stack_Threshold(label2, 1); Stack_Binarize(label2); Stack_Xor(label, label2, label2); sprintf(file_path, "../data/%s.tif", neuron_name); Stack *signal = Read_Stack(file_path); //label = Stack_Boundary_N(label, NULL, 8); //Stack_Label_Bwc(stack, label, color); Stack_Label_Color(stack, label, 5.4, 1.0, signal); //label2 = Stack_Boundary_N(label2, NULL, 8); //Set_Color(&color, 0, 0, 255); //Stack_Label_Bwc(stack, label2, color); Stack_Label_Color(stack, label2, 3.6, 1.0, signal); sprintf(file_path, "../data/%s/label.tif", neuron_name); Write_Stack(file_path, stack); Kill_Stack(signal); Kill_Stack(stack); Kill_Stack(label); Kill_Stack(label2); return 0; }
{ "alphanum_fraction": 0.7090713902, "avg_line_length": 24.5131578947, "ext": "c", "hexsha": "688f65313afcd337fb9ba2f324acd314c4211811", "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": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzhmark/vaa3d_tools", "max_forks_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_label.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_issues_repo_issues_event_max_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_issues_event_min_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzhmark/vaa3d_tools", "max_issues_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_label.c", "max_line_length": 59, "max_stars_count": 1, "max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzhmark/vaa3d_tools", "max_stars_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_label.c", "max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z", "num_tokens": 553, "size": 1863 }
#include <stdlib.h> #include <string.h> #include <math.h> #include <mpi.h> #include <gsl/gsl_math.h> #ifdef SUBFIND #include "allvars.h" #include "proto.h" #include "subfind.h" /*! Structure for communication during the density computation. Holds data that is sent to other processors. */ static struct linkngbdata_in { MyDouble Pos[3]; MyFloat DM_Hsml; int NodeList[NODELISTLENGTH]; } *LinkngbDataIn, *LinkngbDataGet; static struct linkngbdata_out { int Ngb; } *LinkngbDataResult, *LinkngbDataOut; void subfind_find_linkngb(void) { long long ntot; int i, j, ndone, ndone_flag, npleft, dummy, iter = 0, save_DesNumNgb; MyFloat *Left, *Right; char *Todo; int ngrp, sendTask, recvTask, place, nexport, nimport; double dmax1, dmax2, t0, t1; if(ThisTask == 0) printf("Start find_linkngb (%d particles on task=%d)\n", NumPartGroup, ThisTask); save_DesNumNgb = All.DesNumNgb; All.DesNumNgb = All.DesLinkNgb; /* for simplicity, reset this value */ /* allocate buffers to arrange communication */ Ngblist = (int *) mymalloc(NumPartGroup * sizeof(int)); Dist2list = (double *) mymalloc(NumPartGroup * sizeof(double)); All.BunchSize = (int) ((All.BufferSize * 1024 * 1024) / (sizeof(struct data_index) + sizeof(struct data_nodelist) + sizeof(struct linkngbdata_in) + sizeof(struct linkngbdata_out) + sizemax(sizeof(struct linkngbdata_in), sizeof(struct linkngbdata_out)))); DataIndexTable = (struct data_index *) mymalloc(All.BunchSize * sizeof(struct data_index)); DataNodeList = (struct data_nodelist *) mymalloc(All.BunchSize * sizeof(struct data_nodelist)); Left = mymalloc(sizeof(MyFloat) * NumPartGroup); Right = mymalloc(sizeof(MyFloat) * NumPartGroup); Todo = mymalloc(sizeof(char) * NumPartGroup); for(i = 0; i < NumPartGroup; i++) { Left[i] = Right[i] = 0; Todo[i] = 1; } /* we will repeat the whole thing for those particles where we didn't find enough neighbours */ do { t0 = second(); i = 0; /* begin with this index */ do { for(j = 0; j < NTask; j++) { Send_count[j] = 0; Exportflag[j] = -1; } /* do local particles and prepare export list */ for(nexport = 0; i < NumPartGroup; i++) { if(Todo[i]) { if(subfind_linkngb_evaluate(i, 0, &nexport, Send_count) < 0) break; } } qsort(DataIndexTable, nexport, sizeof(struct data_index), data_index_compare); MPI_Allgather(Send_count, NTask, MPI_INT, Sendcount_matrix, NTask, MPI_INT, MPI_COMM_WORLD); for(j = 0, nimport = 0, Recv_offset[0] = 0, Send_offset[0] = 0; j < NTask; j++) { Recv_count[j] = Sendcount_matrix[j * NTask + ThisTask]; nimport += Recv_count[j]; if(j > 0) { Send_offset[j] = Send_offset[j - 1] + Send_count[j - 1]; Recv_offset[j] = Recv_offset[j - 1] + Recv_count[j - 1]; } } LinkngbDataGet = (struct linkngbdata_in *) mymalloc(nimport * sizeof(struct linkngbdata_in)); LinkngbDataIn = (struct linkngbdata_in *) mymalloc(nexport * sizeof(struct linkngbdata_in)); /* prepare particle data for export */ for(j = 0; j < nexport; j++) { place = DataIndexTable[j].Index; LinkngbDataIn[j].Pos[0] = P[place].Pos[0]; LinkngbDataIn[j].Pos[1] = P[place].Pos[1]; LinkngbDataIn[j].Pos[2] = P[place].Pos[2]; LinkngbDataIn[j].DM_Hsml = P[place].DM_Hsml; memcpy(LinkngbDataIn[j].NodeList, DataNodeList[DataIndexTable[j].IndexGet].NodeList, NODELISTLENGTH * sizeof(int)); } /* exchange particle data */ for(ngrp = 1; ngrp < (1 << PTask); ngrp++) { sendTask = ThisTask; recvTask = ThisTask ^ ngrp; if(recvTask < NTask) { if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0) { /* get the particles */ MPI_Sendrecv(&LinkngbDataIn[Send_offset[recvTask]], Send_count[recvTask] * sizeof(struct linkngbdata_in), MPI_BYTE, recvTask, TAG_DENS_A, &LinkngbDataGet[Recv_offset[recvTask]], Recv_count[recvTask] * sizeof(struct linkngbdata_in), MPI_BYTE, recvTask, TAG_DENS_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } } } myfree(LinkngbDataIn); LinkngbDataResult = (struct linkngbdata_out *) mymalloc(nimport * sizeof(struct linkngbdata_out)); LinkngbDataOut = (struct linkngbdata_out *) mymalloc(nexport * sizeof(struct linkngbdata_out)); /* now do the particles that were sent to us */ for(j = 0; j < nimport; j++) subfind_linkngb_evaluate(j, 1, &dummy, &dummy); if(i >= NumPartGroup) ndone_flag = 1; else ndone_flag = 0; MPI_Allreduce(&ndone_flag, &ndone, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); /* get the result */ for(ngrp = 1; ngrp < (1 << PTask); ngrp++) { sendTask = ThisTask; recvTask = ThisTask ^ ngrp; if(recvTask < NTask) { if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0) { /* send the results */ MPI_Sendrecv(&LinkngbDataResult[Recv_offset[recvTask]], Recv_count[recvTask] * sizeof(struct linkngbdata_out), MPI_BYTE, recvTask, TAG_DENS_B, &LinkngbDataOut[Send_offset[recvTask]], Send_count[recvTask] * sizeof(struct linkngbdata_out), MPI_BYTE, recvTask, TAG_DENS_B, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } } } /* add the result to the local particles */ for(j = 0; j < nexport; j++) { place = DataIndexTable[j].Index; P[place].DM_NumNgb += LinkngbDataOut[j].Ngb; } myfree(LinkngbDataOut); myfree(LinkngbDataResult); myfree(LinkngbDataGet); } while(ndone < NTask); /* do final operations on results */ for(i = 0, npleft = 0; i < NumPartGroup; i++) { /* now check whether we had enough neighbours */ if(Todo[i]) { if(P[i].DM_NumNgb != All.DesLinkNgb && ((Right[i] - Left[i]) > 1.0e-3 * Left[i] || Left[i] == 0 || Right[i] == 0)) { /* need to redo this particle */ npleft++; if(P[i].DM_NumNgb < All.DesLinkNgb) Left[i] = DMAX(P[i].DM_Hsml, Left[i]); else { if(Right[i] != 0) { if(P[i].DM_Hsml < Right[i]) Right[i] = P[i].DM_Hsml; } else Right[i] = P[i].DM_Hsml; } if(iter >= MAXITER - 10) { printf ("i=%d task=%d ID=%d DM_Hsml=%g Left=%g Right=%g Ngbs=%g Right-Left=%g\n pos=(%g|%g|%g)\n", i, ThisTask, (int) P[i].ID, P[i].DM_Hsml, Left[i], Right[i], (double) P[i].DM_NumNgb, Right[i] - Left[i], P[i].Pos[0], P[i].Pos[1], P[i].Pos[2]); fflush(stdout); } if(Right[i] > 0 && Left[i] > 0) P[i].DM_Hsml = pow(0.5 * (pow(Left[i], 3) + pow(Right[i], 3)), 1.0 / 3); else { if(Right[i] == 0 && Left[i] == 0) endrun(8189); /* can't occur */ if(Right[i] == 0 && Left[i] > 0) P[i].DM_Hsml *= 1.26; if(Right[i] > 0 && Left[i] == 0) P[i].DM_Hsml /= 1.26; } } else Todo[i] = 0; } } sumup_large_ints(1, &npleft, &ntot); t1 = second(); if(ntot > 0) { iter++; if(iter > 0 && ThisTask == 0) { printf("find linkngb iteration %d: need to repeat for %d%09d particles. (took %g sec)\n", iter, (int) (ntot / 1000000000), (int) (ntot % 1000000000), timediff(t0, t1)); fflush(stdout); } if(iter > MAXITER) { printf("failed to converge in neighbour iteration in density()\n"); fflush(stdout); endrun(1155); } } } while(ntot > 0); myfree(Todo); myfree(Right); myfree(Left); myfree(DataNodeList); myfree(DataIndexTable); myfree(Dist2list); myfree(Ngblist); All.DesNumNgb = save_DesNumNgb; /* restore it */ } /*! This function represents the core of the SPH density computation. The * target particle may either be local, or reside in the communication * buffer. */ int subfind_linkngb_evaluate(int target, int mode, int *nexport, int *nsend_local) { int startnode, numngb, ngbs, listindex = 0; double hmax; double h, h2, hinv, hinv3; MyDouble *pos; numngb = 0; if(mode == 0) { pos = P[target].Pos; h = P[target].DM_Hsml; } else { pos = LinkngbDataGet[target].Pos; h = LinkngbDataGet[target].DM_Hsml; } h2 = h * h; hinv = 1.0 / h; hinv3 = hinv * hinv * hinv; if(mode == 0) { startnode = All.MaxPart; /* root node */ } else { startnode = LinkngbDataGet[target].NodeList[0]; startnode = Nodes[startnode].u.d.nextnode; /* open it */ } numngb = 0; while(startnode >= 0) { while(startnode >= 0) { ngbs = subfind_ngb_treefind_linkngb(pos, h, target, &startnode, mode, &hmax, nexport, nsend_local); if(ngbs < 0) return -1; if(mode == 0 && hmax > 0) P[target].DM_Hsml = hmax; numngb += ngbs; } if(mode == 1) { listindex++; if(listindex < NODELISTLENGTH) { startnode = LinkngbDataGet[target].NodeList[listindex]; if(startnode >= 0) startnode = Nodes[startnode].u.d.nextnode; /* open it */ } } } if(mode == 0) { P[target].DM_NumNgb = numngb; } else { LinkngbDataResult[target].Ngb = numngb; } return 0; } int subfind_ngb_treefind_linkngb(MyDouble searchcenter[3], double hsml, int target, int *startnode, int mode, double *hmax, int *nexport, int *nsend_local) { int numngb, i, no, p, task, nexport_save, exported = 0; struct NODE *current; double dx, dy, dz, dist, r2; #ifdef PERIODIC MyDouble xtmp; #endif nexport_save = *nexport; *hmax = 0; numngb = 0; no = *startnode; while(no >= 0) { if(no < All.MaxPart) /* single particle */ { p = no; no = Nextnode[no]; #ifdef DENSITY_SPLIT_BY_TYPE if(!((1 << P[p].Type) & (DENSITY_SPLIT_BY_TYPE))) #else if(!((1 << P[p].Type) & (FOF_PRIMARY_LINK_TYPES))) #endif continue; dist = hsml; dx = NGB_PERIODIC_LONG_X(P[p].Pos[0] - searchcenter[0]); if(dx > dist) continue; dy = NGB_PERIODIC_LONG_Y(P[p].Pos[1] - searchcenter[1]); if(dy > dist) continue; dz = NGB_PERIODIC_LONG_Z(P[p].Pos[2] - searchcenter[2]); if(dz > dist) continue; if((r2 = (dx * dx + dy * dy + dz * dz)) > dist * dist) continue; Dist2list[numngb] = r2; Ngblist[numngb++] = p; } else { if(no >= All.MaxPart + MaxNodes) /* pseudo particle */ { if(mode == 1) endrun(12312); if(target >= 0) /* if no target is given, export will not occur */ { exported = 1; if(Exportflag[task = DomainTask[no - (All.MaxPart + MaxNodes)]] != target) { Exportflag[task] = target; Exportnodecount[task] = NODELISTLENGTH; } if(Exportnodecount[task] == NODELISTLENGTH) { if(*nexport >= All.BunchSize) { *nexport = nexport_save; if(nexport_save == 0) endrun(13004); /* in this case, the buffer is too small to process even a single particle */ for(task = 0; task < NTask; task++) nsend_local[task] = 0; for(no = 0; no < nexport_save; no++) nsend_local[DataIndexTable[no].Task]++; return -1; } Exportnodecount[task] = 0; Exportindex[task] = *nexport; DataIndexTable[*nexport].Task = task; DataIndexTable[*nexport].Index = target; DataIndexTable[*nexport].IndexGet = *nexport; *nexport = *nexport + 1; nsend_local[task]++; } DataNodeList[Exportindex[task]].NodeList[Exportnodecount[task]++] = DomainNodeIndex[no - (All.MaxPart + MaxNodes)]; if(Exportnodecount[task] < NODELISTLENGTH) DataNodeList[Exportindex[task]].NodeList[Exportnodecount[task]] = -1; } no = Nextnode[no - MaxNodes]; continue; } current = &Nodes[no]; if(mode == 1) { if(current->u.d.bitflags & (1 << BITFLAG_TOPLEVEL)) /* we reached a top-level node again, which means that we are done with the branch */ { *startnode = -1; return numngb; } } no = current->u.d.sibling; /* in case the node can be discarded */ dist = hsml + 0.5 * current->len;; dx = NGB_PERIODIC_LONG_X(current->center[0] - searchcenter[0]); if(dx > dist) continue; dy = NGB_PERIODIC_LONG_Y(current->center[1] - searchcenter[1]); if(dy > dist) continue; dz = NGB_PERIODIC_LONG_Z(current->center[2] - searchcenter[2]); if(dz > dist) continue; /* now test against the minimal sphere enclosing everything */ dist += FACT1 * current->len; if(dx * dx + dy * dy + dz * dz > dist * dist) continue; no = current->u.d.nextnode; /* ok, we need to open the node */ } } if(mode == 0) /* local particle */ if(exported == 0) /* completely local */ if(numngb >= All.DesNumNgb) { R2list = mymalloc(sizeof(struct r2data) * numngb); for(i = 0; i < numngb; i++) { R2list[i].index = Ngblist[i]; R2list[i].r2 = Dist2list[i]; } qsort(R2list, numngb, sizeof(struct r2data), subfind_ngb_compare_dist); *hmax = sqrt(R2list[All.DesNumNgb - 1].r2); numngb = All.DesNumNgb; for(i = 0; i < numngb; i++) { Ngblist[i] = R2list[i].index; Dist2list[i] = R2list[i].r2; } myfree(R2list); } *startnode = -1; return numngb; } #ifdef DENSITY_SPLIT_BY_TYPE /*! This routine finds all neighbours `j' that can interact with * \f$ r_{ij} < h_i \f$ OR if \f$ r_{ij} < h_j \f$. */ int subfind_ngb_treefind_linkpairs(MyDouble searchcenter[3], double hsml, int target, int *startnode, int mode, double *hmax, int *nexport, int *nsend_local) { int numngb, i, no, p, task, nexport_save, exported = 0; struct NODE *current; double dx, dy, dz, dist, r2, dmax1, dmax2; #ifdef PERIODIC MyDouble xtmp; #endif nexport_save = *nexport; *hmax = 0; numngb = 0; no = *startnode; while(no >= 0) { if(no < All.MaxPart) /* single particle */ { p = no; no = Nextnode[no]; #ifdef DENSITY_SPLIT_BY_TYPE if(!((1 << P[p].Type) & (DENSITY_SPLIT_BY_TYPE))) #else if(!((1 << P[p].Type) & (FOF_PRIMARY_LINK_TYPES))) #endif continue; dist = DMAX(P[p].DM_Hsml, hsml); dx = NGB_PERIODIC_LONG_X(P[p].Pos[0] - searchcenter[0]); if(dx > dist) continue; dy = NGB_PERIODIC_LONG_Y(P[p].Pos[1] - searchcenter[1]); if(dy > dist) continue; dz = NGB_PERIODIC_LONG_Z(P[p].Pos[2] - searchcenter[2]); if(dz > dist) continue; if((r2 = (dx * dx + dy * dy + dz * dz)) > dist * dist) continue; Dist2list[numngb] = r2; Ngblist[numngb++] = p; } else { if(no >= All.MaxPart + MaxNodes) /* pseudo particle */ { if(mode == 1) endrun(12312); if(target >= 0) /* if no target is given, export will not occur */ { exported = 1; if(Exportflag[task = DomainTask[no - (All.MaxPart + MaxNodes)]] != target) { Exportflag[task] = target; Exportnodecount[task] = NODELISTLENGTH; } if(Exportnodecount[task] == NODELISTLENGTH) { if(*nexport >= All.BunchSize) { *nexport = nexport_save; if(nexport_save == 0) endrun(13004); /* in this case, the buffer is too small to process even a single particle */ for(task = 0; task < NTask; task++) nsend_local[task] = 0; for(no = 0; no < nexport_save; no++) nsend_local[DataIndexTable[no].Task]++; return -1; } Exportnodecount[task] = 0; Exportindex[task] = *nexport; DataIndexTable[*nexport].Task = task; DataIndexTable[*nexport].Index = target; DataIndexTable[*nexport].IndexGet = *nexport; *nexport = *nexport + 1; nsend_local[task]++; } DataNodeList[Exportindex[task]].NodeList[Exportnodecount[task]++] = DomainNodeIndex[no - (All.MaxPart + MaxNodes)]; if(Exportnodecount[task] < NODELISTLENGTH) DataNodeList[Exportindex[task]].NodeList[Exportnodecount[task]] = -1; } no = Nextnode[no - MaxNodes]; continue; } current = &Nodes[no]; if(mode == 1) { if(current->u.d.bitflags & (1 << BITFLAG_TOPLEVEL)) /* we reached a top-level node again, which means that we are done with the branch */ { *startnode = -1; return numngb; } } dist = DMAX(Extnodes[no].hmax, hsml) + 0.5 * current->len; no = current->u.d.sibling; /* in case the node can be discarded */ dx = NGB_PERIODIC_LONG_X(current->center[0] - searchcenter[0]); if(dx > dist) continue; dy = NGB_PERIODIC_LONG_Y(current->center[1] - searchcenter[1]); if(dy > dist) continue; dz = NGB_PERIODIC_LONG_Z(current->center[2] - searchcenter[2]); if(dz > dist) continue; /* now test against the minimal sphere enclosing everything */ dist += FACT1 * current->len; if(dx * dx + dy * dy + dz * dz > dist * dist) continue; no = current->u.d.nextnode; /* ok, we need to open the node */ } } if(mode == 0) /* local particle */ if(exported == 0) /* completely local */ if(numngb >= All.DesNumNgb) { R2list = mymalloc(sizeof(struct r2data) * numngb); for(i = 0; i < numngb; i++) { R2list[i].index = Ngblist[i]; R2list[i].r2 = Dist2list[i]; } qsort(R2list, numngb, sizeof(struct r2data), subfind_ngb_compare_dist); *hmax = sqrt(R2list[All.DesNumNgb - 1].r2); numngb = All.DesNumNgb; for(i = 0; i < numngb; i++) { Ngblist[i] = R2list[i].index; Dist2list[i] = R2list[i].r2; } myfree(R2list); } *startnode = -1; return numngb; } #endif int subfind_ngb_compare_dist(const void *a, const void *b) { if(((struct r2data *) a)->r2 < (((struct r2data *) b)->r2)) return -1; if(((struct r2data *) a)->r2 > (((struct r2data *) b)->r2)) return +1; return 0; } #endif
{ "alphanum_fraction": 0.5960913876, "avg_line_length": 24.8027777778, "ext": "c", "hexsha": "0f40a5c90ffafc9d2172b27a0dae843ea803510f", "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": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "egpbos/egp", "max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/subfind_findlinkngb.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "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": "egpbos/egp", "max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/subfind_findlinkngb.c", "max_line_length": 144, "max_stars_count": null, "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "egpbos/egp", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/subfind_findlinkngb.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5795, "size": 17858 }
/** * @file EigenAdaptors.h * * @brief This header contains adaptor functions for Eigen types * * @author Stefan Reinhold * @copyright Copyright (C) 2018 Stefan Reinhold -- All Rights Reserved. * You may use, distribute and modify this code under the terms of * the AFL 3.0 license; see LICENSE for full license details. */ #pragma once #include <Eigen/Core> #include <gsl/gsl> #include <array> namespace CortidQCT { namespace Internal { namespace Adaptor { namespace Detail_ { template <class T, class I> constexpr inline auto subscript(T &&x, I i) noexcept(noexcept(std::declval<T>()[i])) { return x[i]; } template <class Derived, class I> constexpr inline auto subscript(Eigen::MatrixBase<Derived> const &x, I i) noexcept(noexcept(x(std::declval<Eigen::Index>()))) { return x(gsl::narrow_cast<Eigen::Index>(i)); } template <class Derived, class I> constexpr inline auto subscript(Eigen::MatrixBase<Derived> &&x, I i) noexcept(noexcept(x(std::declval<Eigen::Index>()))) { return x(gsl::narrow_cast<Eigen::Index>(i)); } template <class T, std::size_t N> struct ConstructionHelper { template <class P, class... Args> inline constexpr T operator()(P &&param, Args &&... args) const noexcept(noexcept(ConstructionHelper<T, N - 1>{}( std::forward<P>(param), subscript(param, N - 1), std::forward<Args>(args)...))) { return ConstructionHelper<T, N - 1>{}(std::forward<P>(param), subscript(param, N - 1), std::forward<Args>(args)...); } }; template <class T> struct ConstructionHelper<T, 0> { template <class P, class... Args> inline constexpr T operator()(P &&, Args &&... args) const noexcept(noexcept(T{std::forward<Args>(args)...})) { return T{std::forward<Args>(args)...}; } }; template <class T, std::size_t N> struct ConstructionHelper<std::array<T, N>, 0> { template <class P, class... Args> inline constexpr std::array<T, N> operator()(P &&, Args &&... args) const noexcept(noexcept(std::array<T, N>{{std::forward<Args>(args)...}})) { return std::array<T, N>{{std::forward<Args>(args)...}}; } }; } // namespace Detail_ /// Converts an std::array based vector into an Eigen vector template <class T, std::size_t N> inline Eigen::Matrix<T, static_cast<Eigen::Index>(N), 1> vec(std::array<T, N> const &arr) { using Result = Eigen::Matrix<T, static_cast<Eigen::Index>(N), 1>; return Detail_::ConstructionHelper<Result, N>{}(arr); } /// Converts an Eigen vector to a std::array based one template <class Derived> inline std::array<typename Derived::Scalar, static_cast<std::size_t>(Derived::RowsAtCompileTime)> arr(Eigen::MatrixBase<Derived> const &vec) noexcept { static_assert(Derived::RowsAtCompileTime != Eigen::Dynamic && Derived::ColsAtCompileTime == 1, "Conversion only available for fix sized vectors"); using T = typename Derived::Scalar; auto constexpr N = static_cast<std::size_t>(Derived::RowsAtCompileTime); using Result = std::array<T, N>; return Detail_::ConstructionHelper<Result, N>{}(vec); } template <class T> inline Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1> const> map(std::vector<T> const &v) { return Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1> const>{ v.data(), gsl::narrow_cast<Eigen::Index>(v.size())}; } template <class T> inline Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1>> map(std::vector<T> &v) { return Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1>>{ v.data(), gsl::narrow_cast<Eigen::Index>(v.size())}; } template <std::size_t N, class T> inline Eigen::Map< Eigen::Matrix<T, static_cast<Eigen::Index>(N), Eigen::Dynamic> const> map(std::vector<std::array<T, N>> const &m) { return Eigen::Map< Eigen::Matrix<T, static_cast<Eigen::Index>(N), Eigen::Dynamic> const>{ reinterpret_cast<T const *>(m.data()), gsl::narrow_cast<Eigen::Index>(N), gsl::narrow_cast<Eigen::Index>(m.size())}; } template <std::size_t N, class T> inline Eigen::Map< Eigen::Matrix<T, static_cast<Eigen::Index>(N), Eigen::Dynamic>> map(std::vector<std::array<T, N>> &m) { return Eigen::Map< Eigen::Matrix<T, static_cast<Eigen::Index>(N), Eigen::Dynamic>>{ reinterpret_cast<T *>(m.data()), gsl::narrow_cast<Eigen::Index>(N), gsl::narrow_cast<Eigen::Index>(m.size())}; } } // namespace Adaptor } // namespace Internal } // namespace CortidQCT
{ "alphanum_fraction": 0.6412900395, "avg_line_length": 33.5147058824, "ext": "h", "hexsha": "083faa67732b6c931553bc4b5262104e8b8124b1", "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": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59", "max_forks_repo_licenses": [ "AFL-3.0" ], "max_forks_repo_name": "ithron/CortidQCT", "max_forks_repo_path": "lib/EigenAdaptors.h", "max_issues_count": 28, "max_issues_repo_head_hexsha": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59", "max_issues_repo_issues_event_max_datetime": "2021-04-22T08:11:33.000Z", "max_issues_repo_issues_event_min_datetime": "2018-10-23T10:51:36.000Z", "max_issues_repo_licenses": [ "AFL-3.0" ], "max_issues_repo_name": "ithron/CortidQCT", "max_issues_repo_path": "lib/EigenAdaptors.h", "max_line_length": 79, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59", "max_stars_repo_licenses": [ "AFL-3.0" ], "max_stars_repo_name": "ithron/CortidQCT", "max_stars_repo_path": "lib/EigenAdaptors.h", "max_stars_repo_stars_event_max_datetime": "2021-08-21T17:30:23.000Z", "max_stars_repo_stars_event_min_datetime": "2021-08-21T17:30:23.000Z", "num_tokens": 1221, "size": 4558 }
/* * cube.c -- solutions of a cubic system * * (c) 2016 Prof Dr Andreas Mueller, Hochschule Rapperswil */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_odeiv2.h> int f(double x, const double y[], double f[], void *params) { f[0] = (y[0] - 1) * y[0] * (y[0] + 1); return GSL_SUCCESS; } int singlecurve(FILE *out, const char *name, double x0, double y0) { printf("%s: %f\n", name, y0); gsl_odeiv2_system system = { f, NULL, 1, NULL }; gsl_odeiv2_driver *driver = gsl_odeiv2_driver_alloc_y_new(&system, gsl_odeiv2_step_rk8pd, 1e-6, 1e-6, 0.0); fprintf(out, "path %s;\n", name); double x = x0; double y[1] = { y0 }; fprintf(out, "%s = (%.3f,%.3f)", name, x, y[0]); for (int i = 1; i <= 400; i++) { double xnext = x + 0.01; int status = gsl_odeiv2_driver_apply(driver, &x, xnext, y); if (status != GSL_SUCCESS) { fprintf(stderr, "error: rc = %d\n", status); fprintf(out, ";\n"); return -1; } if (fabs(y[0]) > 100) { goto end; } fprintf(out, "\n --(%.3f,%.3f)", x, y[0]); } end: fprintf(out, ";\n"); gsl_odeiv2_driver_free(driver); return 1; } int centercurve(FILE *out, const char *name, double y0) { gsl_odeiv2_system system = { f, NULL, 1, NULL }; gsl_odeiv2_driver *driver = gsl_odeiv2_driver_alloc_y_new(&system, gsl_odeiv2_step_rk8pd, -1e-6, 1e-6, 0.0); double x = 0; double y[1] = { y0 }; double xnext = -2; // integrate backwards to the initial value int status = gsl_odeiv2_driver_apply(driver, &x, xnext, y); gsl_odeiv2_driver_free(driver); driver = gsl_odeiv2_driver_alloc_y_new(&system, gsl_odeiv2_step_rk8pd, 1e-6, 1e-6, 0.0); /* if (fabs(y[0]) > 100) { return -1; } */ singlecurve(out, name, -2, y[0]); return 1; } int main(int argc, char *argv[]) { FILE *out = fopen("cube.mp", "w"); char suffix = 'a'; char pathname[6]; for (int i = 0; i < 16; i++) { double y0 = -1.5 + i * 0.2; snprintf(pathname, sizeof(pathname), "path%c", suffix++); centercurve(out, pathname, y0); } return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.6218978102, "avg_line_length": 25.3703703704, "ext": "c", "hexsha": "f2387aee419b800594c4d26919b52fedee994e5d", "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": "a7c452c44097ca851c661d3bc1093204ddae7f67", "max_forks_repo_licenses": [ "CC0-1.0" ], "max_forks_repo_name": "MatthiasRubin/SeminarDGL", "max_forks_repo_path": "skript/chapters/images/cube.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "a7c452c44097ca851c661d3bc1093204ddae7f67", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC0-1.0" ], "max_issues_repo_name": "MatthiasRubin/SeminarDGL", "max_issues_repo_path": "skript/chapters/images/cube.c", "max_line_length": 71, "max_stars_count": 1, "max_stars_repo_head_hexsha": "a7c452c44097ca851c661d3bc1093204ddae7f67", "max_stars_repo_licenses": [ "CC0-1.0" ], "max_stars_repo_name": "MatthiasRubin/SeminarDGL", "max_stars_repo_path": "skript/chapters/images/cube.c", "max_stars_repo_stars_event_max_datetime": "2021-01-05T07:48:28.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-05T07:48:28.000Z", "num_tokens": 775, "size": 2055 }
// // Created by robin on 2018/9/1. // Copyright (c) 2018 Robin. All rights reserved. // #pragma once #include <type_traits> #include <vector> #include <algorithm> #include <gsl/gsl> namespace satz::bytes { /** * @brief Generate n random bytes. */ std::vector<uint8_t> make_random_bytes (int n); /** * @brief Given a byte sequence, return the indices of non-zero bits, regarding * the bytes as a little-endian bit array with index starting at 0. * @param bytes * @post The resultant vector should be in increasing order. */ template <typename T> std::vector<T> make_indices (gsl::span<const uint8_t> bytes) { std::vector<T> d; d.reserve(bytes.size() * 8); for (int i = 0; i < bytes.size(); ++i) { for (int j = 0; j < 8; ++j) { if ((bytes[i] >> j) & 0x1) d.push_back(8 * i + j); } } return d; } /** * @brief Given a byte sequence, join the bytes into a single object. * If the number of bytes is greater than the size of T, discard extra * bytes. If the number of bytes is less than the size of T, pad with * leading zeros. * @param bytes * @example * [0xef, 0xbe, 0xed, 0xfe] ==> 0xfeedbeef * [0xed, 0xfe] ==> 0x0000feed * [0xef, 0xbe, 0xed, 0xfe, 0xee] => 0xfeedbeef * @post The relative byte order of the result should be the same as the argument. */ template <typename T> T from_bytes (gsl::span<const uint8_t> bytes) { static_assert(std::is_trivially_copyable_v<T>); using U = std::make_unsigned_t<T>; static_assert(sizeof(U) == sizeof(T)); U ret = 0; const ssize_t m = bytes.size(); const ssize_t n = sizeof(U); std::for_each(bytes.rbegin() + std::max(m - n, ssize_t(0)), bytes.rend(), [&ret] (uint8_t b) { ret = (ret << 8) | b; }); return static_cast<T>(ret); } }
{ "alphanum_fraction": 0.6121343445, "avg_line_length": 24.6133333333, "ext": "h", "hexsha": "9ab5bd6d541d1961b64c55ff5ab39920d2a7f96e", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-03-26T11:41:15.000Z", "max_forks_repo_forks_event_min_datetime": "2021-03-26T11:41:15.000Z", "max_forks_repo_head_hexsha": "834d2d52e4c5967fe4b7aa6026742cc82c6bc031", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "lie-yan/rabin-fingerprint", "max_forks_repo_path": "src/bytes.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "834d2d52e4c5967fe4b7aa6026742cc82c6bc031", "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": "lie-yan/rabin-fingerprint", "max_issues_repo_path": "src/bytes.h", "max_line_length": 82, "max_stars_count": null, "max_stars_repo_head_hexsha": "834d2d52e4c5967fe4b7aa6026742cc82c6bc031", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "lie-yan/rabin-fingerprint", "max_stars_repo_path": "src/bytes.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 558, "size": 1846 }
/* * C version of Diffusive Nested Sampling (DNest4) by Brendon J. Brewer * * Yan-Rong Li, liyanrong@mail.ihep.ac.cn * Jun 30, 2016 * */ #ifndef _DNESTVARS_H #define _DNESTVARS_H #ifdef __cplusplus extern "C" { #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <stdbool.h> #include <gsl/gsl_rng.h> #define DNEST_MAJOR_VERSION 0 // Dec 2, 2018 #define DNEST_MINOR_VERSION 1 #define DNEST_PATCH_VERSION 0 #define STR_MAX_LENGTH (100) #define BUF_MAX_LENGTH (200) #define LEVEL_NUM_MAX (2000) /* output files */ extern FILE *fsample, *fsample_info; /* random number generator */ extern const gsl_rng_type * dnest_gsl_T; extern gsl_rng * dnest_gsl_r; typedef struct { double value; double tiebreaker; }LikelihoodType; typedef struct { LikelihoodType log_likelihood; double log_X; unsigned long long int visits, exceeds; unsigned long long int accepts, tries; }Level; // struct for options typedef struct { unsigned int num_particles; unsigned int new_level_interval; unsigned int save_interval; unsigned int thread_steps; unsigned int max_num_levels; double lambda, beta; unsigned int max_num_saves; double max_ptol; char sample_file[STR_MAX_LENGTH]; char sample_info_file[STR_MAX_LENGTH]; char levels_file[STR_MAX_LENGTH]; char sampler_state_file[STR_MAX_LENGTH]; char posterior_sample_file[STR_MAX_LENGTH]; char posterior_sample_info_file[STR_MAX_LENGTH]; char limits_file[STR_MAX_LENGTH]; }Options; extern Options options; extern char options_file[STR_MAX_LENGTH]; typedef struct { void (*from_prior)(void *model, const void *arg); double (*log_likelihoods_cal)(const void *model, const void *arg); double (*log_likelihoods_cal_initial)(const void *model, const void *arg); double (*log_likelihoods_cal_restart)(const void *model, const void *arg); double (*perturb)(void *model, const void *arg); void (*print_particle)(FILE *fp, const void *model, const void *arg); void (*read_particle)(FILE *fp, void *model); void (*restart_action)(int iflag); void (*accept_action)(); void (*kill_action)(int i, int i_copy); }DNestFptrSet; extern void *particles; extern int dnest_size_of_modeltype; extern int particle_offset_size, particle_offset_double; // sampler extern bool save_to_disk; extern unsigned int num_threads; extern double compression; extern unsigned int regularisation; extern void *particles; extern LikelihoodType *log_likelihoods; extern unsigned int *level_assignments; // number account of unaccepted times extern unsigned int *account_unaccepts; extern int size_levels; extern Level *levels; extern unsigned int count_saves, num_saves, num_saves_restart; extern unsigned long long int count_mcmc_steps; extern LikelihoodType *above; extern unsigned int size_above; extern int dnest_flag_restart, dnest_flag_postprc, dnest_flag_sample_info, dnest_flag_limits; extern double dnest_post_temp; extern char file_restart[STR_MAX_LENGTH], file_save_restart[STR_MAX_LENGTH]; extern double post_logz; extern int dnest_num_params; extern char dnest_sample_postfix[STR_MAX_LENGTH], dnest_sample_tag[STR_MAX_LENGTH], dnest_sample_dir[STR_MAX_LENGTH]; //the limits of parameters for each level; extern double *limits, *copies_of_limits; extern int dnest_which_particle_update; // which particle to be updated extern int dnest_which_level_update; // which level to be updated; extern int *dnest_perturb_accept; extern int dnest_root; extern void *dnest_arg; //*********************************************** /* functions */ extern double mod(double y, double x); extern void dnest_wrap(double *x, double min, double max); extern void wrap_limit(double *x, double min, double max); extern int mod_int(int y, int x); extern int dnest_cmp(const void *pa, const void *pb); extern void options_load(int max_num_saves, double ptol); extern void setup(int argc, char** argv, DNestFptrSet *fptrset, int num_params, char *sample_dir, int max_num_saves, double ptol); extern void finalise(); extern double dnest(int argc, char **argv, DNestFptrSet *fptrset, int num_params, char *sample_dir, int max_num_saves, double pdff, const void *arg); extern void dnest_run(); extern void dnest_mcmc_run(); extern void update_particle(unsigned int which); extern void update_level_assignment(unsigned int which); extern double log_push(unsigned int which_level); extern bool enough_levels(Level *l, int size_l); extern void do_bookkeeping(); extern void save_levels(); extern void save_particle(); extern void save_limits(); extern void kill_lagging_particles(); extern void renormalise_visits(); extern void recalculate_log_X(); extern double dnest_randh(); extern double dnest_rand(); extern double dnest_randn(); extern int dnest_rand_int(int size); extern void dnest_postprocess(double temperature, int max_num_saves, double ptol); extern void postprocess(double temperature); extern void initialize_output_file(); extern void close_output_file(); extern void dnest_save_restart(); extern void dnest_restart(); extern void dnest_restart_action(int iflag); extern void dnest_accept_action(); extern void dnest_kill_action(int i, int i_copy); extern void dnest_print_particle(FILE *fp, const void *model, const void *arg); extern void dnest_read_particle(FILE *fp, void *model); extern int dnest_get_size_levels(); extern int dnest_get_which_level_update(); extern int dnest_get_which_particle_update(); extern void dnest_get_posterior_sample_file(char *fname); extern int dnest_check_version(char *verion_str); extern unsigned int dnest_get_which_num_saves(); extern unsigned int dnest_get_count_saves(); extern unsigned long long int dnest_get_count_mcmc_steps(); extern void dnest_check_fptrset(DNestFptrSet *fptrset); extern DNestFptrSet * dnest_malloc_fptrset(); extern void dnest_free_fptrset(DNestFptrSet * fptrset); /*=====================================================*/ // users responsible for following functions extern void (*print_particle)(FILE *fp, const void *model, const void *arg); extern void (*read_particle)(FILE *fp, void *model); extern void (*from_prior)(void *model, const void *arg); extern double (*log_likelihoods_cal)(const void *model, const void *arg); extern double (*log_likelihoods_cal_initial)(const void *model, const void *arg); extern double (*log_likelihoods_cal_restart)(const void *model, const void *arg); extern double (*perturb)(void *model, const void *arg); extern void (*restart_action)(int iflag); extern void (*accept_action)(); extern void (*kill_action)(int i, int i_copy); /*=====================================================*/ #ifdef __cplusplus } #endif #endif
{ "alphanum_fraction": 0.7638888889, "avg_line_length": 33.3134328358, "ext": "h", "hexsha": "f675b4655e99065b291564b22edcab91c2717ed2", "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/dnestvars.h", "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/dnestvars.h", "max_line_length": 130, "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/dnestvars.h", "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": 1607, "size": 6696 }
/* * 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 */ /*! * \file reconstruct_line2d.c * \brief reconstruct 2d line and BLR model. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <float.h> #include <gsl/gsl_interp.h> #include "brains.h" void *best_model_line2d; /*!< best model */ void *best_model_std_line2d; /*!< standard deviation of the best model */ /*! * postprocessing. */ void postprocess2d() { char posterior_sample_file[BRAINS_MAX_STR_LENGTH]; int num_ps, i, j, k, nc; double *pm, *pmstd; double *lag; void *posterior_sample, *post_model; double mean_lag, mean_lag_std, sum1, sum2; int size_of_modeltype = num_params * sizeof(double); best_model_line2d = malloc(size_of_modeltype); best_model_std_line2d = malloc(size_of_modeltype); if(thistask == roottask) { // initialize smoothing workspace smooth_init(n_vel_data_ext, Vline_data_ext); char fname[200]; FILE *fp, *fcon, *fline, *ftran, *fline1d; double *Fline1d, dV; // velocity grid width, in term of wavelength of Hbeta. dV = (Vline_data[n_vel_data-1]-Vline_data[0])/(n_vel_data-1) * parset.linecenter/C_Unit; Fline1d = malloc(n_line_data * sizeof(double)); // get number of lines in posterior sample file get_posterior_sample_file(dnest_options_file, posterior_sample_file); //file for posterior sample fp = fopen(posterior_sample_file, "r"); if(fp == NULL) { fprintf(stderr, "# Error: Cannot open file %s.\n", posterior_sample_file); exit(0); } //file for continuum reconstruction sprintf(fname, "%s/%s", parset.file_dir, "data/con_rec.txt"); fcon = fopen(fname, "w"); if(fcon == NULL) { fprintf(stderr, "# Error: Cannot open file %s.\n", fname); exit(0); } //file for line reconstruction sprintf(fname, "%s/%s", parset.file_dir, "data/line2d_rec.txt"); fline = fopen(fname, "w"); if(fline == NULL) { fprintf(stderr, "# Error: Cannot open file %s.\n", fname); exit(0); } //file for line reconstruction sprintf(fname, "%s/%s", parset.file_dir, "data/line_rec.txt"); fline1d = fopen(fname, "w"); if(fline1d == NULL) { fprintf(stderr, "# Error: Cannot open file %s.\n", fname); exit(0); } //file for transfer function sprintf(fname, "%s/%s", parset.file_dir, "data/tran2d_rec.txt"); ftran = fopen(fname, "w"); if(ftran == NULL) { fprintf(stderr, "# Error: Cannot open file %s.\n", fname); exit(0); } // read number of lines if(fscanf(fp, "# %d", &num_ps) < 1) { fprintf(stderr, "# Error: Cannot read file %s.\n", posterior_sample_file); exit(0); } printf("# Number of points in posterior sample: %d\n", num_ps); lag = malloc(num_ps * sizeof(double)); post_model = malloc(size_of_modeltype); posterior_sample = malloc(num_ps * size_of_modeltype); force_update = 1; which_parameter_update = -1; // force to update the transfer function which_particle_update = 0; mean_lag = 0.0; nc = 0; Fcon_rm = Fcon_rm_particles[which_particle_update]; TransTau = TransTau_particles[which_particle_update]; Trans2D_at_veldata = Trans2D_at_veldata_particles[which_particle_update]; Fline2d_at_data = Fline_at_data_particles[which_particle_update]; for(i=0; i<num_ps; i++) { // read lines for(j=0; j<num_params; j++) { if(fscanf(fp, "%lf", (double *)post_model + j) < 1) { fprintf(stderr, "# Error: Cannot read file %s.\n", posterior_sample_file); exit(0); } } fscanf(fp, "\n"); //store model memcpy(posterior_sample+i*size_of_modeltype, post_model, size_of_modeltype); //calculate_con_from_model(post_model + num_params_blr *sizeof(double)); calculate_con_from_model_semiseparable(post_model + num_params_blr *sizeof(double)); calculate_con_rm(post_model); gsl_interp_init(gsl_linear, Tcon, Fcon_rm, parset.n_con_recon); transfun_2d_cal(post_model, Vline_data_ext, Trans2D_at_veldata, n_vel_data_ext, 0); calculate_line2d_from_blrmodel(post_model, Tline_data, Vline_data_ext, Trans2D_at_veldata, Fline2d_at_data, n_line_data, n_vel_data_ext); // calculate integrated line fluxes for(j = 0; j < n_line_data; j++) { Fline1d[j] = 0.0; for(k=0; k<n_vel_data; k++) { Fline1d[j] += Fline2d_at_data[j * n_vel_data_ext + (k+n_vel_data_incr)] * dV /line_scale; } } // calculate mean time lag sum1 = 0.0; sum2 = 0.0; for(j=0; j<parset.n_tau; j++) { for(k=0; k<n_vel_data_ext; k++) { sum1 += Trans2D_at_veldata[j * n_vel_data_ext + k] * TransTau[j]; sum2 += Trans2D_at_veldata[j * n_vel_data_ext + k]; } } // take care of zero transfer function if(sum2 > 0.0) { lag[i] = sum1/sum2; mean_lag += lag[i]; nc++; } else { lag[i] = -DBL_MAX; } //if( i % (num_ps/10+1) == 0) { // output continuum for(j=0; j<parset.n_con_recon; j++) { fprintf(fcon, "%e %e\n", Tcon[j]*(1.0+parset.redshift), Fcon[j]/con_scale); } fprintf(fcon, "\n"); // output 2d line for(j=0; j<n_line_data; j++) { for(k=0; k<n_vel_data; k++) { fprintf(fline, "%e ", Fline2d_at_data[j * n_vel_data_ext + (k+n_vel_data_incr)]/line_scale); } fprintf(fline, "\n"); } fprintf(fline, "\n"); // output transfer function for(j=0; j<parset.n_tau; j++) { fprintf(ftran, "%e ", TransTau[j]); for(k=0; k<n_vel_data; k++) { fprintf(ftran, "%e ", Trans2D_at_veldata[j * n_vel_data_ext + (k+n_vel_data_incr)]); } fprintf(ftran, "\n"); } fprintf(ftran, "\n"); // output 1d line for(j = 0; j<n_line_data; j++) { fprintf(fline1d, "%e %e\n", Tline_data[j]*(1.0+parset.redshift), Fline1d[j]); } fprintf(fline1d, "\n"); } } smooth_end(); fclose(fp); fclose(fcon); fclose(fline); fclose(ftran); fclose(fline1d); /* calculate mean lags */ mean_lag /= (nc); mean_lag_std = 0.0; for(i=0; i<num_ps; i++) { if(lag[i] > -DBL_MAX) mean_lag_std += (lag[i] - mean_lag) * (lag[i] - mean_lag); } if(nc > 1) mean_lag_std = sqrt(mean_lag_std/(nc -1.0)); else mean_lag_std = 0.0; printf("Mean time lag: %f+-%f\n", mean_lag, mean_lag_std); pm = (double *)best_model_line2d; pmstd = (double *)best_model_std_line2d; for(j=0; j<num_params; j++) { pm[j] = pmstd[j] = 0.0; } for(i=0; i<num_ps; i++) { for(j =0; j<num_params; j++) pm[j] += *((double *)posterior_sample + i*num_params + j ); } for(j=0; j<num_params; j++) pm[j] /= num_ps; for(i=0; i<num_ps; i++) { for(j=0; j<num_params; j++) pmstd[j] += pow( *((double *)posterior_sample + i*num_params + j ) - pm[j], 2.0 ); } for(j=0; j<num_params; j++) { if(num_ps > 1) pmstd[j] = sqrt(pmstd[j]/(num_ps-1.0)); else pmstd[j] = 0.0; } for(j = 0; j<num_params_blr + num_params_var; j++) printf("Best params %d %f +- %f\n", j, *((double *)best_model_line2d + j), *((double *)best_model_std_line2d+j) ); free(lag); free(post_model); free(posterior_sample); free(Fline1d); } return; } /*! * this function run dnest sampleing, reconstruct light curves using the best estimates for parameters. */ void reconstruct_line2d() { int i, argc=0; char **argv; //configure restart of dnest argv = malloc(9*sizeof(char *)); for(i=0; i<9; i++) { argv[i] = malloc(BRAINS_MAX_STR_LENGTH*sizeof(char)); } //setup argc and argv strcpy(argv[argc++], "dnest"); strcpy(argv[argc++], "-s"); strcpy(argv[argc], parset.file_dir); strcat(argv[argc++], "/data/restart2d_dnest.txt"); if(parset.flag_restart == 1) { strcpy(argv[argc++], "-r"); strcpy(argv[argc], parset.file_dir); strcat(argv[argc], "/"); strcat(argv[argc++], "data/restart2d_dnest.txt"); } if(parset.flag_postprc == 1) { strcpy(argv[argc++], "-p"); } if(parset.flag_temp == 1) { sprintf(argv[argc++], "-t%f", parset.temperature); } if(parset.flag_sample_info == 1) { strcpy(argv[argc++], "-c"); } //level-dependent sampling { strcpy(argv[argc++], "-l"); } reconstruct_line2d_init(); smooth_init(n_vel_data_ext, Vline_data_ext); dnest_line2d(argc, argv); smooth_end(); if(parset.flag_exam_prior != 1 && parset.flag_para_name != 1) { postprocess2d(); // calculate light curves using the best model if(thistask == roottask) { force_update = 1; which_parameter_update = -1; which_particle_update = 0; Fcon_rm = Fcon_rm_particles[which_particle_update]; TransTau = TransTau_particles[which_particle_update]; Trans2D_at_veldata = Trans2D_at_veldata_particles[which_particle_update]; Fline2d_at_data = Fline_at_data_particles[which_particle_update]; //calculate_con_from_model(best_model_line2d + num_params_blr *sizeof(double)); calculate_con_from_model_semiseparable(best_model_line2d + num_params_blr *sizeof(double)); calculate_con_rm(best_model_line2d); gsl_interp_init(gsl_linear, Tcon, Fcon_rm, parset.n_con_recon); FILE *fp; char fname[200]; int i, j; sprintf(fname, "%s/%s", parset.file_dir, parset.pcon_out_file); fp = fopen(fname, "w"); if(fp == NULL) { fprintf(stderr, "# Error: Cannot open file %s\n", fname); exit(-1); } for(i=0; i<parset.n_con_recon; i++) { fprintf(fp, "%e %e %e\n", Tcon[i]*(1.0+parset.redshift), Fcon[i] / con_scale, Fcerrs[i] / con_scale); } fclose(fp); smooth_init(n_vel_data_ext, Vline_data_ext); // recovered line2d at data points transfun_2d_cal(best_model_line2d, Vline_data_ext, Trans2D_at_veldata, n_vel_data_ext, parset.flag_save_clouds); calculate_line2d_from_blrmodel(best_model_line2d, Tline_data, Vline_data_ext, Trans2D_at_veldata, Fline2d_at_data, n_line_data, n_vel_data_ext); sprintf(fname, "%s/%s", parset.file_dir, parset.pline2d_data_out_file); fp = fopen(fname, "w"); if(fp == NULL) { fprintf(stderr, "# Error: Cannot open file %s\n", fname); exit(-1); } fprintf(fp, "# %d %d\n", n_line_data, n_vel_data); for(i=0; i<n_line_data; i++) { fprintf(fp, "# %f\n", Tline_data[i]*(1.0+parset.redshift)); for(j=0; j<n_vel_data; j++) { fprintf(fp, "%e %e\n", Wline_data[j], Fline2d_at_data[i*n_vel_data_ext + (j+n_vel_data_incr)] / line_scale); } fprintf(fp, "\n"); } fclose(fp); sprintf(fname, "%s/%s", parset.file_dir, parset.tran2d_data_out_file); fp = fopen(fname, "w"); if(fp == NULL) { fprintf(stderr, "# Error: Cannot open file %s\n", fname); exit(-1); } fprintf(fp, "# %d %d\n", parset.n_tau, n_vel_data); for(i=0; i<parset.n_tau; i++) { fprintf(fp, "# %f\n", TransTau[i]); for(j=0; j<n_vel_data; j++) { fprintf(fp, "%e %e\n", Vline_data[j], Trans2D_at_veldata[i*n_vel_data_ext + (j+n_vel_data_incr)]); } fprintf(fp, "\n"); } fclose(fp); smooth_end(); // recovered line2d at specified points smooth_init(parset.n_vel_recon, TransV); which_parameter_update = -1; which_particle_update = 0; transfun_2d_cal(best_model_line2d, TransV, Trans2D, parset.n_vel_recon, 0); /* there is no data for spectral broadening at given specified epoch, using the mean value * and set InstRes_err=0.0. */ double *pm = (double *)best_model_line2d; if(parset.flag_InstRes > 0) { parset.flag_InstRes = 0; /* force to be uniform prior */ double instres_mean = 0.0; for(i=0; i<n_line_data; i++) { instres_mean += instres_epoch[i]; } parset.InstRes = instres_mean/n_line_data; parset.InstRes_err = 0.0; instres_mean = 0.0; for(i=0; i<n_line_data; i++) { instres_mean += pm[num_params_blr_model+num_params_nlr+i]; } pm[num_params_blr_model + num_params_nlr ] = instres_mean/n_line_data; } /* similarly, there is no data for line center information at given specified epoch, * using the mean value */ if(parset.flag_linecenter < 0) { parset.flag_linecenter = 1; /* force to be uniform prior, note num_params_linecenter is still unchanged */ double linecenter_mean = 0.0; for(i=0; i<n_line_data; i++) { linecenter_mean += pm[idx_linecenter + i]; } pm[idx_linecenter] = linecenter_mean/n_line_data; } calculate_line2d_from_blrmodel(best_model_line2d, Tline, TransV, Trans2D, Fline2d, parset.n_line_recon, parset.n_vel_recon); sprintf(fname, "%s/%s", parset.file_dir, parset.pline2d_out_file); fp = fopen(fname, "w"); if(fp == NULL) { fprintf(stderr, "# Error: Cannot open file %s\n", fname); exit(-1); } fprintf(fp, "# %d %d\n", parset.n_line_recon, parset.n_vel_recon); for(i=0; i<parset.n_line_recon; i++) { fprintf(fp, "# %f\n", Tline[i]*(1.0+parset.redshift)); for(j=0; j<parset.n_vel_recon; j++) { fprintf(fp, "%e %e\n", (1.0 + TransV[j]/C_Unit) * parset.linecenter * (1.0+parset.redshift), Fline2d[i*parset.n_vel_recon + j] / line_scale); } fprintf(fp, "\n"); } fclose(fp); // output 2d transfer function sprintf(fname, "%s/%s", parset.file_dir, parset.tran2d_out_file); fp = fopen(fname, "w"); if(fp == NULL) { fprintf(stderr, "# Error: Cannot open file %s\n", fname); exit(-1); } fprintf(fp, "# %d %d\n", parset.n_tau, parset.n_vel_recon); for(i=0; i<parset.n_tau; i++) { fprintf(fp, "# %f\n", TransTau[i]); for(j=0; j<parset.n_vel_recon; j++) { fprintf(fp, "%e %e\n", TransV[j]*VelUnit, Trans2D[i*parset.n_vel_recon + j]); } fprintf(fp, "\n"); } fclose(fp); smooth_end(); } } reconstruct_line2d_end(); //clear up argv for(i=0; i<9; i++) { free(argv[i]); } free(argv); return; } /*! * this function initializes 2d reconstruction. */ void reconstruct_line2d_init() { int i, j; double dT, Tspan; Tspan = Tcon_data[n_con_data -1] - Tcon_data[0]; /* set time grid for continuum */ /*if(parset.time_back > 0.0) Tcon_min = Tcon_data[0] - parset.time_back; else Tcon_min = Tcon_data[0] - fmax(0.05*Tspan, Tspan/2.0 + (Tcon_data[0] - Tline_data[0]));*/ Tcon_min = Tcon_data[0] - time_back_set - 10.0; Tcon_max = Tcon_data[n_con_data-1] + fmax(0.05*Tspan, 20.0); Tcon_max = fmax(Tcon_max, Tline_data[n_line_data -1] + 10.0); /* The time span should cover that of the emission line data */ if(thistask == roottask) printf("Tcon_min_max: %f %f\n", Tcon_min - Tcon_data[0], Tcon_max - Tcon_data[n_con_data-1]); dT = (Tcon_max - Tcon_min)/(parset.n_con_recon -1); for(i=0; i<parset.n_con_recon; i++) { Tcon[i] = Tcon_min + i*dT; } /* set Larr_rec */ for(i=0;i<parset.n_con_recon;i++) { Larr_rec[i*nq + 0]=1.0; for(j=1; j<nq; j++) Larr_rec[i*nq + j] = pow(Tcon[i], j); } //TransTau = malloc(parset.n_tau * sizeof(double)); //Trans2D_at_veldata = malloc(parset.n_tau * n_vel_data * sizeof(double)); TransV = malloc(parset.n_vel_recon * sizeof(double)); Trans2D = malloc(parset.n_tau * parset.n_vel_recon * sizeof(double)); //Fline2d_at_data = malloc(n_line_data * n_vel_data * sizeof(double)); Tline = malloc(parset.n_line_recon * sizeof(double)); Fline2d = malloc(parset.n_line_recon * parset.n_vel_recon * sizeof(double)); Tline_min = Tline_data[0] - fmin(0.1*(Tline_data[n_line_data - 1] - Tline_data[0]), 10.0); if(parset.time_back <= 0.0) Tline_min = fmax(Tline_min, Tcon_min + time_back_set); Tline_max = Tline_data[n_line_data -1] + fmin(0.1*(Tline_data[n_line_data - 1] - Tline_data[0]), 10.0); Tline_max = fmin(Tline_max, Tcon_max - 1.0); /* The time span should be smaller than that of the continuum */ if(thistask == roottask) printf("Tline_min_max: %f %f\n", Tline_min - Tline_data[0], Tline_max - Tline_data[n_line_data -1]); dT = (Tline_max - Tline_min)/(parset.n_line_recon - 1); for(i=0; i<parset.n_line_recon; i++) { Tline[i] = Tline_min + i*dT; } double vel_max_set = Vline_data_ext[n_vel_data_ext -1], vel_min_set = Vline_data_ext[0]; double dVel = (vel_max_set- vel_min_set)/(parset.n_vel_recon -1.0); for(i=0; i<parset.n_vel_recon; i++) { TransV[i] = vel_min_set + dVel*i; } sprintf(dnest_options_file, "%s/%s", parset.file_dir, "src/OPTIONS2D"); if(thistask == roottask) { get_num_particles(dnest_options_file); } MPI_Bcast(&parset.num_particles, 1, MPI_INT, roottask, MPI_COMM_WORLD); Fcon = malloc(parset.n_con_recon * sizeof(double *)); Fcon_rm_particles = malloc(parset.num_particles * sizeof(double *)); Fcon_rm_particles_perturb = malloc(parset.num_particles * sizeof(double *)); for(i=0; i<parset.num_particles; i++) { Fcon_rm_particles[i] = malloc(parset.n_con_recon * sizeof(double)); Fcon_rm_particles_perturb[i] = malloc(parset.n_con_recon * sizeof(double)); } TransTau_particles = malloc(parset.num_particles * sizeof(double *)); TransTau_particles_perturb = malloc(parset.num_particles * sizeof(double *)); for(i=0; i<parset.num_particles; i++) { TransTau_particles[i] = malloc(parset.n_tau * sizeof(double)); TransTau_particles_perturb[i] = malloc(parset.n_tau * sizeof(double)); } Trans2D_at_veldata_particles = malloc(parset.num_particles * sizeof(double *)); Trans2D_at_veldata_particles_perturb = malloc(parset.num_particles * sizeof(double *)); for(i=0; i<parset.num_particles; i++) { Trans2D_at_veldata_particles[i] = malloc(parset.n_tau * n_vel_data_ext * sizeof(double)); Trans2D_at_veldata_particles_perturb[i] = malloc(parset.n_tau * n_vel_data_ext * sizeof(double)); } Fline_at_data_particles = malloc(parset.num_particles * sizeof(double *)); Fline_at_data_particles_perturb = malloc(parset.num_particles * sizeof(double *)); for(i=0; i<parset.num_particles; i++) { Fline_at_data_particles[i] = malloc(n_line_data * n_vel_data_ext * sizeof(double)); Fline_at_data_particles_perturb[i] = malloc(n_line_data * n_vel_data_ext * sizeof(double)); } clouds_tau = malloc(parset.n_cloud_per_task * sizeof(double)); clouds_weight = malloc(parset.n_cloud_per_task * sizeof(double)); clouds_vel = malloc(parset.n_cloud_per_task * parset.n_vel_per_cloud * sizeof(double)); if(parset.flag_save_clouds && thistask == roottask) { if(parset.n_cloud_per_task <= 10000) icr_cloud_save = 1; else icr_cloud_save = parset.n_cloud_per_task/10000; char fname[200]; sprintf(fname, "%s/%s", parset.file_dir, parset.cloud_out_file); fcloud_out = fopen(fname, "w"); if(fcloud_out == NULL) { fprintf(stderr, "# Error: Cannot open file %s\n", fname); exit(-1); } } return; } /*! * this function finalizes 2d reconstruction. */ void reconstruct_line2d_end() { free(Tline); //free(Fline2d_at_data); free(Fline2d); //free(TransTau); free(TransV); free(Trans2D); //free(Trans2D_at_veldata); int i; for(i=0; i<parset.num_particles; i++) { free(Fcon_rm_particles[i]); free(Fcon_rm_particles_perturb[i]); } free(Fcon); free(Fcon_rm_particles); free(Fcon_rm_particles_perturb); free(Fline_at_data); free(par_fix); free(par_fix_val); free(best_model_line2d); free(best_model_std_line2d); for(i=0; i<parset.num_particles; i++) { free(Trans2D_at_veldata_particles[i]); free(Trans2D_at_veldata_particles_perturb[i]); free(TransTau_particles[i]); free(TransTau_particles_perturb[i]); free(Fline_at_data_particles[i]); free(Fline_at_data_particles_perturb[i]); } free(Trans2D_at_veldata_particles); free(Trans2D_at_veldata_particles_perturb); free(TransTau_particles); free(TransTau_particles_perturb); free(Fline_at_data_particles); free(Fline_at_data_particles_perturb); for(i=0; i<num_params; i++) { free(par_range_model[i]); free(par_prior_gaussian[i]); } free(par_range_model); free(par_prior_gaussian); free(par_prior_model); free(clouds_tau); free(clouds_weight); free(clouds_vel); if(parset.flag_save_clouds && thistask==roottask) { fclose(fcloud_out); } if(thistask == roottask) { printf("Ends reconstruct_line2d.\n"); } return; } /*! * this function calculate probability at initial step. */ double prob_initial_line2d(const void *model) { double prob_line = 0.0, var2, dy, var2_se; int i, j; double *pm = (double *)model; which_particle_update = dnest_get_which_particle_update(); Fcon_rm = Fcon_rm_particles[which_particle_update]; //calculate_con_from_model(model + num_params_blr*sizeof(double)); calculate_con_from_model_semiseparable(model + num_params_blr*sizeof(double)); calculate_con_rm(model); gsl_interp_init(gsl_linear, Tcon, Fcon_rm, parset.n_con_recon); TransTau = TransTau_particles[which_particle_update]; Trans2D_at_veldata = Trans2D_at_veldata_particles[which_particle_update]; Fline2d_at_data = Fline_at_data_particles[which_particle_update]; which_parameter_update = -1; transfun_2d_cal(model, Vline_data_ext, Trans2D_at_veldata, n_vel_data_ext, 0); calculate_line2d_from_blrmodel(model, Tline_data, Vline_data_ext, Trans2D_at_veldata, Fline2d_at_data, n_line_data, n_vel_data_ext); var2_se = (exp(pm[num_params_blr-1])-1.0) * (exp(pm[num_params_blr-1])-1.0) * line_error_mean_sq; for(i=0; i<n_line_data; i++) { for(j=0; j<n_vel_data; j++) { //note mask with error < 0.0 if(Flerrs2d_data[i] > 0.0) { dy = Fline2d_data[i*n_vel_data + j] - Fline2d_at_data[i * n_vel_data_ext + (j+n_vel_data_incr)]; var2 = Flerrs2d_data[i*n_vel_data+j]*Flerrs2d_data[i*n_vel_data+j] + var2_se; prob_line += (-0.5 * (dy*dy)/var2) - 0.5*log(var2 * 2.0*PI); } } } return prob_line; } /*! * this function calculate probability at restart step. */ double prob_restart_line2d(const void *model) { double prob_line = 0.0, var2, dy, var2_se; int i, j; double *pm = (double *)model; which_particle_update = dnest_get_which_particle_update(); Fcon_rm = Fcon_rm_particles[which_particle_update]; //calculate_con_from_model(model + num_params_blr*sizeof(double)); calculate_con_from_model_semiseparable(model + num_params_blr*sizeof(double)); calculate_con_rm(model); gsl_interp_init(gsl_linear, Tcon, Fcon_rm, parset.n_con_recon); TransTau = TransTau_particles[which_particle_update]; Trans2D_at_veldata = Trans2D_at_veldata_particles[which_particle_update]; Fline2d_at_data = Fline_at_data_particles[which_particle_update]; which_parameter_update = num_params + 1; // so as not to update clouds. transfun_2d_cal(model, Vline_data_ext, Trans2D_at_veldata, n_vel_data_ext, 0); calculate_line2d_from_blrmodel(model, Tline_data, Vline_data_ext, Trans2D_at_veldata, Fline2d_at_data, n_line_data, n_vel_data_ext); var2_se = (exp(pm[num_params_blr-1])-1.0) * (exp(pm[num_params_blr-1])-1.0) * line_error_mean_sq; for(i=0; i<n_line_data; i++) { for(j=0; j<n_vel_data; j++) { //note mask with error < 0.0 if(Flerrs2d_data[i] > 0.0) { dy = Fline2d_data[i*n_vel_data + j] - Fline2d_at_data[i * n_vel_data_ext + (j+n_vel_data_incr)]; var2 = Flerrs2d_data[i*n_vel_data+j]*Flerrs2d_data[i*n_vel_data+j] + var2_se; prob_line += (-0.5 * (dy*dy)/var2) - 0.5*log(var2 * 2.0*PI); } } } return prob_line; } /*! * this function calculate probability. * * At each MCMC step, only one parameter is updated, which only changes some values; thus, * optimization that reuses the unchanged values can improve computation efficiency. */ double prob_line2d(const void *model) { double prob_line = 0.0, var2, dy, var2_se; int i, j; double *pm = (double *)model; which_particle_update = dnest_get_which_particle_update(); // only update continuum reconstruction when the corresponding parameters are updated if(which_parameter_update >= num_params_blr) { Fcon_rm = Fcon_rm_particles_perturb[which_particle_update]; //calculate_con_from_model(model + num_params_blr*sizeof(double)); calculate_con_from_model_semiseparable(model + num_params_blr*sizeof(double)); calculate_con_rm(model); gsl_interp_init(gsl_linear, Tcon, Fcon_rm, parset.n_con_recon); } else /* continuum has no change, use the previous values */ { Fcon_rm = Fcon_rm_particles[which_particle_update]; gsl_interp_init(gsl_linear, Tcon, Fcon_rm, parset.n_con_recon); } // only update transfer function when BLR model is changed. // or when forced to updated if( (which_parameter_update < num_params_blr-1) || force_update == 1) { TransTau = TransTau_particles_perturb[which_particle_update]; Trans2D_at_veldata = Trans2D_at_veldata_particles_perturb[which_particle_update]; transfun_2d_cal(model, Vline_data_ext, Trans2D_at_veldata, n_vel_data_ext, 0); } else { TransTau = TransTau_particles[which_particle_update]; Trans2D_at_veldata = Trans2D_at_veldata_particles[which_particle_update]; } /* no need to calculate line when only systematic error parameter of line are updated. * otherwise, always need to calculate line. */ if( which_parameter_update != num_params_blr-1 || force_update == 1 ) { Fline2d_at_data = Fline_at_data_particles_perturb[which_particle_update]; calculate_line2d_from_blrmodel(model, Tline_data, Vline_data_ext, Trans2D_at_veldata, Fline2d_at_data, n_line_data, n_vel_data_ext); var2_se = (exp(pm[num_params_blr-1])-1.0) * (exp(pm[num_params_blr-1])-1.0) * line_error_mean_sq; for(i=0; i<n_line_data; i++) { for(j=0; j<n_vel_data; j++) { //note mask with error < 0.0 if(Flerrs2d_data[i] > 0.0) { dy = Fline2d_data[i*n_vel_data + j] - Fline2d_at_data[i * n_vel_data_ext + (j+n_vel_data_incr)]; var2 = Flerrs2d_data[i*n_vel_data+j]*Flerrs2d_data[i*n_vel_data+j] + var2_se; prob_line += (-0.5 * (dy*dy)/var2) - 0.5*log(var2 * 2.0*PI); } } } } else { /* re-point */ Fline2d_at_data = Fline_at_data_particles[which_particle_update]; var2_se = (exp(pm[num_params_blr-1])-1.0) * (exp(pm[num_params_blr-1])-1.0) * line_error_mean_sq; for(i=0; i<n_line_data; i++) { for(j=0; j<n_vel_data; j++) { //note mask with error < 0.0 if(Flerrs2d_data[i] > 0.0) { dy = Fline2d_data[i*n_vel_data + j] - Fline2d_at_data[i * n_vel_data_ext + (j+n_vel_data_incr)]; var2 = Flerrs2d_data[i*n_vel_data+j]*Flerrs2d_data[i*n_vel_data+j] + var2_se; prob_line += (-0.5 * (dy*dy)/var2) - 0.5*log(var2 * 2.0*PI); } } } } return prob_line; }
{ "alphanum_fraction": 0.6321460216, "avg_line_length": 30.9375, "ext": "c", "hexsha": "1c48b32e9bdab931a688e64b634876eb17ab5be7", "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": "b81cec02a1902df1e544542a970b66d9916a7496", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "yzxamos/BRAINS", "max_forks_repo_path": "src/reconstruct_line2d.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496", "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": "yzxamos/BRAINS", "max_issues_repo_path": "src/reconstruct_line2d.c", "max_line_length": 136, "max_stars_count": null, "max_stars_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "yzxamos/BRAINS", "max_stars_repo_path": "src/reconstruct_line2d.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 8450, "size": 28215 }
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 1.3.36 * * This file is not intended to be easily readable and contains a number of * coding conventions designed to improve portability and efficiency. Do not make * changes to this file unless you know what you are doing--modify the SWIG * interface file instead. * ----------------------------------------------------------------------------- */ #define SWIGPYTHON #define SWIG_PYTHON_DIRECTOR_NO_VTABLE /* ----------------------------------------------------------------------------- * This section contains generic SWIG labels for method/variable * declarations/attributes, and other compiler dependent labels. * ----------------------------------------------------------------------------- */ /* template workaround for compilers that cannot correctly implement the C++ standard */ #ifndef SWIGTEMPLATEDISAMBIGUATOR # if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560) # define SWIGTEMPLATEDISAMBIGUATOR template # elif defined(__HP_aCC) /* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */ /* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */ # define SWIGTEMPLATEDISAMBIGUATOR template # else # define SWIGTEMPLATEDISAMBIGUATOR # endif #endif /* inline attribute */ #ifndef SWIGINLINE # if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) # define SWIGINLINE inline # else # define SWIGINLINE # endif #endif /* attribute recognised by some compilers to avoid 'unused' warnings */ #ifndef SWIGUNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif # elif defined(__ICC) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif #endif #ifndef SWIG_MSC_UNSUPPRESS_4505 # if defined(_MSC_VER) # pragma warning(disable : 4505) /* unreferenced local function has been removed */ # endif #endif #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) # else # define SWIGUNUSEDPARM(p) p SWIGUNUSED # endif #endif /* internal SWIG method */ #ifndef SWIGINTERN # define SWIGINTERN static SWIGUNUSED #endif /* internal inline SWIG method */ #ifndef SWIGINTERNINLINE # define SWIGINTERNINLINE SWIGINTERN SWIGINLINE #endif /* exporting methods */ #if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) # ifndef GCC_HASCLASSVISIBILITY # define GCC_HASCLASSVISIBILITY # endif #endif #ifndef SWIGEXPORT # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # if defined(STATIC_LINKED) # define SWIGEXPORT # else # define SWIGEXPORT __declspec(dllexport) # endif # else # if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) # define SWIGEXPORT __attribute__ ((visibility("default"))) # else # define SWIGEXPORT # endif # endif #endif /* calling conventions for Windows */ #ifndef SWIGSTDCALL # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # define SWIGSTDCALL __stdcall # else # define SWIGSTDCALL # endif #endif /* Deal with Microsoft's attempt at deprecating C standard runtime functions */ #if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) # define _CRT_SECURE_NO_DEPRECATE #endif /* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */ #if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE) # define _SCL_SECURE_NO_DEPRECATE #endif /* Python.h has to appear first */ #include <Python.h> /* ----------------------------------------------------------------------------- * swigrun.swg * * This file contains generic CAPI SWIG runtime support for pointer * type checking. * ----------------------------------------------------------------------------- */ /* This should only be incremented when either the layout of swig_type_info changes, or for whatever reason, the runtime changes incompatibly */ #define SWIG_RUNTIME_VERSION "4" /* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */ #ifdef SWIG_TYPE_TABLE # define SWIG_QUOTE_STRING(x) #x # define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x) # define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE) #else # define SWIG_TYPE_TABLE_NAME #endif /* You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for creating a static or dynamic library from the swig runtime code. In 99.9% of the cases, swig just needs to declare them as 'static'. But only do this if is strictly necessary, ie, if you have problems with your compiler or so. */ #ifndef SWIGRUNTIME # define SWIGRUNTIME SWIGINTERN #endif #ifndef SWIGRUNTIMEINLINE # define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE #endif /* Generic buffer size */ #ifndef SWIG_BUFFER_SIZE # define SWIG_BUFFER_SIZE 1024 #endif /* Flags for pointer conversions */ #define SWIG_POINTER_DISOWN 0x1 #define SWIG_CAST_NEW_MEMORY 0x2 /* Flags for new pointer objects */ #define SWIG_POINTER_OWN 0x1 /* Flags/methods for returning states. The swig conversion methods, as ConvertPtr, return and integer that tells if the conversion was successful or not. And if not, an error code can be returned (see swigerrors.swg for the codes). Use the following macros/flags to set or process the returning states. In old swig versions, you usually write code as: if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) { // success code } else { //fail code } Now you can be more explicit as: int res = SWIG_ConvertPtr(obj,vptr,ty.flags); if (SWIG_IsOK(res)) { // success code } else { // fail code } that seems to be the same, but now you can also do Type *ptr; int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags); if (SWIG_IsOK(res)) { // success code if (SWIG_IsNewObj(res) { ... delete *ptr; } else { ... } } else { // fail code } I.e., now SWIG_ConvertPtr can return new objects and you can identify the case and take care of the deallocation. Of course that requires also to SWIG_ConvertPtr to return new result values, as int SWIG_ConvertPtr(obj, ptr,...) { if (<obj is ok>) { if (<need new object>) { *ptr = <ptr to new allocated object>; return SWIG_NEWOBJ; } else { *ptr = <ptr to old object>; return SWIG_OLDOBJ; } } else { return SWIG_BADOBJ; } } Of course, returning the plain '0(success)/-1(fail)' still works, but you can be more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the swig errors code. Finally, if the SWIG_CASTRANK_MODE is enabled, the result code allows to return the 'cast rank', for example, if you have this int food(double) int fooi(int); and you call food(1) // cast rank '1' (1 -> 1.0) fooi(1) // cast rank '0' just use the SWIG_AddCast()/SWIG_CheckState() */ #define SWIG_OK (0) #define SWIG_ERROR (-1) #define SWIG_IsOK(r) (r >= 0) #define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) /* The CastRankLimit says how many bits are used for the cast rank */ #define SWIG_CASTRANKLIMIT (1 << 8) /* The NewMask denotes the object was created (using new/malloc) */ #define SWIG_NEWOBJMASK (SWIG_CASTRANKLIMIT << 1) /* The TmpMask is for in/out typemaps that use temporal objects */ #define SWIG_TMPOBJMASK (SWIG_NEWOBJMASK << 1) /* Simple returning values */ #define SWIG_BADOBJ (SWIG_ERROR) #define SWIG_OLDOBJ (SWIG_OK) #define SWIG_NEWOBJ (SWIG_OK | SWIG_NEWOBJMASK) #define SWIG_TMPOBJ (SWIG_OK | SWIG_TMPOBJMASK) /* Check, add and del mask methods */ #define SWIG_AddNewMask(r) (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r) #define SWIG_DelNewMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r) #define SWIG_IsNewObj(r) (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK)) #define SWIG_AddTmpMask(r) (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r) #define SWIG_DelTmpMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r) #define SWIG_IsTmpObj(r) (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK)) /* Cast-Rank Mode */ #if defined(SWIG_CASTRANK_MODE) # ifndef SWIG_TypeRank # define SWIG_TypeRank unsigned long # endif # ifndef SWIG_MAXCASTRANK /* Default cast allowed */ # define SWIG_MAXCASTRANK (2) # endif # define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) # define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) SWIGINTERNINLINE int SWIG_AddCast(int r) { return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; } SWIGINTERNINLINE int SWIG_CheckState(int r) { return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; } #else /* no cast-rank mode */ # define SWIG_AddCast # define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0) #endif #include <string.h> #ifdef __cplusplus extern "C" { #endif typedef void *(*swig_converter_func)(void *, int *); typedef struct swig_type_info *(*swig_dycast_func)(void **); /* Structure to store information on one type */ typedef struct swig_type_info { const char *name; /* mangled name of this type */ const char *str; /* human readable name of this type */ swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ struct swig_cast_info *cast; /* linked list of types that can cast into this type */ void *clientdata; /* language specific type data */ int owndata; /* flag if the structure owns the clientdata */ } swig_type_info; /* Structure to store a type and conversion function used for casting */ typedef struct swig_cast_info { swig_type_info *type; /* pointer to type that is equivalent to this type */ swig_converter_func converter; /* function to cast the void pointers */ struct swig_cast_info *next; /* pointer to next cast in linked list */ struct swig_cast_info *prev; /* pointer to the previous cast */ } swig_cast_info; /* Structure used to store module information * Each module generates one structure like this, and the runtime collects * all of these structures and stores them in a circularly linked list.*/ typedef struct swig_module_info { swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ size_t size; /* Number of types in this module */ struct swig_module_info *next; /* Pointer to next element in circularly linked list */ swig_type_info **type_initial; /* Array of initially generated type structures */ swig_cast_info **cast_initial; /* Array of initially generated casting structures */ void *clientdata; /* Language specific module data */ } swig_module_info; /* Compare two type names skipping the space characters, therefore "char*" == "char *" and "Class<int>" == "Class<int >", etc. Return 0 when the two name types are equivalent, as in strncmp, but skipping ' '. */ SWIGRUNTIME int SWIG_TypeNameComp(const char *f1, const char *l1, const char *f2, const char *l2) { for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { while ((*f1 == ' ') && (f1 != l1)) ++f1; while ((*f2 == ' ') && (f2 != l2)) ++f2; if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; } return (int)((l1 - f1) - (l2 - f2)); } /* Check type equivalence in a name list like <name1>|<name2>|... Return 0 if not equal, 1 if equal */ SWIGRUNTIME int SWIG_TypeEquiv(const char *nb, const char *tb) { int equiv = 0; const char* te = tb + strlen(tb); const char* ne = nb; while (!equiv && *ne) { for (nb = ne; *ne; ++ne) { if (*ne == '|') break; } equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; if (*ne) ++ne; } return equiv; } /* Check type equivalence in a name list like <name1>|<name2>|... Return 0 if equal, -1 if nb < tb, 1 if nb > tb */ SWIGRUNTIME int SWIG_TypeCompare(const char *nb, const char *tb) { int equiv = 0; const char* te = tb + strlen(tb); const char* ne = nb; while (!equiv && *ne) { for (nb = ne; *ne; ++ne) { if (*ne == '|') break; } equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; if (*ne) ++ne; } return equiv; } /* think of this as a c++ template<> or a scheme macro */ #define SWIG_TypeCheck_Template(comparison, ty) \ if (ty) { \ swig_cast_info *iter = ty->cast; \ while (iter) { \ if (comparison) { \ if (iter == ty->cast) return iter; \ /* Move iter to the top of the linked list */ \ iter->prev->next = iter->next; \ if (iter->next) \ iter->next->prev = iter->prev; \ iter->next = ty->cast; \ iter->prev = 0; \ if (ty->cast) ty->cast->prev = iter; \ ty->cast = iter; \ return iter; \ } \ iter = iter->next; \ } \ } \ return 0 /* Check the typename */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheck(const char *c, swig_type_info *ty) { SWIG_TypeCheck_Template(strcmp(iter->type->name, c) == 0, ty); } /* Same as previous function, except strcmp is replaced with a pointer comparison */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *into) { SWIG_TypeCheck_Template(iter->type == from, into); } /* Cast a pointer up an inheritance hierarchy */ SWIGRUNTIMEINLINE void * SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); } /* Dynamic pointer casting. Down an inheritance hierarchy */ SWIGRUNTIME swig_type_info * SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { swig_type_info *lastty = ty; if (!ty || !ty->dcast) return ty; while (ty && (ty->dcast)) { ty = (*ty->dcast)(ptr); if (ty) lastty = ty; } return lastty; } /* Return the name associated with this type */ SWIGRUNTIMEINLINE const char * SWIG_TypeName(const swig_type_info *ty) { return ty->name; } /* Return the pretty name associated with this type, that is an unmangled type name in a form presentable to the user. */ SWIGRUNTIME const char * SWIG_TypePrettyName(const swig_type_info *type) { /* The "str" field contains the equivalent pretty names of the type, separated by vertical-bar characters. We choose to print the last name, as it is often (?) the most specific. */ if (!type) return NULL; if (type->str != NULL) { const char *last_name = type->str; const char *s; for (s = type->str; *s; s++) if (*s == '|') last_name = s+1; return last_name; } else return type->name; } /* Set the clientdata field for a type */ SWIGRUNTIME void SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { swig_cast_info *cast = ti->cast; /* if (ti->clientdata == clientdata) return; */ ti->clientdata = clientdata; while (cast) { if (!cast->converter) { swig_type_info *tc = cast->type; if (!tc->clientdata) { SWIG_TypeClientData(tc, clientdata); } } cast = cast->next; } } SWIGRUNTIME void SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { SWIG_TypeClientData(ti, clientdata); ti->owndata = 1; } /* Search for a swig_type_info structure only by mangled name Search is a O(log #types) We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * SWIG_MangledTypeQueryModule(swig_module_info *start, swig_module_info *end, const char *name) { swig_module_info *iter = start; do { if (iter->size) { register size_t l = 0; register size_t r = iter->size - 1; do { /* since l+r >= 0, we can (>> 1) instead (/ 2) */ register size_t i = (l + r) >> 1; const char *iname = iter->types[i]->name; if (iname) { register int compare = strcmp(name, iname); if (compare == 0) { return iter->types[i]; } else if (compare < 0) { if (i) { r = i - 1; } else { break; } } else if (compare > 0) { l = i + 1; } } else { break; /* should never happen */ } } while (l <= r); } iter = iter->next; } while (iter != end); return 0; } /* Search for a swig_type_info structure for either a mangled name or a human readable name. It first searches the mangled names of the types, which is a O(log #types) If a type is not found it then searches the human readable names, which is O(#types). We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * SWIG_TypeQueryModule(swig_module_info *start, swig_module_info *end, const char *name) { /* STEP 1: Search the name field using binary search */ swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); if (ret) { return ret; } else { /* STEP 2: If the type hasn't been found, do a complete search of the str field (the human readable name) */ swig_module_info *iter = start; do { register size_t i = 0; for (; i < iter->size; ++i) { if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) return iter->types[i]; } iter = iter->next; } while (iter != end); } /* neither found a match */ return 0; } /* Pack binary data into a string */ SWIGRUNTIME char * SWIG_PackData(char *c, void *ptr, size_t sz) { static const char hex[17] = "0123456789abcdef"; register const unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { register unsigned char uu = *u; *(c++) = hex[(uu & 0xf0) >> 4]; *(c++) = hex[uu & 0xf]; } return c; } /* Unpack binary data from a string */ SWIGRUNTIME const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { register unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { register char d = *(c++); register unsigned char uu; if ((d >= '0') && (d <= '9')) uu = ((d - '0') << 4); else if ((d >= 'a') && (d <= 'f')) uu = ((d - ('a'-10)) << 4); else return (char *) 0; d = *(c++); if ((d >= '0') && (d <= '9')) uu |= (d - '0'); else if ((d >= 'a') && (d <= 'f')) uu |= (d - ('a'-10)); else return (char *) 0; *u = uu; } return c; } /* Pack 'void *' into a string buffer. */ SWIGRUNTIME char * SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { char *r = buff; if ((2*sizeof(void *) + 2) > bsz) return 0; *(r++) = '_'; r = SWIG_PackData(r,&ptr,sizeof(void *)); if (strlen(name) + 1 > (bsz - (r - buff))) return 0; strcpy(r,name); return buff; } SWIGRUNTIME const char * SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { if (*c != '_') { if (strcmp(c,"NULL") == 0) { *ptr = (void *) 0; return name; } else { return 0; } } return SWIG_UnpackData(++c,ptr,sizeof(void *)); } SWIGRUNTIME char * SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { char *r = buff; size_t lname = (name ? strlen(name) : 0); if ((2*sz + 2 + lname) > bsz) return 0; *(r++) = '_'; r = SWIG_PackData(r,ptr,sz); if (lname) { strncpy(r,name,lname+1); } else { *r = 0; } return buff; } SWIGRUNTIME const char * SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { if (*c != '_') { if (strcmp(c,"NULL") == 0) { memset(ptr,0,sz); return name; } else { return 0; } } return SWIG_UnpackData(++c,ptr,sz); } #ifdef __cplusplus } #endif /* Errors in SWIG */ #define SWIG_UnknownError -1 #define SWIG_IOError -2 #define SWIG_RuntimeError -3 #define SWIG_IndexError -4 #define SWIG_TypeError -5 #define SWIG_DivisionByZero -6 #define SWIG_OverflowError -7 #define SWIG_SyntaxError -8 #define SWIG_ValueError -9 #define SWIG_SystemError -10 #define SWIG_AttributeError -11 #define SWIG_MemoryError -12 #define SWIG_NullReferenceError -13 /* Add PyOS_snprintf for old Pythons */ #if PY_VERSION_HEX < 0x02020000 # if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WATCOM) # define PyOS_snprintf _snprintf # else # define PyOS_snprintf snprintf # endif #endif /* A crude PyString_FromFormat implementation for old Pythons */ #if PY_VERSION_HEX < 0x02020000 #ifndef SWIG_PYBUFFER_SIZE # define SWIG_PYBUFFER_SIZE 1024 #endif static PyObject * PyString_FromFormat(const char *fmt, ...) { va_list ap; char buf[SWIG_PYBUFFER_SIZE * 2]; int res; va_start(ap, fmt); res = vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); return (res < 0 || res >= (int)sizeof(buf)) ? 0 : PyString_FromString(buf); } #endif /* Add PyObject_Del for old Pythons */ #if PY_VERSION_HEX < 0x01060000 # define PyObject_Del(op) PyMem_DEL((op)) #endif #ifndef PyObject_DEL # define PyObject_DEL PyObject_Del #endif /* A crude PyExc_StopIteration exception for old Pythons */ #if PY_VERSION_HEX < 0x02020000 # ifndef PyExc_StopIteration # define PyExc_StopIteration PyExc_RuntimeError # endif # ifndef PyObject_GenericGetAttr # define PyObject_GenericGetAttr 0 # endif #endif /* Py_NotImplemented is defined in 2.1 and up. */ #if PY_VERSION_HEX < 0x02010000 # ifndef Py_NotImplemented # define Py_NotImplemented PyExc_RuntimeError # endif #endif /* A crude PyString_AsStringAndSize implementation for old Pythons */ #if PY_VERSION_HEX < 0x02010000 # ifndef PyString_AsStringAndSize # define PyString_AsStringAndSize(obj, s, len) {*s = PyString_AsString(obj); *len = *s ? strlen(*s) : 0;} # endif #endif /* PySequence_Size for old Pythons */ #if PY_VERSION_HEX < 0x02000000 # ifndef PySequence_Size # define PySequence_Size PySequence_Length # endif #endif /* PyBool_FromLong for old Pythons */ #if PY_VERSION_HEX < 0x02030000 static PyObject *PyBool_FromLong(long ok) { PyObject *result = ok ? Py_True : Py_False; Py_INCREF(result); return result; } #endif /* Py_ssize_t for old Pythons */ /* This code is as recommended by: */ /* http://www.python.org/dev/peps/pep-0353/#conversion-guidelines */ #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) typedef int Py_ssize_t; # define PY_SSIZE_T_MAX INT_MAX # define PY_SSIZE_T_MIN INT_MIN #endif /* ----------------------------------------------------------------------------- * error manipulation * ----------------------------------------------------------------------------- */ SWIGRUNTIME PyObject* SWIG_Python_ErrorType(int code) { PyObject* type = 0; switch(code) { case SWIG_MemoryError: type = PyExc_MemoryError; break; case SWIG_IOError: type = PyExc_IOError; break; case SWIG_RuntimeError: type = PyExc_RuntimeError; break; case SWIG_IndexError: type = PyExc_IndexError; break; case SWIG_TypeError: type = PyExc_TypeError; break; case SWIG_DivisionByZero: type = PyExc_ZeroDivisionError; break; case SWIG_OverflowError: type = PyExc_OverflowError; break; case SWIG_SyntaxError: type = PyExc_SyntaxError; break; case SWIG_ValueError: type = PyExc_ValueError; break; case SWIG_SystemError: type = PyExc_SystemError; break; case SWIG_AttributeError: type = PyExc_AttributeError; break; default: type = PyExc_RuntimeError; } return type; } SWIGRUNTIME void SWIG_Python_AddErrorMsg(const char* mesg) { PyObject *type = 0; PyObject *value = 0; PyObject *traceback = 0; if (PyErr_Occurred()) PyErr_Fetch(&type, &value, &traceback); if (value) { PyObject *old_str = PyObject_Str(value); PyErr_Clear(); Py_XINCREF(type); PyErr_Format(type, "%s %s", PyString_AsString(old_str), mesg); Py_DECREF(old_str); Py_DECREF(value); } else { PyErr_SetString(PyExc_RuntimeError, mesg); } } #if defined(SWIG_PYTHON_NO_THREADS) # if defined(SWIG_PYTHON_THREADS) # undef SWIG_PYTHON_THREADS # endif #endif #if defined(SWIG_PYTHON_THREADS) /* Threading support is enabled */ # if !defined(SWIG_PYTHON_USE_GIL) && !defined(SWIG_PYTHON_NO_USE_GIL) # if (PY_VERSION_HEX >= 0x02030000) /* For 2.3 or later, use the PyGILState calls */ # define SWIG_PYTHON_USE_GIL # endif # endif # if defined(SWIG_PYTHON_USE_GIL) /* Use PyGILState threads calls */ # ifndef SWIG_PYTHON_INITIALIZE_THREADS # define SWIG_PYTHON_INITIALIZE_THREADS PyEval_InitThreads() # endif # ifdef __cplusplus /* C++ code */ class SWIG_Python_Thread_Block { bool status; PyGILState_STATE state; public: void end() { if (status) { PyGILState_Release(state); status = false;} } SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {} ~SWIG_Python_Thread_Block() { end(); } }; class SWIG_Python_Thread_Allow { bool status; PyThreadState *save; public: void end() { if (status) { PyEval_RestoreThread(save); status = false; }} SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {} ~SWIG_Python_Thread_Allow() { end(); } }; # define SWIG_PYTHON_THREAD_BEGIN_BLOCK SWIG_Python_Thread_Block _swig_thread_block # define SWIG_PYTHON_THREAD_END_BLOCK _swig_thread_block.end() # define SWIG_PYTHON_THREAD_BEGIN_ALLOW SWIG_Python_Thread_Allow _swig_thread_allow # define SWIG_PYTHON_THREAD_END_ALLOW _swig_thread_allow.end() # else /* C code */ # define SWIG_PYTHON_THREAD_BEGIN_BLOCK PyGILState_STATE _swig_thread_block = PyGILState_Ensure() # define SWIG_PYTHON_THREAD_END_BLOCK PyGILState_Release(_swig_thread_block) # define SWIG_PYTHON_THREAD_BEGIN_ALLOW PyThreadState *_swig_thread_allow = PyEval_SaveThread() # define SWIG_PYTHON_THREAD_END_ALLOW PyEval_RestoreThread(_swig_thread_allow) # endif # else /* Old thread way, not implemented, user must provide it */ # if !defined(SWIG_PYTHON_INITIALIZE_THREADS) # define SWIG_PYTHON_INITIALIZE_THREADS # endif # if !defined(SWIG_PYTHON_THREAD_BEGIN_BLOCK) # define SWIG_PYTHON_THREAD_BEGIN_BLOCK # endif # if !defined(SWIG_PYTHON_THREAD_END_BLOCK) # define SWIG_PYTHON_THREAD_END_BLOCK # endif # if !defined(SWIG_PYTHON_THREAD_BEGIN_ALLOW) # define SWIG_PYTHON_THREAD_BEGIN_ALLOW # endif # if !defined(SWIG_PYTHON_THREAD_END_ALLOW) # define SWIG_PYTHON_THREAD_END_ALLOW # endif # endif #else /* No thread support */ # define SWIG_PYTHON_INITIALIZE_THREADS # define SWIG_PYTHON_THREAD_BEGIN_BLOCK # define SWIG_PYTHON_THREAD_END_BLOCK # define SWIG_PYTHON_THREAD_BEGIN_ALLOW # define SWIG_PYTHON_THREAD_END_ALLOW #endif /* ----------------------------------------------------------------------------- * Python API portion that goes into the runtime * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #if 0 } /* cc-mode */ #endif #endif /* ----------------------------------------------------------------------------- * Constant declarations * ----------------------------------------------------------------------------- */ /* Constant Types */ #define SWIG_PY_POINTER 4 #define SWIG_PY_BINARY 5 /* Constant information structure */ typedef struct swig_const_info { int type; char *name; long lvalue; double dvalue; void *pvalue; swig_type_info **ptype; } swig_const_info; #ifdef __cplusplus #if 0 { /* cc-mode */ #endif } #endif /* ----------------------------------------------------------------------------- * See the LICENSE file for information on copyright, usage and redistribution * of SWIG, and the README file for authors - http://www.swig.org/release.html. * * pyrun.swg * * This file contains the runtime support for Python modules * and includes code for managing global variables and pointer * type checking. * * ----------------------------------------------------------------------------- */ /* Common SWIG API */ /* for raw pointers */ #define SWIG_Python_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, 0) #define SWIG_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtr(obj, pptr, type, flags) #define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, own) #define SWIG_NewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(ptr, type, flags) #define SWIG_CheckImplicit(ty) SWIG_Python_CheckImplicit(ty) #define SWIG_AcquirePtr(ptr, src) SWIG_Python_AcquirePtr(ptr, src) #define swig_owntype int /* for raw packed data */ #define SWIG_ConvertPacked(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) #define SWIG_NewPackedObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) /* for class or struct pointers */ #define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_ConvertPtr(obj, pptr, type, flags) #define SWIG_NewInstanceObj(ptr, type, flags) SWIG_NewPointerObj(ptr, type, flags) /* for C or C++ function pointers */ #define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_Python_ConvertFunctionPtr(obj, pptr, type) #define SWIG_NewFunctionPtrObj(ptr, type) SWIG_Python_NewPointerObj(ptr, type, 0) /* for C++ member pointers, ie, member methods */ #define SWIG_ConvertMember(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) #define SWIG_NewMemberObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) /* Runtime API */ #define SWIG_GetModule(clientdata) SWIG_Python_GetModule() #define SWIG_SetModule(clientdata, pointer) SWIG_Python_SetModule(pointer) #define SWIG_NewClientData(obj) PySwigClientData_New(obj) #define SWIG_SetErrorObj SWIG_Python_SetErrorObj #define SWIG_SetErrorMsg SWIG_Python_SetErrorMsg #define SWIG_ErrorType(code) SWIG_Python_ErrorType(code) #define SWIG_Error(code, msg) SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) #define SWIG_fail goto fail /* Runtime API implementation */ /* Error manipulation */ SWIGINTERN void SWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) { SWIG_PYTHON_THREAD_BEGIN_BLOCK; PyErr_SetObject(errtype, obj); Py_DECREF(obj); SWIG_PYTHON_THREAD_END_BLOCK; } SWIGINTERN void SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) { SWIG_PYTHON_THREAD_BEGIN_BLOCK; PyErr_SetString(errtype, (char *) msg); SWIG_PYTHON_THREAD_END_BLOCK; } #define SWIG_Python_Raise(obj, type, desc) SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj) /* Set a constant value */ SWIGINTERN void SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) { PyDict_SetItemString(d, (char*) name, obj); Py_DECREF(obj); } /* Append a value to the result obj */ SWIGINTERN PyObject* SWIG_Python_AppendOutput(PyObject* result, PyObject* obj) { #if !defined(SWIG_PYTHON_OUTPUT_TUPLE) if (!result) { result = obj; } else if (result == Py_None) { Py_DECREF(result); result = obj; } else { if (!PyList_Check(result)) { PyObject *o2 = result; result = PyList_New(1); PyList_SetItem(result, 0, o2); } PyList_Append(result,obj); Py_DECREF(obj); } return result; #else PyObject* o2; PyObject* o3; if (!result) { result = obj; } else if (result == Py_None) { Py_DECREF(result); result = obj; } else { if (!PyTuple_Check(result)) { o2 = result; result = PyTuple_New(1); PyTuple_SET_ITEM(result, 0, o2); } o3 = PyTuple_New(1); PyTuple_SET_ITEM(o3, 0, obj); o2 = result; result = PySequence_Concat(o2, o3); Py_DECREF(o2); Py_DECREF(o3); } return result; #endif } /* Unpack the argument tuple */ SWIGINTERN int SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs) { if (!args) { if (!min && !max) { return 1; } else { PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", name, (min == max ? "" : "at least "), (int)min); return 0; } } if (!PyTuple_Check(args)) { PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple"); return 0; } else { register Py_ssize_t l = PyTuple_GET_SIZE(args); if (l < min) { PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", name, (min == max ? "" : "at least "), (int)min, (int)l); return 0; } else if (l > max) { PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", name, (min == max ? "" : "at most "), (int)max, (int)l); return 0; } else { register int i; for (i = 0; i < l; ++i) { objs[i] = PyTuple_GET_ITEM(args, i); } for (; l < max; ++l) { objs[l] = 0; } return i + 1; } } } /* A functor is a function object with one single object argument */ #if PY_VERSION_HEX >= 0x02020000 #define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunctionObjArgs(functor, obj, NULL); #else #define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunction(functor, "O", obj); #endif /* Helper for static pointer initialization for both C and C++ code, for example static PyObject *SWIG_STATIC_POINTER(MyVar) = NewSomething(...); */ #ifdef __cplusplus #define SWIG_STATIC_POINTER(var) var #else #define SWIG_STATIC_POINTER(var) var = 0; if (!var) var #endif /* ----------------------------------------------------------------------------- * Pointer declarations * ----------------------------------------------------------------------------- */ /* Flags for new pointer objects */ #define SWIG_POINTER_NOSHADOW (SWIG_POINTER_OWN << 1) #define SWIG_POINTER_NEW (SWIG_POINTER_NOSHADOW | SWIG_POINTER_OWN) #define SWIG_POINTER_IMPLICIT_CONV (SWIG_POINTER_DISOWN << 1) #ifdef __cplusplus extern "C" { #if 0 } /* cc-mode */ #endif #endif /* How to access Py_None */ #if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # ifndef SWIG_PYTHON_NO_BUILD_NONE # ifndef SWIG_PYTHON_BUILD_NONE # define SWIG_PYTHON_BUILD_NONE # endif # endif #endif #ifdef SWIG_PYTHON_BUILD_NONE # ifdef Py_None # undef Py_None # define Py_None SWIG_Py_None() # endif SWIGRUNTIMEINLINE PyObject * _SWIG_Py_None(void) { PyObject *none = Py_BuildValue((char*)""); Py_DECREF(none); return none; } SWIGRUNTIME PyObject * SWIG_Py_None(void) { static PyObject *SWIG_STATIC_POINTER(none) = _SWIG_Py_None(); return none; } #endif /* The python void return value */ SWIGRUNTIMEINLINE PyObject * SWIG_Py_Void(void) { PyObject *none = Py_None; Py_INCREF(none); return none; } /* PySwigClientData */ typedef struct { PyObject *klass; PyObject *newraw; PyObject *newargs; PyObject *destroy; int delargs; int implicitconv; } PySwigClientData; SWIGRUNTIMEINLINE int SWIG_Python_CheckImplicit(swig_type_info *ty) { PySwigClientData *data = (PySwigClientData *)ty->clientdata; return data ? data->implicitconv : 0; } SWIGRUNTIMEINLINE PyObject * SWIG_Python_ExceptionType(swig_type_info *desc) { PySwigClientData *data = desc ? (PySwigClientData *) desc->clientdata : 0; PyObject *klass = data ? data->klass : 0; return (klass ? klass : PyExc_RuntimeError); } SWIGRUNTIME PySwigClientData * PySwigClientData_New(PyObject* obj) { if (!obj) { return 0; } else { PySwigClientData *data = (PySwigClientData *)malloc(sizeof(PySwigClientData)); /* the klass element */ data->klass = obj; Py_INCREF(data->klass); /* the newraw method and newargs arguments used to create a new raw instance */ if (PyClass_Check(obj)) { data->newraw = 0; data->newargs = obj; Py_INCREF(obj); } else { #if (PY_VERSION_HEX < 0x02020000) data->newraw = 0; #else data->newraw = PyObject_GetAttrString(data->klass, (char *)"__new__"); #endif if (data->newraw) { Py_INCREF(data->newraw); data->newargs = PyTuple_New(1); PyTuple_SetItem(data->newargs, 0, obj); } else { data->newargs = obj; } Py_INCREF(data->newargs); } /* the destroy method, aka as the C++ delete method */ data->destroy = PyObject_GetAttrString(data->klass, (char *)"__swig_destroy__"); if (PyErr_Occurred()) { PyErr_Clear(); data->destroy = 0; } if (data->destroy) { int flags; Py_INCREF(data->destroy); flags = PyCFunction_GET_FLAGS(data->destroy); #ifdef METH_O data->delargs = !(flags & (METH_O)); #else data->delargs = 0; #endif } else { data->delargs = 0; } data->implicitconv = 0; return data; } } SWIGRUNTIME void PySwigClientData_Del(PySwigClientData* data) { Py_XDECREF(data->newraw); Py_XDECREF(data->newargs); Py_XDECREF(data->destroy); } /* =============== PySwigObject =====================*/ typedef struct { PyObject_HEAD void *ptr; swig_type_info *ty; int own; PyObject *next; } PySwigObject; SWIGRUNTIME PyObject * PySwigObject_long(PySwigObject *v) { return PyLong_FromVoidPtr(v->ptr); } SWIGRUNTIME PyObject * PySwigObject_format(const char* fmt, PySwigObject *v) { PyObject *res = NULL; PyObject *args = PyTuple_New(1); if (args) { if (PyTuple_SetItem(args, 0, PySwigObject_long(v)) == 0) { PyObject *ofmt = PyString_FromString(fmt); if (ofmt) { res = PyString_Format(ofmt,args); Py_DECREF(ofmt); } Py_DECREF(args); } } return res; } SWIGRUNTIME PyObject * PySwigObject_oct(PySwigObject *v) { return PySwigObject_format("%o",v); } SWIGRUNTIME PyObject * PySwigObject_hex(PySwigObject *v) { return PySwigObject_format("%x",v); } SWIGRUNTIME PyObject * #ifdef METH_NOARGS PySwigObject_repr(PySwigObject *v) #else PySwigObject_repr(PySwigObject *v, PyObject *args) #endif { const char *name = SWIG_TypePrettyName(v->ty); PyObject *hex = PySwigObject_hex(v); PyObject *repr = PyString_FromFormat("<Swig Object of type '%s' at 0x%s>", name, PyString_AsString(hex)); Py_DECREF(hex); if (v->next) { #ifdef METH_NOARGS PyObject *nrep = PySwigObject_repr((PySwigObject *)v->next); #else PyObject *nrep = PySwigObject_repr((PySwigObject *)v->next, args); #endif PyString_ConcatAndDel(&repr,nrep); } return repr; } SWIGRUNTIME int PySwigObject_print(PySwigObject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { #ifdef METH_NOARGS PyObject *repr = PySwigObject_repr(v); #else PyObject *repr = PySwigObject_repr(v, NULL); #endif if (repr) { fputs(PyString_AsString(repr), fp); Py_DECREF(repr); return 0; } else { return 1; } } SWIGRUNTIME PyObject * PySwigObject_str(PySwigObject *v) { char result[SWIG_BUFFER_SIZE]; return SWIG_PackVoidPtr(result, v->ptr, v->ty->name, sizeof(result)) ? PyString_FromString(result) : 0; } SWIGRUNTIME int PySwigObject_compare(PySwigObject *v, PySwigObject *w) { void *i = v->ptr; void *j = w->ptr; return (i < j) ? -1 : ((i > j) ? 1 : 0); } SWIGRUNTIME PyTypeObject* _PySwigObject_type(void); SWIGRUNTIME PyTypeObject* PySwigObject_type(void) { static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigObject_type(); return type; } SWIGRUNTIMEINLINE int PySwigObject_Check(PyObject *op) { return ((op)->ob_type == PySwigObject_type()) || (strcmp((op)->ob_type->tp_name,"PySwigObject") == 0); } SWIGRUNTIME PyObject * PySwigObject_New(void *ptr, swig_type_info *ty, int own); SWIGRUNTIME void PySwigObject_dealloc(PyObject *v) { PySwigObject *sobj = (PySwigObject *) v; PyObject *next = sobj->next; if (sobj->own == SWIG_POINTER_OWN) { swig_type_info *ty = sobj->ty; PySwigClientData *data = ty ? (PySwigClientData *) ty->clientdata : 0; PyObject *destroy = data ? data->destroy : 0; if (destroy) { /* destroy is always a VARARGS method */ PyObject *res; if (data->delargs) { /* we need to create a temporal object to carry the destroy operation */ PyObject *tmp = PySwigObject_New(sobj->ptr, ty, 0); res = SWIG_Python_CallFunctor(destroy, tmp); Py_DECREF(tmp); } else { PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); PyObject *mself = PyCFunction_GET_SELF(destroy); res = ((*meth)(mself, v)); } Py_XDECREF(res); } #if !defined(SWIG_PYTHON_SILENT_MEMLEAK) else { const char *name = SWIG_TypePrettyName(ty); printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown")); } #endif } Py_XDECREF(next); PyObject_DEL(v); } SWIGRUNTIME PyObject* PySwigObject_append(PyObject* v, PyObject* next) { PySwigObject *sobj = (PySwigObject *) v; #ifndef METH_O PyObject *tmp = 0; if (!PyArg_ParseTuple(next,(char *)"O:append", &tmp)) return NULL; next = tmp; #endif if (!PySwigObject_Check(next)) { return NULL; } sobj->next = next; Py_INCREF(next); return SWIG_Py_Void(); } SWIGRUNTIME PyObject* #ifdef METH_NOARGS PySwigObject_next(PyObject* v) #else PySwigObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) #endif { PySwigObject *sobj = (PySwigObject *) v; if (sobj->next) { Py_INCREF(sobj->next); return sobj->next; } else { return SWIG_Py_Void(); } } SWIGINTERN PyObject* #ifdef METH_NOARGS PySwigObject_disown(PyObject *v) #else PySwigObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) #endif { PySwigObject *sobj = (PySwigObject *)v; sobj->own = 0; return SWIG_Py_Void(); } SWIGINTERN PyObject* #ifdef METH_NOARGS PySwigObject_acquire(PyObject *v) #else PySwigObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) #endif { PySwigObject *sobj = (PySwigObject *)v; sobj->own = SWIG_POINTER_OWN; return SWIG_Py_Void(); } SWIGINTERN PyObject* PySwigObject_own(PyObject *v, PyObject *args) { PyObject *val = 0; #if (PY_VERSION_HEX < 0x02020000) if (!PyArg_ParseTuple(args,(char *)"|O:own",&val)) #else if (!PyArg_UnpackTuple(args, (char *)"own", 0, 1, &val)) #endif { return NULL; } else { PySwigObject *sobj = (PySwigObject *)v; PyObject *obj = PyBool_FromLong(sobj->own); if (val) { #ifdef METH_NOARGS if (PyObject_IsTrue(val)) { PySwigObject_acquire(v); } else { PySwigObject_disown(v); } #else if (PyObject_IsTrue(val)) { PySwigObject_acquire(v,args); } else { PySwigObject_disown(v,args); } #endif } return obj; } } #ifdef METH_O static PyMethodDef swigobject_methods[] = { {(char *)"disown", (PyCFunction)PySwigObject_disown, METH_NOARGS, (char *)"releases ownership of the pointer"}, {(char *)"acquire", (PyCFunction)PySwigObject_acquire, METH_NOARGS, (char *)"aquires ownership of the pointer"}, {(char *)"own", (PyCFunction)PySwigObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, {(char *)"append", (PyCFunction)PySwigObject_append, METH_O, (char *)"appends another 'this' object"}, {(char *)"next", (PyCFunction)PySwigObject_next, METH_NOARGS, (char *)"returns the next 'this' object"}, {(char *)"__repr__",(PyCFunction)PySwigObject_repr, METH_NOARGS, (char *)"returns object representation"}, {0, 0, 0, 0} }; #else static PyMethodDef swigobject_methods[] = { {(char *)"disown", (PyCFunction)PySwigObject_disown, METH_VARARGS, (char *)"releases ownership of the pointer"}, {(char *)"acquire", (PyCFunction)PySwigObject_acquire, METH_VARARGS, (char *)"aquires ownership of the pointer"}, {(char *)"own", (PyCFunction)PySwigObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, {(char *)"append", (PyCFunction)PySwigObject_append, METH_VARARGS, (char *)"appends another 'this' object"}, {(char *)"next", (PyCFunction)PySwigObject_next, METH_VARARGS, (char *)"returns the next 'this' object"}, {(char *)"__repr__",(PyCFunction)PySwigObject_repr, METH_VARARGS, (char *)"returns object representation"}, {0, 0, 0, 0} }; #endif #if PY_VERSION_HEX < 0x02020000 SWIGINTERN PyObject * PySwigObject_getattr(PySwigObject *sobj,char *name) { return Py_FindMethod(swigobject_methods, (PyObject *)sobj, name); } #endif SWIGRUNTIME PyTypeObject* _PySwigObject_type(void) { static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer"; static PyNumberMethods PySwigObject_as_number = { (binaryfunc)0, /*nb_add*/ (binaryfunc)0, /*nb_subtract*/ (binaryfunc)0, /*nb_multiply*/ (binaryfunc)0, /*nb_divide*/ (binaryfunc)0, /*nb_remainder*/ (binaryfunc)0, /*nb_divmod*/ (ternaryfunc)0,/*nb_power*/ (unaryfunc)0, /*nb_negative*/ (unaryfunc)0, /*nb_positive*/ (unaryfunc)0, /*nb_absolute*/ (inquiry)0, /*nb_nonzero*/ 0, /*nb_invert*/ 0, /*nb_lshift*/ 0, /*nb_rshift*/ 0, /*nb_and*/ 0, /*nb_xor*/ 0, /*nb_or*/ (coercion)0, /*nb_coerce*/ (unaryfunc)PySwigObject_long, /*nb_int*/ (unaryfunc)PySwigObject_long, /*nb_long*/ (unaryfunc)0, /*nb_float*/ (unaryfunc)PySwigObject_oct, /*nb_oct*/ (unaryfunc)PySwigObject_hex, /*nb_hex*/ #if PY_VERSION_HEX >= 0x02050000 /* 2.5.0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index */ #elif PY_VERSION_HEX >= 0x02020000 /* 2.2.0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_true_divide */ #elif PY_VERSION_HEX >= 0x02000000 /* 2.0.0 */ 0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_or */ #endif }; static PyTypeObject pyswigobject_type; static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ (char *)"PySwigObject", /* tp_name */ sizeof(PySwigObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)PySwigObject_dealloc, /* tp_dealloc */ (printfunc)PySwigObject_print, /* tp_print */ #if PY_VERSION_HEX < 0x02020000 (getattrfunc)PySwigObject_getattr, /* tp_getattr */ #else (getattrfunc)0, /* tp_getattr */ #endif (setattrfunc)0, /* tp_setattr */ (cmpfunc)PySwigObject_compare, /* tp_compare */ (reprfunc)PySwigObject_repr, /* tp_repr */ &PySwigObject_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)0, /* tp_hash */ (ternaryfunc)0, /* tp_call */ (reprfunc)PySwigObject_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ swigobject_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ #if PY_VERSION_HEX >= 0x02020000 0, /* tp_iter */ 0, /* tp_iternext */ swigobject_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ #endif #if PY_VERSION_HEX >= 0x02030000 0, /* tp_del */ #endif #ifdef COUNT_ALLOCS 0,0,0,0 /* tp_alloc -> tp_next */ #endif }; pyswigobject_type = tmp; pyswigobject_type.ob_type = &PyType_Type; type_init = 1; } return &pyswigobject_type; } SWIGRUNTIME PyObject * PySwigObject_New(void *ptr, swig_type_info *ty, int own) { PySwigObject *sobj = PyObject_NEW(PySwigObject, PySwigObject_type()); if (sobj) { sobj->ptr = ptr; sobj->ty = ty; sobj->own = own; sobj->next = 0; } return (PyObject *)sobj; } /* ----------------------------------------------------------------------------- * Implements a simple Swig Packed type, and use it instead of string * ----------------------------------------------------------------------------- */ typedef struct { PyObject_HEAD void *pack; swig_type_info *ty; size_t size; } PySwigPacked; SWIGRUNTIME int PySwigPacked_print(PySwigPacked *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { char result[SWIG_BUFFER_SIZE]; fputs("<Swig Packed ", fp); if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { fputs("at ", fp); fputs(result, fp); } fputs(v->ty->name,fp); fputs(">", fp); return 0; } SWIGRUNTIME PyObject * PySwigPacked_repr(PySwigPacked *v) { char result[SWIG_BUFFER_SIZE]; if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { return PyString_FromFormat("<Swig Packed at %s%s>", result, v->ty->name); } else { return PyString_FromFormat("<Swig Packed %s>", v->ty->name); } } SWIGRUNTIME PyObject * PySwigPacked_str(PySwigPacked *v) { char result[SWIG_BUFFER_SIZE]; if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){ return PyString_FromFormat("%s%s", result, v->ty->name); } else { return PyString_FromString(v->ty->name); } } SWIGRUNTIME int PySwigPacked_compare(PySwigPacked *v, PySwigPacked *w) { size_t i = v->size; size_t j = w->size; int s = (i < j) ? -1 : ((i > j) ? 1 : 0); return s ? s : strncmp((char *)v->pack, (char *)w->pack, 2*v->size); } SWIGRUNTIME PyTypeObject* _PySwigPacked_type(void); SWIGRUNTIME PyTypeObject* PySwigPacked_type(void) { static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigPacked_type(); return type; } SWIGRUNTIMEINLINE int PySwigPacked_Check(PyObject *op) { return ((op)->ob_type == _PySwigPacked_type()) || (strcmp((op)->ob_type->tp_name,"PySwigPacked") == 0); } SWIGRUNTIME void PySwigPacked_dealloc(PyObject *v) { if (PySwigPacked_Check(v)) { PySwigPacked *sobj = (PySwigPacked *) v; free(sobj->pack); } PyObject_DEL(v); } SWIGRUNTIME PyTypeObject* _PySwigPacked_type(void) { static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer"; static PyTypeObject pyswigpacked_type; static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ (char *)"PySwigPacked", /* tp_name */ sizeof(PySwigPacked), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)PySwigPacked_dealloc, /* tp_dealloc */ (printfunc)PySwigPacked_print, /* tp_print */ (getattrfunc)0, /* tp_getattr */ (setattrfunc)0, /* tp_setattr */ (cmpfunc)PySwigPacked_compare, /* tp_compare */ (reprfunc)PySwigPacked_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)0, /* tp_hash */ (ternaryfunc)0, /* tp_call */ (reprfunc)PySwigPacked_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ swigpacked_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ #if PY_VERSION_HEX >= 0x02020000 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ #endif #if PY_VERSION_HEX >= 0x02030000 0, /* tp_del */ #endif #ifdef COUNT_ALLOCS 0,0,0,0 /* tp_alloc -> tp_next */ #endif }; pyswigpacked_type = tmp; pyswigpacked_type.ob_type = &PyType_Type; type_init = 1; } return &pyswigpacked_type; } SWIGRUNTIME PyObject * PySwigPacked_New(void *ptr, size_t size, swig_type_info *ty) { PySwigPacked *sobj = PyObject_NEW(PySwigPacked, PySwigPacked_type()); if (sobj) { void *pack = malloc(size); if (pack) { memcpy(pack, ptr, size); sobj->pack = pack; sobj->ty = ty; sobj->size = size; } else { PyObject_DEL((PyObject *) sobj); sobj = 0; } } return (PyObject *) sobj; } SWIGRUNTIME swig_type_info * PySwigPacked_UnpackData(PyObject *obj, void *ptr, size_t size) { if (PySwigPacked_Check(obj)) { PySwigPacked *sobj = (PySwigPacked *)obj; if (sobj->size != size) return 0; memcpy(ptr, sobj->pack, size); return sobj->ty; } else { return 0; } } /* ----------------------------------------------------------------------------- * pointers/data manipulation * ----------------------------------------------------------------------------- */ SWIGRUNTIMEINLINE PyObject * _SWIG_This(void) { return PyString_FromString("this"); } SWIGRUNTIME PyObject * SWIG_This(void) { static PyObject *SWIG_STATIC_POINTER(swig_this) = _SWIG_This(); return swig_this; } /* #define SWIG_PYTHON_SLOW_GETSET_THIS */ SWIGRUNTIME PySwigObject * SWIG_Python_GetSwigThis(PyObject *pyobj) { if (PySwigObject_Check(pyobj)) { return (PySwigObject *) pyobj; } else { PyObject *obj = 0; #if (!defined(SWIG_PYTHON_SLOW_GETSET_THIS) && (PY_VERSION_HEX >= 0x02030000)) if (PyInstance_Check(pyobj)) { obj = _PyInstance_Lookup(pyobj, SWIG_This()); } else { PyObject **dictptr = _PyObject_GetDictPtr(pyobj); if (dictptr != NULL) { PyObject *dict = *dictptr; obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0; } else { #ifdef PyWeakref_CheckProxy if (PyWeakref_CheckProxy(pyobj)) { PyObject *wobj = PyWeakref_GET_OBJECT(pyobj); return wobj ? SWIG_Python_GetSwigThis(wobj) : 0; } #endif obj = PyObject_GetAttr(pyobj,SWIG_This()); if (obj) { Py_DECREF(obj); } else { if (PyErr_Occurred()) PyErr_Clear(); return 0; } } } #else obj = PyObject_GetAttr(pyobj,SWIG_This()); if (obj) { Py_DECREF(obj); } else { if (PyErr_Occurred()) PyErr_Clear(); return 0; } #endif if (obj && !PySwigObject_Check(obj)) { /* a PyObject is called 'this', try to get the 'real this' PySwigObject from it */ return SWIG_Python_GetSwigThis(obj); } return (PySwigObject *)obj; } } /* Acquire a pointer value */ SWIGRUNTIME int SWIG_Python_AcquirePtr(PyObject *obj, int own) { if (own == SWIG_POINTER_OWN) { PySwigObject *sobj = SWIG_Python_GetSwigThis(obj); if (sobj) { int oldown = sobj->own; sobj->own = own; return oldown; } } return 0; } /* Convert a pointer value */ SWIGRUNTIME int SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) { if (!obj) return SWIG_ERROR; if (obj == Py_None) { if (ptr) *ptr = 0; return SWIG_OK; } else { PySwigObject *sobj = SWIG_Python_GetSwigThis(obj); if (own) *own = 0; while (sobj) { void *vptr = sobj->ptr; if (ty) { swig_type_info *to = sobj->ty; if (to == ty) { /* no type cast needed */ if (ptr) *ptr = vptr; break; } else { swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); if (!tc) { sobj = (PySwigObject *)sobj->next; } else { if (ptr) { int newmemory = 0; *ptr = SWIG_TypeCast(tc,vptr,&newmemory); if (newmemory == SWIG_CAST_NEW_MEMORY) { assert(own); if (own) *own = *own | SWIG_CAST_NEW_MEMORY; } } break; } } } else { if (ptr) *ptr = vptr; break; } } if (sobj) { if (own) *own = *own | sobj->own; if (flags & SWIG_POINTER_DISOWN) { sobj->own = 0; } return SWIG_OK; } else { int res = SWIG_ERROR; if (flags & SWIG_POINTER_IMPLICIT_CONV) { PySwigClientData *data = ty ? (PySwigClientData *) ty->clientdata : 0; if (data && !data->implicitconv) { PyObject *klass = data->klass; if (klass) { PyObject *impconv; data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/ impconv = SWIG_Python_CallFunctor(klass, obj); data->implicitconv = 0; if (PyErr_Occurred()) { PyErr_Clear(); impconv = 0; } if (impconv) { PySwigObject *iobj = SWIG_Python_GetSwigThis(impconv); if (iobj) { void *vptr; res = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0); if (SWIG_IsOK(res)) { if (ptr) { *ptr = vptr; /* transfer the ownership to 'ptr' */ iobj->own = 0; res = SWIG_AddCast(res); res = SWIG_AddNewMask(res); } else { res = SWIG_AddCast(res); } } } Py_DECREF(impconv); } } } } return res; } } } /* Convert a function ptr value */ SWIGRUNTIME int SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) { if (!PyCFunction_Check(obj)) { return SWIG_ConvertPtr(obj, ptr, ty, 0); } else { void *vptr = 0; /* here we get the method pointer for callbacks */ const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc); const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0; if (desc) { desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0; if (!desc) return SWIG_ERROR; } if (ty) { swig_cast_info *tc = SWIG_TypeCheck(desc,ty); if (tc) { int newmemory = 0; *ptr = SWIG_TypeCast(tc,vptr,&newmemory); assert(!newmemory); /* newmemory handling not yet implemented */ } else { return SWIG_ERROR; } } else { *ptr = vptr; } return SWIG_OK; } } /* Convert a packed value value */ SWIGRUNTIME int SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) { swig_type_info *to = PySwigPacked_UnpackData(obj, ptr, sz); if (!to) return SWIG_ERROR; if (ty) { if (to != ty) { /* check type cast? */ swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); if (!tc) return SWIG_ERROR; } } return SWIG_OK; } /* ----------------------------------------------------------------------------- * Create a new pointer object * ----------------------------------------------------------------------------- */ /* Create a new instance object, whitout calling __init__, and set the 'this' attribute. */ SWIGRUNTIME PyObject* SWIG_Python_NewShadowInstance(PySwigClientData *data, PyObject *swig_this) { #if (PY_VERSION_HEX >= 0x02020000) PyObject *inst = 0; PyObject *newraw = data->newraw; if (newraw) { inst = PyObject_Call(newraw, data->newargs, NULL); if (inst) { #if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) PyObject **dictptr = _PyObject_GetDictPtr(inst); if (dictptr != NULL) { PyObject *dict = *dictptr; if (dict == NULL) { dict = PyDict_New(); *dictptr = dict; PyDict_SetItem(dict, SWIG_This(), swig_this); } } #else PyObject *key = SWIG_This(); PyObject_SetAttr(inst, key, swig_this); #endif } } else { PyObject *dict = PyDict_New(); PyDict_SetItem(dict, SWIG_This(), swig_this); inst = PyInstance_NewRaw(data->newargs, dict); Py_DECREF(dict); } return inst; #else #if (PY_VERSION_HEX >= 0x02010000) PyObject *inst; PyObject *dict = PyDict_New(); PyDict_SetItem(dict, SWIG_This(), swig_this); inst = PyInstance_NewRaw(data->newargs, dict); Py_DECREF(dict); return (PyObject *) inst; #else PyInstanceObject *inst = PyObject_NEW(PyInstanceObject, &PyInstance_Type); if (inst == NULL) { return NULL; } inst->in_class = (PyClassObject *)data->newargs; Py_INCREF(inst->in_class); inst->in_dict = PyDict_New(); if (inst->in_dict == NULL) { Py_DECREF(inst); return NULL; } #ifdef Py_TPFLAGS_HAVE_WEAKREFS inst->in_weakreflist = NULL; #endif #ifdef Py_TPFLAGS_GC PyObject_GC_Init(inst); #endif PyDict_SetItem(inst->in_dict, SWIG_This(), swig_this); return (PyObject *) inst; #endif #endif } SWIGRUNTIME void SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this) { PyObject *dict; #if (PY_VERSION_HEX >= 0x02020000) && !defined(SWIG_PYTHON_SLOW_GETSET_THIS) PyObject **dictptr = _PyObject_GetDictPtr(inst); if (dictptr != NULL) { dict = *dictptr; if (dict == NULL) { dict = PyDict_New(); *dictptr = dict; } PyDict_SetItem(dict, SWIG_This(), swig_this); return; } #endif dict = PyObject_GetAttrString(inst, (char*)"__dict__"); PyDict_SetItem(dict, SWIG_This(), swig_this); Py_DECREF(dict); } SWIGINTERN PyObject * SWIG_Python_InitShadowInstance(PyObject *args) { PyObject *obj[2]; if (!SWIG_Python_UnpackTuple(args,(char*)"swiginit", 2, 2, obj)) { return NULL; } else { PySwigObject *sthis = SWIG_Python_GetSwigThis(obj[0]); if (sthis) { PySwigObject_append((PyObject*) sthis, obj[1]); } else { SWIG_Python_SetSwigThis(obj[0], obj[1]); } return SWIG_Py_Void(); } } /* Create a new pointer object */ SWIGRUNTIME PyObject * SWIG_Python_NewPointerObj(void *ptr, swig_type_info *type, int flags) { if (!ptr) { return SWIG_Py_Void(); } else { int own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0; PyObject *robj = PySwigObject_New(ptr, type, own); PySwigClientData *clientdata = type ? (PySwigClientData *)(type->clientdata) : 0; if (clientdata && !(flags & SWIG_POINTER_NOSHADOW)) { PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj); if (inst) { Py_DECREF(robj); robj = inst; } } return robj; } } /* Create a new packed object */ SWIGRUNTIMEINLINE PyObject * SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) { return ptr ? PySwigPacked_New((void *) ptr, sz, type) : SWIG_Py_Void(); } /* -----------------------------------------------------------------------------* * Get type list * -----------------------------------------------------------------------------*/ #ifdef SWIG_LINK_RUNTIME void *SWIG_ReturnGlobalTypeList(void *); #endif SWIGRUNTIME swig_module_info * SWIG_Python_GetModule(void) { static void *type_pointer = (void *)0; /* first check if module already created */ if (!type_pointer) { #ifdef SWIG_LINK_RUNTIME type_pointer = SWIG_ReturnGlobalTypeList((void *)0); #else type_pointer = PyCObject_Import((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME); if (PyErr_Occurred()) { PyErr_Clear(); type_pointer = (void *)0; } #endif } return (swig_module_info *) type_pointer; } #if PY_MAJOR_VERSION < 2 /* PyModule_AddObject function was introduced in Python 2.0. The following function is copied out of Python/modsupport.c in python version 2.3.4 */ SWIGINTERN int PyModule_AddObject(PyObject *m, char *name, PyObject *o) { PyObject *dict; if (!PyModule_Check(m)) { PyErr_SetString(PyExc_TypeError, "PyModule_AddObject() needs module as first arg"); return SWIG_ERROR; } if (!o) { PyErr_SetString(PyExc_TypeError, "PyModule_AddObject() needs non-NULL value"); return SWIG_ERROR; } dict = PyModule_GetDict(m); if (dict == NULL) { /* Internal error -- modules must have a dict! */ PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__", PyModule_GetName(m)); return SWIG_ERROR; } if (PyDict_SetItemString(dict, name, o)) return SWIG_ERROR; Py_DECREF(o); return SWIG_OK; } #endif SWIGRUNTIME void SWIG_Python_DestroyModule(void *vptr) { swig_module_info *swig_module = (swig_module_info *) vptr; swig_type_info **types = swig_module->types; size_t i; for (i =0; i < swig_module->size; ++i) { swig_type_info *ty = types[i]; if (ty->owndata) { PySwigClientData *data = (PySwigClientData *) ty->clientdata; if (data) PySwigClientData_Del(data); } } Py_DECREF(SWIG_This()); } SWIGRUNTIME void SWIG_Python_SetModule(swig_module_info *swig_module) { static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} };/* Sentinel */ PyObject *module = Py_InitModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, swig_empty_runtime_method_table); PyObject *pointer = PyCObject_FromVoidPtr((void *) swig_module, SWIG_Python_DestroyModule); if (pointer && module) { PyModule_AddObject(module, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME, pointer); } else { Py_XDECREF(pointer); } } /* The python cached type query */ SWIGRUNTIME PyObject * SWIG_Python_TypeCache(void) { static PyObject *SWIG_STATIC_POINTER(cache) = PyDict_New(); return cache; } SWIGRUNTIME swig_type_info * SWIG_Python_TypeQuery(const char *type) { PyObject *cache = SWIG_Python_TypeCache(); PyObject *key = PyString_FromString(type); PyObject *obj = PyDict_GetItem(cache, key); swig_type_info *descriptor; if (obj) { descriptor = (swig_type_info *) PyCObject_AsVoidPtr(obj); } else { swig_module_info *swig_module = SWIG_Python_GetModule(); descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type); if (descriptor) { obj = PyCObject_FromVoidPtr(descriptor, NULL); PyDict_SetItem(cache, key, obj); Py_DECREF(obj); } } Py_DECREF(key); return descriptor; } /* For backward compatibility only */ #define SWIG_POINTER_EXCEPTION 0 #define SWIG_arg_fail(arg) SWIG_Python_ArgFail(arg) #define SWIG_MustGetPtr(p, type, argnum, flags) SWIG_Python_MustGetPtr(p, type, argnum, flags) SWIGRUNTIME int SWIG_Python_AddErrMesg(const char* mesg, int infront) { if (PyErr_Occurred()) { PyObject *type = 0; PyObject *value = 0; PyObject *traceback = 0; PyErr_Fetch(&type, &value, &traceback); if (value) { PyObject *old_str = PyObject_Str(value); Py_XINCREF(type); PyErr_Clear(); if (infront) { PyErr_Format(type, "%s %s", mesg, PyString_AsString(old_str)); } else { PyErr_Format(type, "%s %s", PyString_AsString(old_str), mesg); } Py_DECREF(old_str); } return 1; } else { return 0; } } SWIGRUNTIME int SWIG_Python_ArgFail(int argnum) { if (PyErr_Occurred()) { /* add information about failing argument */ char mesg[256]; PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum); return SWIG_Python_AddErrMesg(mesg, 1); } else { return 0; } } SWIGRUNTIMEINLINE const char * PySwigObject_GetDesc(PyObject *self) { PySwigObject *v = (PySwigObject *)self; swig_type_info *ty = v ? v->ty : 0; return ty ? ty->str : (char*)""; } SWIGRUNTIME void SWIG_Python_TypeError(const char *type, PyObject *obj) { if (type) { #if defined(SWIG_COBJECT_TYPES) if (obj && PySwigObject_Check(obj)) { const char *otype = (const char *) PySwigObject_GetDesc(obj); if (otype) { PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'PySwigObject(%s)' is received", type, otype); return; } } else #endif { const char *otype = (obj ? obj->ob_type->tp_name : 0); if (otype) { PyObject *str = PyObject_Str(obj); const char *cstr = str ? PyString_AsString(str) : 0; if (cstr) { PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received", type, otype, cstr); } else { PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received", type, otype); } Py_XDECREF(str); return; } } PyErr_Format(PyExc_TypeError, "a '%s' is expected", type); } else { PyErr_Format(PyExc_TypeError, "unexpected type is received"); } } /* Convert a pointer value, signal an exception on a type mismatch */ SWIGRUNTIME void * SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags) { void *result; if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) { PyErr_Clear(); if (flags & SWIG_POINTER_EXCEPTION) { SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj); SWIG_Python_ArgFail(argnum); } } return result; } #ifdef __cplusplus #if 0 { /* cc-mode */ #endif } #endif #define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) #define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else /* -------- TYPES TABLE (BEGIN) -------- */ #define SWIGTYPE_p_FILE swig_types[0] #define SWIGTYPE_p_char swig_types[1] #define SWIGTYPE_p_double swig_types[2] #define SWIGTYPE_p_float swig_types[3] #define SWIGTYPE_p_gsl_complex swig_types[4] #define SWIGTYPE_p_gsl_complex_float swig_types[5] #define SWIGTYPE_p_gsl_matrix swig_types[6] #define SWIGTYPE_p_gsl_matrix_char swig_types[7] #define SWIGTYPE_p_gsl_matrix_complex swig_types[8] #define SWIGTYPE_p_gsl_matrix_complex_float swig_types[9] #define SWIGTYPE_p_gsl_matrix_float swig_types[10] #define SWIGTYPE_p_gsl_matrix_int swig_types[11] #define SWIGTYPE_p_gsl_matrix_long swig_types[12] #define SWIGTYPE_p_gsl_matrix_short swig_types[13] #define SWIGTYPE_p_gsl_vector swig_types[14] #define SWIGTYPE_p_gsl_vector_char swig_types[15] #define SWIGTYPE_p_gsl_vector_complex swig_types[16] #define SWIGTYPE_p_gsl_vector_complex_float swig_types[17] #define SWIGTYPE_p_gsl_vector_float swig_types[18] #define SWIGTYPE_p_gsl_vector_int swig_types[19] #define SWIGTYPE_p_gsl_vector_long swig_types[20] #define SWIGTYPE_p_gsl_vector_short swig_types[21] #define SWIGTYPE_p_int swig_types[22] #define SWIGTYPE_p_long swig_types[23] #define SWIGTYPE_p_short swig_types[24] #define SWIGTYPE_p_unsigned_int swig_types[25] static swig_type_info *swig_types[27]; static swig_module_info swig_module = {swig_types, 26, 0, 0, 0, 0}; #define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) #define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) /* -------- TYPES TABLE (END) -------- */ #if (PY_VERSION_HEX <= 0x02000000) # if !defined(SWIG_PYTHON_CLASSIC) # error "This python version requires swig to be run with the '-classic' option" # endif #endif /*----------------------------------------------- @(target):= __block.so ------------------------------------------------*/ #define SWIG_init init__block #define SWIG_name "__block" #define SWIGVERSION 0x010336 #define SWIG_VERSION SWIGVERSION #define SWIG_as_voidptr(a) (void *)((const void *)(a)) #define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),(void**)(a)) #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_complex.h> #include <stdlib.h> #include <assert.h> #include <pygsl/error_helpers.h> /* * Normally Microsofts (R) Visual C (TM) Compiler is used to compile python * on windows. * When I used MinGW to compile I could not convert Python File Objects to * C File Structs (The function PyFile_AsFile generated a core). Therefore * I raise a python exception if someone tries to use this Code when it was * compiled with MinGW. Do you know a better solution? Perhaps how to get it * work? */ #ifdef __MINGW32__ #define HANDLE_MINGW() \ do { \ PyGSL_add_traceback(NULL, __FILE__, __FUNCTION__, __LINE__); \ PyErr_SetString(PyExc_TypeError, "This Module was compiled using MinGW32. " \ "Conversion of python files to C files is not supported.");\ goto fail; \ } while(0) #else #define HANDLE_MINGW() #endif #include <pygsl/utils.h> #include <pygsl/block_helpers.h> #include <typemaps/block_conversion_functions.h> #include <string.h> #include <assert.h> #include <pygsl/utils.h> #include <pygsl/error_helpers.h> typedef int gsl_error_flag; typedef int gsl_error_flag_drop; PyObject *pygsl_module_for_error_treatment = NULL; SWIGINTERN int SWIG_AsVal_double (PyObject *obj, double *val) { int res = SWIG_TypeError; if (PyFloat_Check(obj)) { if (val) *val = PyFloat_AsDouble(obj); return SWIG_OK; } else if (PyInt_Check(obj)) { if (val) *val = PyInt_AsLong(obj); return SWIG_OK; } else if (PyLong_Check(obj)) { double v = PyLong_AsDouble(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_OK; } else { PyErr_Clear(); } } #ifdef SWIG_PYTHON_CAST_MODE { int dispatch = 0; double d = PyFloat_AsDouble(obj); if (!PyErr_Occurred()) { if (val) *val = d; return SWIG_AddCast(SWIG_OK); } else { PyErr_Clear(); } if (!dispatch) { long v = PyLong_AsLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_AddCast(SWIG_AddCast(SWIG_OK)); } else { PyErr_Clear(); } } } #endif return res; } #include <float.h> #include <math.h> SWIGINTERNINLINE int SWIG_CanCastAsInteger(double *d, double min, double max) { double x = *d; if ((min <= x && x <= max)) { double fx = floor(x); double cx = ceil(x); double rd = ((x - fx) < 0.5) ? fx : cx; /* simple rint */ if ((errno == EDOM) || (errno == ERANGE)) { errno = 0; } else { double summ, reps, diff; if (rd < x) { diff = x - rd; } else if (rd > x) { diff = rd - x; } else { return 1; } summ = rd + x; reps = diff/summ; if (reps < 8*DBL_EPSILON) { *d = rd; return 1; } } } return 0; } SWIGINTERN int SWIG_AsVal_unsigned_SS_long (PyObject *obj, unsigned long *val) { if (PyInt_Check(obj)) { long v = PyInt_AsLong(obj); if (v >= 0) { if (val) *val = v; return SWIG_OK; } else { return SWIG_OverflowError; } } else if (PyLong_Check(obj)) { unsigned long v = PyLong_AsUnsignedLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_OK; } else { PyErr_Clear(); } } #ifdef SWIG_PYTHON_CAST_MODE { int dispatch = 0; unsigned long v = PyLong_AsUnsignedLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_AddCast(SWIG_OK); } else { PyErr_Clear(); } if (!dispatch) { double d; int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d)); if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, 0, ULONG_MAX)) { if (val) *val = (unsigned long)(d); return res; } } } #endif return SWIG_TypeError; } SWIGINTERNINLINE int SWIG_AsVal_size_t (PyObject * obj, size_t *val) { unsigned long v; int res = SWIG_AsVal_unsigned_SS_long (obj, val ? &v : 0); if (SWIG_IsOK(res) && val) *val = (size_t)(v); return res; } SWIGINTERN swig_type_info* SWIG_pchar_descriptor(void) { static int init = 0; static swig_type_info* info = 0; if (!init) { info = SWIG_TypeQuery("_p_char"); init = 1; } return info; } SWIGINTERN int SWIG_AsCharPtrAndSize(PyObject *obj, char** cptr, size_t* psize, int *alloc) { if (PyString_Check(obj)) { char *cstr; Py_ssize_t len; PyString_AsStringAndSize(obj, &cstr, &len); if (cptr) { if (alloc) { /* In python the user should not be able to modify the inner string representation. To warranty that, if you define SWIG_PYTHON_SAFE_CSTRINGS, a new/copy of the python string buffer is always returned. The default behavior is just to return the pointer value, so, be careful. */ #if defined(SWIG_PYTHON_SAFE_CSTRINGS) if (*alloc != SWIG_OLDOBJ) #else if (*alloc == SWIG_NEWOBJ) #endif { *cptr = (char *)memcpy((char *)malloc((len + 1)*sizeof(char)), cstr, sizeof(char)*(len + 1)); *alloc = SWIG_NEWOBJ; } else { *cptr = cstr; *alloc = SWIG_OLDOBJ; } } else { *cptr = PyString_AsString(obj); } } if (psize) *psize = len + 1; return SWIG_OK; } else { swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); if (pchar_descriptor) { void* vptr = 0; if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { if (cptr) *cptr = (char *) vptr; if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0; if (alloc) *alloc = SWIG_OLDOBJ; return SWIG_OK; } } } return SWIG_TypeError; } #define SWIG_From_double PyFloat_FromDouble #define SWIG_From_long PyInt_FromLong SWIGINTERNINLINE PyObject* SWIG_From_unsigned_SS_long (unsigned long value) { return (value > LONG_MAX) ? PyLong_FromUnsignedLong(value) : PyInt_FromLong((long)(value)); } SWIGINTERNINLINE PyObject * SWIG_From_size_t (size_t value) { return SWIG_From_unsigned_SS_long ((unsigned long)(value)); } SWIGINTERNINLINE PyObject * SWIG_From_int (int value) { return SWIG_From_long (value); } SWIGINTERN int SWIG_AsVal_float (PyObject * obj, float *val) { double v; int res = SWIG_AsVal_double (obj, &v); if (SWIG_IsOK(res)) { if ((v < -FLT_MAX || v > FLT_MAX)) { return SWIG_OverflowError; } else { if (val) *val = (float)(v); } } return res; } SWIGINTERNINLINE PyObject * SWIG_From_float (float value) { return SWIG_From_double (value); } SWIGINTERN int SWIG_AsVal_long (PyObject *obj, long* val) { if (PyInt_Check(obj)) { if (val) *val = PyInt_AsLong(obj); return SWIG_OK; } else if (PyLong_Check(obj)) { long v = PyLong_AsLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_OK; } else { PyErr_Clear(); } } #ifdef SWIG_PYTHON_CAST_MODE { int dispatch = 0; long v = PyInt_AsLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_AddCast(SWIG_OK); } else { PyErr_Clear(); } if (!dispatch) { double d; int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d)); if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, LONG_MAX)) { if (val) *val = (long)(d); return res; } } } #endif return SWIG_TypeError; } #include <limits.h> #if !defined(SWIG_NO_LLONG_MAX) # if !defined(LLONG_MAX) && defined(__GNUC__) && defined (__LONG_LONG_MAX__) # define LLONG_MAX __LONG_LONG_MAX__ # define LLONG_MIN (-LLONG_MAX - 1LL) # define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL) # endif #endif SWIGINTERN int SWIG_AsVal_int (PyObject * obj, int *val) { long v; int res = SWIG_AsVal_long (obj, &v); if (SWIG_IsOK(res)) { if ((v < INT_MIN || v > INT_MAX)) { return SWIG_OverflowError; } else { if (val) *val = (int)(v); } } return res; } SWIGINTERN int SWIG_AsVal_short (PyObject * obj, short *val) { long v; int res = SWIG_AsVal_long (obj, &v); if (SWIG_IsOK(res)) { if ((v < SHRT_MIN || v > SHRT_MAX)) { return SWIG_OverflowError; } else { if (val) *val = (short)(v); } } return res; } SWIGINTERNINLINE PyObject * SWIG_From_short (short value) { return SWIG_From_long (value); } SWIGINTERN int SWIG_AsCharArray(PyObject * obj, char *val, size_t size) { char* cptr = 0; size_t csize = 0; int alloc = SWIG_OLDOBJ; int res = SWIG_AsCharPtrAndSize(obj, &cptr, &csize, &alloc); if (SWIG_IsOK(res)) { if ((csize == size + 1) && cptr && !(cptr[csize-1])) --csize; if (csize <= size) { if (val) { if (csize) memcpy(val, cptr, csize*sizeof(char)); if (csize < size) memset(val + csize, 0, (size - csize)*sizeof(char)); } if (alloc == SWIG_NEWOBJ) { free((char*)cptr); res = SWIG_DelNewMask(res); } return res; } if (alloc == SWIG_NEWOBJ) free((char*)cptr); } return SWIG_TypeError; } SWIGINTERN int SWIG_AsVal_char (PyObject * obj, char *val) { int res = SWIG_AsCharArray(obj, val, 1); if (!SWIG_IsOK(res)) { long v; res = SWIG_AddCast(SWIG_AsVal_long (obj, &v)); if (SWIG_IsOK(res)) { if ((CHAR_MIN <= v) && (v <= CHAR_MAX)) { if (val) *val = (char)(v); } else { res = SWIG_OverflowError; } } } return res; } SWIGINTERNINLINE PyObject * SWIG_FromCharPtrAndSize(const char* carray, size_t size) { if (carray) { if (size > INT_MAX) { swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); return pchar_descriptor ? SWIG_NewPointerObj((char *)(carray), pchar_descriptor, 0) : SWIG_Py_Void(); } else { return PyString_FromStringAndSize(carray, (int)(size)); } } else { return SWIG_Py_Void(); } } SWIGINTERNINLINE PyObject * SWIG_From_char (char c) { return SWIG_FromCharPtrAndSize(&c,1); } #define _GSL_BLOCK_COMPLEX_FUNCTIONS_C #include <gsl/gsl_errno.h> #include <pygsl/utils.h> #include <pygsl/complex_helpers.h> #ifdef __cplusplus extern "C" { #endif SWIGINTERN PyObject *_wrap_gsl_vector_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector *arg1 = (gsl_vector *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_set_zero",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } gsl_vector_set_zero(arg1); resultobj = SWIG_Py_Void(); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector *arg1 = (gsl_vector *) 0 ; double arg2 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "x", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_set_all",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_vector_set_all" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); gsl_vector_set_all(arg1,arg2); resultobj = SWIG_Py_Void(); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_set_basis(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector *arg1 = (gsl_vector *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "i", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_set_basis",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_vector_set_basis" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = (int)gsl_vector_set_basis(arg1,arg2); { resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result); if (resultobj == NULL){ PyGSL_add_traceback(pygsl_module_for_error_treatment, "typemaps/gsl_error_typemap.i", __FUNCTION__, 48); goto fail; } } { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector *arg2 = (gsl_vector *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_fread",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; int flag; _vector2.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2, PyGSL_OUTPUT_ARRAY, gsl_vector, 2, &stride); if (flag != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_fread(arg1,arg2); { resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result); if (resultobj == NULL){ PyGSL_add_traceback(pygsl_module_for_error_treatment, "typemaps/gsl_error_typemap.i", __FUNCTION__, 48); goto fail; } } { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyVector2); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyVector2); _PyVector2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector *arg2 = (gsl_vector *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_fwrite",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_INPUT_ARRAY, gsl_vector, 2, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_fwrite(arg1,(gsl_vector const *)arg2); { resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result); if (resultobj == NULL){ PyGSL_add_traceback(pygsl_module_for_error_treatment, "typemaps/gsl_error_typemap.i", __FUNCTION__, 48); goto fail; } } { Py_XDECREF(_PyVector2); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyVector2); _PyVector2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector *arg2 = (gsl_vector *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_fscanf",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; int flag; _vector2.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2, PyGSL_OUTPUT_ARRAY, gsl_vector, 2, &stride); if (flag != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_fscanf(arg1,arg2); { resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result); if (resultobj == NULL){ PyGSL_add_traceback(pygsl_module_for_error_treatment, "typemaps/gsl_error_typemap.i", __FUNCTION__, 48); goto fail; } } { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyVector2); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyVector2); _PyVector2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector *arg2 = (gsl_vector *) 0 ; char *arg3 = (char *) 0 ; int res3 ; char *buf3 = 0 ; int alloc3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN",(char *) "format", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_vector_fprintf",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_INPUT_ARRAY, gsl_vector, 2, &stride) != GSL_SUCCESS){ goto fail; } } res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "gsl_vector_fprintf" "', argument " "3"" of type '" "char const *""'"); } arg3 = (char *)(buf3); result = (int)gsl_vector_fprintf(arg1,(gsl_vector const *)arg2,(char const *)arg3); { resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result); if (resultobj == NULL){ PyGSL_add_traceback(pygsl_module_for_error_treatment, "typemaps/gsl_error_typemap.i", __FUNCTION__, 48); goto fail; } } { Py_XDECREF(_PyVector2); _PyVector2 = NULL; FUNC_MESS_END(); } if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return resultobj; fail: { Py_XDECREF(_PyVector2); _PyVector2 = NULL; FUNC_MESS_END(); } if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_reverse(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector *arg1 = (gsl_vector *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "INOUT", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_reverse",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_reverse(arg1); { resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result); if (resultobj == NULL){ PyGSL_add_traceback(pygsl_module_for_error_treatment, "typemaps/gsl_error_typemap.i", __FUNCTION__, 48); goto fail; } } { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector *arg1 = (gsl_vector *) 0 ; gsl_vector *arg2 = (gsl_vector *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "INOUT", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector _vector1; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_swap",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){ goto fail; } } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_IO_ARRAY, gsl_vector, 2, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_swap(arg1,arg2); { resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result); if (resultobj == NULL){ PyGSL_add_traceback(pygsl_module_for_error_treatment, "typemaps/gsl_error_typemap.i", __FUNCTION__, 48); goto fail; } } { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyVector2); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyVector2); _PyVector2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_swap_elements(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector *arg1 = (gsl_vector *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_vector_swap_elements",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){ goto fail; } } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_vector_swap_elements" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_vector_swap_elements" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_vector_swap_elements(arg1,arg2,arg3); { resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result); if (resultobj == NULL){ PyGSL_add_traceback(pygsl_module_for_error_treatment, "typemaps/gsl_error_typemap.i", __FUNCTION__, 48); goto fail; } } { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector *arg1 = (gsl_vector *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_max",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (double)gsl_vector_max((gsl_vector const *)arg1); resultobj = SWIG_From_double((double)(result)); { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector *arg1 = (gsl_vector *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_min",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (double)gsl_vector_min((gsl_vector const *)arg1); resultobj = SWIG_From_double((double)(result)); { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector *arg1 = (gsl_vector *) 0 ; double *arg2 = (double *) 0 ; double *arg3 = (double *) 0 ; double temp2 ; int res2 = SWIG_TMPOBJ ; double temp3 ; int res3 = SWIG_TMPOBJ ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector _vector1; arg2 = &temp2; arg3 = &temp3; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_minmax",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){ goto fail; } } gsl_vector_minmax((gsl_vector const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); if (SWIG_IsTmpObj(res2)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg2))); } else { int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_double, new_flags)); } if (SWIG_IsTmpObj(res3)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg3))); } else { int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_double, new_flags)); } { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector *arg1 = (gsl_vector *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; size_t result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_max_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (size_t)gsl_vector_max_index((gsl_vector const *)arg1); resultobj = SWIG_From_size_t((size_t)(result)); { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector *arg1 = (gsl_vector *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; size_t result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_min_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (size_t)gsl_vector_min_index((gsl_vector const *)arg1); resultobj = SWIG_From_size_t((size_t)(result)); { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector *arg1 = (gsl_vector *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector _vector1; size_t _size_t_temp2; size_t _size_t_temp3; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_minmax_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){ goto fail; } } gsl_vector_minmax_index((gsl_vector const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector *arg1 = (gsl_vector *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_isnull",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_isnull((gsl_vector const *)arg1); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyVector1); _PyVector1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix *arg1 = (gsl_matrix *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_set_zero",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix, 1, &stride) !=GSL_SUCCESS) goto fail; } gsl_matrix_set_zero(arg1); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix *arg1 = (gsl_matrix *) 0 ; double arg2 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "x", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_set_all",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix, 1, &stride) !=GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_set_all" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); gsl_matrix_set_all(arg1,arg2); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_set_identity(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix *arg1 = (gsl_matrix *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_set_identity",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix, 1, &stride) !=GSL_SUCCESS) goto fail; } gsl_matrix_set_identity(arg1); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix *arg2 = (gsl_matrix *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_fread",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix, 2, &stride) !=GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_fread(arg1,arg2); { resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result); if (resultobj == NULL){ PyGSL_add_traceback(pygsl_module_for_error_treatment, "typemaps/gsl_error_typemap.i", __FUNCTION__, 48); goto fail; } } { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix *arg2 = (gsl_matrix *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_fwrite",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_INPUT_ARRAY, gsl_matrix, 2, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_fwrite(arg1,(gsl_matrix const *)arg2); { resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result); if (resultobj == NULL){ PyGSL_add_traceback(pygsl_module_for_error_treatment, "typemaps/gsl_error_typemap.i", __FUNCTION__, 48); goto fail; } } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix *arg2 = (gsl_matrix *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_fscanf",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix, 2, &stride) !=GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_fscanf(arg1,arg2); { resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result); if (resultobj == NULL){ PyGSL_add_traceback(pygsl_module_for_error_treatment, "typemaps/gsl_error_typemap.i", __FUNCTION__, 48); goto fail; } } { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix *arg2 = (gsl_matrix *) 0 ; char *arg3 = (char *) 0 ; int res3 ; char *buf3 = 0 ; int alloc3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN",(char *) "format", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_fprintf",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_INPUT_ARRAY, gsl_matrix, 2, &stride) != GSL_SUCCESS) goto fail; } res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "gsl_matrix_fprintf" "', argument " "3"" of type '" "char const *""'"); } arg3 = (char *)(buf3); result = (int)gsl_matrix_fprintf(arg1,(gsl_matrix const *)arg2,(char const *)arg3); { resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result); if (resultobj == NULL){ PyGSL_add_traceback(pygsl_module_for_error_treatment, "typemaps/gsl_error_typemap.i", __FUNCTION__, 48); goto fail; } } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix *arg1 = (gsl_matrix *) 0 ; gsl_matrix *arg2 = (gsl_matrix *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "INOUT", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix _matrix1; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_swap",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS) goto fail; } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_IO_ARRAY, gsl_matrix, 2, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_swap(arg1,arg2); { resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result); if (resultobj == NULL){ PyGSL_add_traceback(pygsl_module_for_error_treatment, "typemaps/gsl_error_typemap.i", __FUNCTION__, 48); goto fail; } } { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_swap_rows(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix *arg1 = (gsl_matrix *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_swap_rows",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_swap_rows" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_swap_rows" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_swap_rows(arg1,arg2,arg3); { resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result); if (resultobj == NULL){ PyGSL_add_traceback(pygsl_module_for_error_treatment, "typemaps/gsl_error_typemap.i", __FUNCTION__, 48); goto fail; } } { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_swap_columns(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix *arg1 = (gsl_matrix *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_swap_columns",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_swap_columns" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_swap_columns" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_swap_columns(arg1,arg2,arg3); { resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result); if (resultobj == NULL){ PyGSL_add_traceback(pygsl_module_for_error_treatment, "typemaps/gsl_error_typemap.i", __FUNCTION__, 48); goto fail; } } { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_swap_rowcol(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix *arg1 = (gsl_matrix *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_swap_rowcol",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_swap_rowcol" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_swap_rowcol" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_swap_rowcol(arg1,arg2,arg3); { resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result); if (resultobj == NULL){ PyGSL_add_traceback(pygsl_module_for_error_treatment, "typemaps/gsl_error_typemap.i", __FUNCTION__, 48); goto fail; } } { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_transpose(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix *arg1 = (gsl_matrix *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "INOUT", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_transpose",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_transpose(arg1); { resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result); if (resultobj == NULL){ PyGSL_add_traceback(pygsl_module_for_error_treatment, "typemaps/gsl_error_typemap.i", __FUNCTION__, 48); goto fail; } } { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix *arg1 = (gsl_matrix *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_max",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS) goto fail; } result = (double)gsl_matrix_max((gsl_matrix const *)arg1); resultobj = SWIG_From_double((double)(result)); { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix *arg1 = (gsl_matrix *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_min",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS) goto fail; } result = (double)gsl_matrix_min((gsl_matrix const *)arg1); resultobj = SWIG_From_double((double)(result)); { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix *arg1 = (gsl_matrix *) 0 ; double *arg2 = (double *) 0 ; double *arg3 = (double *) 0 ; double temp2 ; int res2 = SWIG_TMPOBJ ; double temp3 ; int res3 = SWIG_TMPOBJ ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix _matrix1; arg2 = &temp2; arg3 = &temp3; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_minmax",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_minmax((gsl_matrix const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); if (SWIG_IsTmpObj(res2)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg2))); } else { int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_double, new_flags)); } if (SWIG_IsTmpObj(res3)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg3))); } else { int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_double, new_flags)); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix *arg1 = (gsl_matrix *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix _matrix1; size_t _size_t_temp2; size_t _size_t_temp3; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_max_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_max_index((gsl_matrix const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix *arg1 = (gsl_matrix *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix _matrix1; size_t _size_t_temp2; size_t _size_t_temp3; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_min_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_min_index((gsl_matrix const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix *arg1 = (gsl_matrix *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; size_t *arg4 = (size_t *) 0 ; size_t *arg5 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix _matrix1; size_t _size_t_temp2; size_t _size_t_temp3; size_t _size_t_temp4; size_t _size_t_temp5; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } { _size_t_temp4 = 0; arg4 = &_size_t_temp4; } { _size_t_temp5 = 0; arg5 = &_size_t_temp5; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_minmax_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_minmax_index((gsl_matrix const *)arg1,arg2,arg3,arg4,arg5); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg4)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg5)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix *arg1 = (gsl_matrix *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_isnull",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_isnull((gsl_matrix const *)arg1); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_diagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix *arg1 = (gsl_matrix *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; gsl_vector_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_diagonal",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS) goto fail; } result = gsl_matrix_diagonal(arg1); { PyArrayObject * out = NULL; gsl_vector_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_subdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix *arg1 = (gsl_matrix *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN",(char *) "k", NULL }; gsl_vector_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_subdiagonal",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_subdiagonal" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = gsl_matrix_subdiagonal(arg1,arg2); { PyArrayObject * out = NULL; gsl_vector_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_superdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix *arg1 = (gsl_matrix *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN",(char *) "k", NULL }; gsl_vector_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_superdiagonal",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_superdiagonal" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = gsl_matrix_superdiagonal(arg1,arg2); { PyArrayObject * out = NULL; gsl_vector_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_float_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_float *arg1 = (gsl_vector_float *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_float _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_float_set_zero",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector_float, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } gsl_vector_float_set_zero(arg1); resultobj = SWIG_Py_Void(); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_float_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_float *arg1 = (gsl_vector_float *) 0 ; float arg2 ; float val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "IN", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_float _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_float_set_all",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector_float, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } ecode2 = SWIG_AsVal_float(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_vector_float_set_all" "', argument " "2"" of type '" "float""'"); } arg2 = (float)(val2); gsl_vector_float_set_all(arg1,arg2); resultobj = SWIG_Py_Void(); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_float_set_basis(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_float *arg1 = (gsl_vector_float *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "i", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_float _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_float_set_basis",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector_float, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_vector_float_set_basis" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = (int)gsl_vector_float_set_basis(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_float_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_float *arg2 = (gsl_vector_float *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_float _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_float_fread",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; int flag; _vector2.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2, PyGSL_OUTPUT_ARRAY, gsl_vector_float, 2, &stride); if (flag != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_float_fread(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_float_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_float *arg2 = (gsl_vector_float *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_float _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_float_fwrite",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_INPUT_ARRAY, gsl_vector_float, 2, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_float_fwrite(arg1,(gsl_vector_float const *)arg2); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_float_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_float *arg2 = (gsl_vector_float *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_float _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_float_fscanf",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; int flag; _vector2.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2, PyGSL_OUTPUT_ARRAY, gsl_vector_float, 2, &stride); if (flag != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_float_fscanf(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_float_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_float *arg2 = (gsl_vector_float *) 0 ; char *arg3 = (char *) 0 ; int res3 ; char *buf3 = 0 ; int alloc3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN",(char *) "format", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_float _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_vector_float_fprintf",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_INPUT_ARRAY, gsl_vector_float, 2, &stride) != GSL_SUCCESS){ goto fail; } } res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "gsl_vector_float_fprintf" "', argument " "3"" of type '" "char const *""'"); } arg3 = (char *)(buf3); result = (int)gsl_vector_float_fprintf(arg1,(gsl_vector_float const *)arg2,(char const *)arg3); resultobj = SWIG_From_int((int)(result)); if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return resultobj; fail: if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_float_reverse(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_float *arg1 = (gsl_vector_float *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "INOUT", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_float _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_float_reverse",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector_float, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_float_reverse(arg1); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_float_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_float *arg1 = (gsl_vector_float *) 0 ; gsl_vector_float *arg2 = (gsl_vector_float *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "INOUT", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_float _vector1; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_float _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_float_swap",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector_float, 1, &stride) != GSL_SUCCESS){ goto fail; } } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_IO_ARRAY, gsl_vector_float, 2, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_float_swap(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_float_swap_elements(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_float *arg1 = (gsl_vector_float *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_float _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_vector_float_swap_elements",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector_float, 1, &stride) != GSL_SUCCESS){ goto fail; } } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_vector_float_swap_elements" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_vector_float_swap_elements" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_vector_float_swap_elements(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_float_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_float *arg1 = (gsl_vector_float *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_float _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_float_max",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_float, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (double)gsl_vector_float_max((gsl_vector_float const *)arg1); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_float_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_float *arg1 = (gsl_vector_float *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_float _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_float_min",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_float, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (double)gsl_vector_float_min((gsl_vector_float const *)arg1); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_float_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_float *arg1 = (gsl_vector_float *) 0 ; float *arg2 = (float *) 0 ; float *arg3 = (float *) 0 ; float temp2 ; int res2 = SWIG_TMPOBJ ; float temp3 ; int res3 = SWIG_TMPOBJ ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_float _vector1; arg2 = &temp2; arg3 = &temp3; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_float_minmax",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_float, 1, &stride) != GSL_SUCCESS){ goto fail; } } gsl_vector_float_minmax((gsl_vector_float const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); if (SWIG_IsTmpObj(res2)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_float((*arg2))); } else { int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_float, new_flags)); } if (SWIG_IsTmpObj(res3)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_float((*arg3))); } else { int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_float, new_flags)); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_float_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_float *arg1 = (gsl_vector_float *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; size_t result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_float _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_float_max_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_float, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (size_t)gsl_vector_float_max_index((gsl_vector_float const *)arg1); resultobj = SWIG_From_size_t((size_t)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_float_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_float *arg1 = (gsl_vector_float *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; size_t result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_float _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_float_min_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_float, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (size_t)gsl_vector_float_min_index((gsl_vector_float const *)arg1); resultobj = SWIG_From_size_t((size_t)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_float_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_float *arg1 = (gsl_vector_float *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_float _vector1; size_t _size_t_temp2; size_t _size_t_temp3; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_float_minmax_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_float, 1, &stride) != GSL_SUCCESS){ goto fail; } } gsl_vector_float_minmax_index((gsl_vector_float const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_float_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_float *arg1 = (gsl_vector_float *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_float _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_float_isnull",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_float, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_float_isnull((gsl_vector_float const *)arg1); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_float_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_float_set_zero",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_float, 1, &stride) !=GSL_SUCCESS) goto fail; } gsl_matrix_float_set_zero(arg1); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_float_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ; float arg2 ; float val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_float_set_all",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_float, 1, &stride) !=GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_float(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_float_set_all" "', argument " "2"" of type '" "float""'"); } arg2 = (float)(val2); gsl_matrix_float_set_all(arg1,arg2); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_float_set_identity(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_float_set_identity",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_float, 1, &stride) !=GSL_SUCCESS) goto fail; } gsl_matrix_float_set_identity(arg1); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_float_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_float *arg2 = (gsl_matrix_float *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_float _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_float_fread",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_float, 2, &stride) !=GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_float_fread(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_float_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_float *arg2 = (gsl_matrix_float *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_float _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_float_fwrite",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_INPUT_ARRAY, gsl_matrix_float, 2, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_float_fwrite(arg1,(gsl_matrix_float const *)arg2); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_float_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_float *arg2 = (gsl_matrix_float *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_float _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_float_fscanf",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_float, 2, &stride) !=GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_float_fscanf(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_float_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_float *arg2 = (gsl_matrix_float *) 0 ; char *arg3 = (char *) 0 ; int res3 ; char *buf3 = 0 ; int alloc3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN",(char *) "format", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_float _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_float_fprintf",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_INPUT_ARRAY, gsl_matrix_float, 2, &stride) != GSL_SUCCESS) goto fail; } res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "gsl_matrix_float_fprintf" "', argument " "3"" of type '" "char const *""'"); } arg3 = (char *)(buf3); result = (int)gsl_matrix_float_fprintf(arg1,(gsl_matrix_float const *)arg2,(char const *)arg3); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_float_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ; gsl_matrix_float *arg2 = (gsl_matrix_float *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "INOUT", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_float _matrix1; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_float _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_float_swap",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS) goto fail; } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_IO_ARRAY, gsl_matrix_float, 2, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_float_swap(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_float_swap_rows(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_float_swap_rows",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_float_swap_rows" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_float_swap_rows" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_float_swap_rows(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_float_swap_columns(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_float_swap_columns",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_float_swap_columns" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_float_swap_columns" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_float_swap_columns(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_float_swap_rowcol(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_float_swap_rowcol",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_float_swap_rowcol" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_float_swap_rowcol" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_float_swap_rowcol(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_float_transpose(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "INOUT", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_float_transpose",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_float_transpose(arg1); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_float_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_float_max",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS) goto fail; } result = (double)gsl_matrix_float_max((gsl_matrix_float const *)arg1); resultobj = SWIG_From_double((double)(result)); { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_float_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_float_min",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS) goto fail; } result = (double)gsl_matrix_float_min((gsl_matrix_float const *)arg1); resultobj = SWIG_From_double((double)(result)); { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_float_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ; float *arg2 = (float *) 0 ; float *arg3 = (float *) 0 ; float temp2 ; int res2 = SWIG_TMPOBJ ; float temp3 ; int res3 = SWIG_TMPOBJ ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_float _matrix1; arg2 = &temp2; arg3 = &temp3; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_float_minmax",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_float_minmax((gsl_matrix_float const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); if (SWIG_IsTmpObj(res2)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_float((*arg2))); } else { int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_float, new_flags)); } if (SWIG_IsTmpObj(res3)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_float((*arg3))); } else { int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_float, new_flags)); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_float_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_float _matrix1; size_t _size_t_temp2; size_t _size_t_temp3; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_float_max_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_float_max_index((gsl_matrix_float const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_float_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_float _matrix1; size_t _size_t_temp2; size_t _size_t_temp3; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_float_min_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_float_min_index((gsl_matrix_float const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_float_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; size_t *arg4 = (size_t *) 0 ; size_t *arg5 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_float _matrix1; size_t _size_t_temp2; size_t _size_t_temp3; size_t _size_t_temp4; size_t _size_t_temp5; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } { _size_t_temp4 = 0; arg4 = &_size_t_temp4; } { _size_t_temp5 = 0; arg5 = &_size_t_temp5; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_float_minmax_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_float_minmax_index((gsl_matrix_float const *)arg1,arg2,arg3,arg4,arg5); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg4)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg5)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_float_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_float_isnull",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_float_isnull((gsl_matrix_float const *)arg1); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_float_diagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; gsl_vector_float_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_float_diagonal",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS) goto fail; } result = gsl_matrix_float_diagonal(arg1); { PyArrayObject * out = NULL; gsl_vector_float_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_float_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_float_subdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN",(char *) "k", NULL }; gsl_vector_float_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_float_subdiagonal",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_float_subdiagonal" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = gsl_matrix_float_subdiagonal(arg1,arg2); { PyArrayObject * out = NULL; gsl_vector_float_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_float_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_float_superdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN",(char *) "k", NULL }; gsl_vector_float_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_float_superdiagonal",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_float_superdiagonal" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = gsl_matrix_float_superdiagonal(arg1,arg2); { PyArrayObject * out = NULL; gsl_vector_float_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_float_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_long_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_long *arg1 = (gsl_vector_long *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_long _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_long_set_zero",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector_long, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } gsl_vector_long_set_zero(arg1); resultobj = SWIG_Py_Void(); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_long_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_long *arg1 = (gsl_vector_long *) 0 ; long arg2 ; long val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "IN", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_long _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_long_set_all",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector_long, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } ecode2 = SWIG_AsVal_long(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_vector_long_set_all" "', argument " "2"" of type '" "long""'"); } arg2 = (long)(val2); gsl_vector_long_set_all(arg1,arg2); resultobj = SWIG_Py_Void(); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_long_set_basis(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_long *arg1 = (gsl_vector_long *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "i", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_long _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_long_set_basis",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector_long, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_vector_long_set_basis" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = (int)gsl_vector_long_set_basis(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_long_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_long *arg2 = (gsl_vector_long *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_long _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_long_fread",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; int flag; _vector2.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2, PyGSL_OUTPUT_ARRAY, gsl_vector_long, 2, &stride); if (flag != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_long_fread(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_long_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_long *arg2 = (gsl_vector_long *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_long _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_long_fwrite",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_INPUT_ARRAY, gsl_vector_long, 2, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_long_fwrite(arg1,(gsl_vector_long const *)arg2); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_long_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_long *arg2 = (gsl_vector_long *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_long _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_long_fscanf",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; int flag; _vector2.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2, PyGSL_OUTPUT_ARRAY, gsl_vector_long, 2, &stride); if (flag != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_long_fscanf(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_long_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_long *arg2 = (gsl_vector_long *) 0 ; char *arg3 = (char *) 0 ; int res3 ; char *buf3 = 0 ; int alloc3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN",(char *) "format", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_long _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_vector_long_fprintf",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_INPUT_ARRAY, gsl_vector_long, 2, &stride) != GSL_SUCCESS){ goto fail; } } res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "gsl_vector_long_fprintf" "', argument " "3"" of type '" "char const *""'"); } arg3 = (char *)(buf3); result = (int)gsl_vector_long_fprintf(arg1,(gsl_vector_long const *)arg2,(char const *)arg3); resultobj = SWIG_From_int((int)(result)); if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return resultobj; fail: if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_long_reverse(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_long *arg1 = (gsl_vector_long *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "INOUT", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_long _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_long_reverse",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector_long, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_long_reverse(arg1); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_long_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_long *arg1 = (gsl_vector_long *) 0 ; gsl_vector_long *arg2 = (gsl_vector_long *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "INOUT", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_long _vector1; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_long _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_long_swap",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector_long, 1, &stride) != GSL_SUCCESS){ goto fail; } } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_IO_ARRAY, gsl_vector_long, 2, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_long_swap(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_long_swap_elements(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_long *arg1 = (gsl_vector_long *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_long _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_vector_long_swap_elements",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector_long, 1, &stride) != GSL_SUCCESS){ goto fail; } } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_vector_long_swap_elements" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_vector_long_swap_elements" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_vector_long_swap_elements(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_long_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_long *arg1 = (gsl_vector_long *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_long _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_long_max",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_long, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (double)gsl_vector_long_max((gsl_vector_long const *)arg1); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_long_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_long *arg1 = (gsl_vector_long *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_long _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_long_min",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_long, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (double)gsl_vector_long_min((gsl_vector_long const *)arg1); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_long_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_long *arg1 = (gsl_vector_long *) 0 ; long *arg2 = (long *) 0 ; long *arg3 = (long *) 0 ; long temp2 ; int res2 = SWIG_TMPOBJ ; long temp3 ; int res3 = SWIG_TMPOBJ ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_long _vector1; arg2 = &temp2; arg3 = &temp3; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_long_minmax",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_long, 1, &stride) != GSL_SUCCESS){ goto fail; } } gsl_vector_long_minmax((gsl_vector_long const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); if (SWIG_IsTmpObj(res2)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_long((*arg2))); } else { int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_long, new_flags)); } if (SWIG_IsTmpObj(res3)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_long((*arg3))); } else { int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_long, new_flags)); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_long_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_long *arg1 = (gsl_vector_long *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; size_t result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_long _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_long_max_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_long, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (size_t)gsl_vector_long_max_index((gsl_vector_long const *)arg1); resultobj = SWIG_From_size_t((size_t)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_long_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_long *arg1 = (gsl_vector_long *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; size_t result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_long _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_long_min_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_long, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (size_t)gsl_vector_long_min_index((gsl_vector_long const *)arg1); resultobj = SWIG_From_size_t((size_t)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_long_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_long *arg1 = (gsl_vector_long *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_long _vector1; size_t _size_t_temp2; size_t _size_t_temp3; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_long_minmax_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_long, 1, &stride) != GSL_SUCCESS){ goto fail; } } gsl_vector_long_minmax_index((gsl_vector_long const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_long_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_long *arg1 = (gsl_vector_long *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_long _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_long_isnull",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_long, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_long_isnull((gsl_vector_long const *)arg1); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_long_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_long _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_long_set_zero",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_long, 1, &stride) !=GSL_SUCCESS) goto fail; } gsl_matrix_long_set_zero(arg1); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_long_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ; long arg2 ; long val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_long _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_long_set_all",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_long, 1, &stride) !=GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_long(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_long_set_all" "', argument " "2"" of type '" "long""'"); } arg2 = (long)(val2); gsl_matrix_long_set_all(arg1,arg2); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_long_set_identity(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_long _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_long_set_identity",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_long, 1, &stride) !=GSL_SUCCESS) goto fail; } gsl_matrix_long_set_identity(arg1); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_long_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_long *arg2 = (gsl_matrix_long *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_long _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_long_fread",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_long, 2, &stride) !=GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_long_fread(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_long_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_long *arg2 = (gsl_matrix_long *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_long _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_long_fwrite",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_INPUT_ARRAY, gsl_matrix_long, 2, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_long_fwrite(arg1,(gsl_matrix_long const *)arg2); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_long_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_long *arg2 = (gsl_matrix_long *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_long _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_long_fscanf",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_long, 2, &stride) !=GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_long_fscanf(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_long_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_long *arg2 = (gsl_matrix_long *) 0 ; char *arg3 = (char *) 0 ; int res3 ; char *buf3 = 0 ; int alloc3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN",(char *) "format", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_long _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_long_fprintf",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_INPUT_ARRAY, gsl_matrix_long, 2, &stride) != GSL_SUCCESS) goto fail; } res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "gsl_matrix_long_fprintf" "', argument " "3"" of type '" "char const *""'"); } arg3 = (char *)(buf3); result = (int)gsl_matrix_long_fprintf(arg1,(gsl_matrix_long const *)arg2,(char const *)arg3); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_long_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ; gsl_matrix_long *arg2 = (gsl_matrix_long *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "INOUT", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_long _matrix1; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_long _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_long_swap",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS) goto fail; } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_IO_ARRAY, gsl_matrix_long, 2, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_long_swap(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_long_swap_rows(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_long _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_long_swap_rows",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_long_swap_rows" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_long_swap_rows" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_long_swap_rows(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_long_swap_columns(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_long _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_long_swap_columns",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_long_swap_columns" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_long_swap_columns" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_long_swap_columns(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_long_swap_rowcol(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_long _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_long_swap_rowcol",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_long_swap_rowcol" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_long_swap_rowcol" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_long_swap_rowcol(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_long_transpose(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "INOUT", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_long _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_long_transpose",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_long_transpose(arg1); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_long_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_long _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_long_max",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS) goto fail; } result = (double)gsl_matrix_long_max((gsl_matrix_long const *)arg1); resultobj = SWIG_From_double((double)(result)); { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_long_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_long _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_long_min",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS) goto fail; } result = (double)gsl_matrix_long_min((gsl_matrix_long const *)arg1); resultobj = SWIG_From_double((double)(result)); { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_long_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ; long *arg2 = (long *) 0 ; long *arg3 = (long *) 0 ; long temp2 ; int res2 = SWIG_TMPOBJ ; long temp3 ; int res3 = SWIG_TMPOBJ ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_long _matrix1; arg2 = &temp2; arg3 = &temp3; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_long_minmax",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_long_minmax((gsl_matrix_long const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); if (SWIG_IsTmpObj(res2)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_long((*arg2))); } else { int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_long, new_flags)); } if (SWIG_IsTmpObj(res3)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_long((*arg3))); } else { int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_long, new_flags)); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_long_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_long _matrix1; size_t _size_t_temp2; size_t _size_t_temp3; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_long_max_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_long_max_index((gsl_matrix_long const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_long_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_long _matrix1; size_t _size_t_temp2; size_t _size_t_temp3; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_long_min_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_long_min_index((gsl_matrix_long const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_long_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; size_t *arg4 = (size_t *) 0 ; size_t *arg5 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_long _matrix1; size_t _size_t_temp2; size_t _size_t_temp3; size_t _size_t_temp4; size_t _size_t_temp5; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } { _size_t_temp4 = 0; arg4 = &_size_t_temp4; } { _size_t_temp5 = 0; arg5 = &_size_t_temp5; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_long_minmax_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_long_minmax_index((gsl_matrix_long const *)arg1,arg2,arg3,arg4,arg5); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg4)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg5)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_long_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_long _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_long_isnull",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_long_isnull((gsl_matrix_long const *)arg1); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_long_diagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; gsl_vector_long_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_long _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_long_diagonal",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS) goto fail; } result = gsl_matrix_long_diagonal(arg1); { PyArrayObject * out = NULL; gsl_vector_long_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_long_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_long_subdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN",(char *) "k", NULL }; gsl_vector_long_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_long _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_long_subdiagonal",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_long_subdiagonal" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = gsl_matrix_long_subdiagonal(arg1,arg2); { PyArrayObject * out = NULL; gsl_vector_long_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_long_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_long_superdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN",(char *) "k", NULL }; gsl_vector_long_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_long _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_long_superdiagonal",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_long_superdiagonal" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = gsl_matrix_long_superdiagonal(arg1,arg2); { PyArrayObject * out = NULL; gsl_vector_long_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_long_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_int_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_int *arg1 = (gsl_vector_int *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_int _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_int_set_zero",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector_int, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } gsl_vector_int_set_zero(arg1); resultobj = SWIG_Py_Void(); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_int_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_int *arg1 = (gsl_vector_int *) 0 ; int arg2 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "IN", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_int _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_int_set_all",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector_int, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_vector_int_set_all" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); gsl_vector_int_set_all(arg1,arg2); resultobj = SWIG_Py_Void(); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_int_set_basis(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_int *arg1 = (gsl_vector_int *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "i", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_int _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_int_set_basis",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector_int, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_vector_int_set_basis" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = (int)gsl_vector_int_set_basis(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_int_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_int *arg2 = (gsl_vector_int *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_int _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_int_fread",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; int flag; _vector2.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2, PyGSL_OUTPUT_ARRAY, gsl_vector_int, 2, &stride); if (flag != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_int_fread(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_int_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_int *arg2 = (gsl_vector_int *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_int _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_int_fwrite",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_INPUT_ARRAY, gsl_vector_int, 2, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_int_fwrite(arg1,(gsl_vector_int const *)arg2); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_int_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_int *arg2 = (gsl_vector_int *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_int _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_int_fscanf",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; int flag; _vector2.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2, PyGSL_OUTPUT_ARRAY, gsl_vector_int, 2, &stride); if (flag != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_int_fscanf(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_int_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_int *arg2 = (gsl_vector_int *) 0 ; char *arg3 = (char *) 0 ; int res3 ; char *buf3 = 0 ; int alloc3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN",(char *) "format", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_int _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_vector_int_fprintf",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_INPUT_ARRAY, gsl_vector_int, 2, &stride) != GSL_SUCCESS){ goto fail; } } res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "gsl_vector_int_fprintf" "', argument " "3"" of type '" "char const *""'"); } arg3 = (char *)(buf3); result = (int)gsl_vector_int_fprintf(arg1,(gsl_vector_int const *)arg2,(char const *)arg3); resultobj = SWIG_From_int((int)(result)); if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return resultobj; fail: if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_int_reverse(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_int *arg1 = (gsl_vector_int *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "INOUT", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_int _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_int_reverse",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector_int, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_int_reverse(arg1); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_int_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_int *arg1 = (gsl_vector_int *) 0 ; gsl_vector_int *arg2 = (gsl_vector_int *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "INOUT", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_int _vector1; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_int _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_int_swap",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector_int, 1, &stride) != GSL_SUCCESS){ goto fail; } } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_IO_ARRAY, gsl_vector_int, 2, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_int_swap(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_int_swap_elements(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_int *arg1 = (gsl_vector_int *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_int _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_vector_int_swap_elements",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector_int, 1, &stride) != GSL_SUCCESS){ goto fail; } } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_vector_int_swap_elements" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_vector_int_swap_elements" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_vector_int_swap_elements(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_int_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_int *arg1 = (gsl_vector_int *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_int _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_int_max",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_int, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (double)gsl_vector_int_max((gsl_vector_int const *)arg1); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_int_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_int *arg1 = (gsl_vector_int *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_int _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_int_min",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_int, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (double)gsl_vector_int_min((gsl_vector_int const *)arg1); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_int_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_int *arg1 = (gsl_vector_int *) 0 ; int *arg2 = (int *) 0 ; int *arg3 = (int *) 0 ; int temp2 ; int res2 = SWIG_TMPOBJ ; int temp3 ; int res3 = SWIG_TMPOBJ ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_int _vector1; arg2 = &temp2; arg3 = &temp3; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_int_minmax",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_int, 1, &stride) != GSL_SUCCESS){ goto fail; } } gsl_vector_int_minmax((gsl_vector_int const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); if (SWIG_IsTmpObj(res2)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_int((*arg2))); } else { int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_int, new_flags)); } if (SWIG_IsTmpObj(res3)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_int((*arg3))); } else { int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_int, new_flags)); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_int_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_int *arg1 = (gsl_vector_int *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; size_t result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_int _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_int_max_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_int, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (size_t)gsl_vector_int_max_index((gsl_vector_int const *)arg1); resultobj = SWIG_From_size_t((size_t)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_int_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_int *arg1 = (gsl_vector_int *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; size_t result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_int _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_int_min_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_int, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (size_t)gsl_vector_int_min_index((gsl_vector_int const *)arg1); resultobj = SWIG_From_size_t((size_t)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_int_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_int *arg1 = (gsl_vector_int *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_int _vector1; size_t _size_t_temp2; size_t _size_t_temp3; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_int_minmax_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_int, 1, &stride) != GSL_SUCCESS){ goto fail; } } gsl_vector_int_minmax_index((gsl_vector_int const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_int_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_int *arg1 = (gsl_vector_int *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_int _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_int_isnull",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_int, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_int_isnull((gsl_vector_int const *)arg1); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_int_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_int _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_int_set_zero",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_int, 1, &stride) !=GSL_SUCCESS) goto fail; } gsl_matrix_int_set_zero(arg1); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_int_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ; int arg2 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_int _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_int_set_all",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_int, 1, &stride) !=GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_int_set_all" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); gsl_matrix_int_set_all(arg1,arg2); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_int_set_identity(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_int _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_int_set_identity",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_int, 1, &stride) !=GSL_SUCCESS) goto fail; } gsl_matrix_int_set_identity(arg1); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_int_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_int *arg2 = (gsl_matrix_int *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_int _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_int_fread",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_int, 2, &stride) !=GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_int_fread(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_int_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_int *arg2 = (gsl_matrix_int *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_int _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_int_fwrite",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_INPUT_ARRAY, gsl_matrix_int, 2, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_int_fwrite(arg1,(gsl_matrix_int const *)arg2); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_int_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_int *arg2 = (gsl_matrix_int *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_int _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_int_fscanf",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_int, 2, &stride) !=GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_int_fscanf(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_int_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_int *arg2 = (gsl_matrix_int *) 0 ; char *arg3 = (char *) 0 ; int res3 ; char *buf3 = 0 ; int alloc3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN",(char *) "format", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_int _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_int_fprintf",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_INPUT_ARRAY, gsl_matrix_int, 2, &stride) != GSL_SUCCESS) goto fail; } res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "gsl_matrix_int_fprintf" "', argument " "3"" of type '" "char const *""'"); } arg3 = (char *)(buf3); result = (int)gsl_matrix_int_fprintf(arg1,(gsl_matrix_int const *)arg2,(char const *)arg3); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_int_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ; gsl_matrix_int *arg2 = (gsl_matrix_int *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "INOUT", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_int _matrix1; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_int _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_int_swap",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS) goto fail; } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_IO_ARRAY, gsl_matrix_int, 2, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_int_swap(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_int_swap_rows(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_int _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_int_swap_rows",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_int_swap_rows" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_int_swap_rows" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_int_swap_rows(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_int_swap_columns(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_int _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_int_swap_columns",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_int_swap_columns" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_int_swap_columns" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_int_swap_columns(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_int_swap_rowcol(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_int _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_int_swap_rowcol",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_int_swap_rowcol" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_int_swap_rowcol" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_int_swap_rowcol(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_int_transpose(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "INOUT", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_int _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_int_transpose",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_int_transpose(arg1); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_int_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_int _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_int_max",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS) goto fail; } result = (double)gsl_matrix_int_max((gsl_matrix_int const *)arg1); resultobj = SWIG_From_double((double)(result)); { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_int_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_int _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_int_min",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS) goto fail; } result = (double)gsl_matrix_int_min((gsl_matrix_int const *)arg1); resultobj = SWIG_From_double((double)(result)); { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_int_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ; int *arg2 = (int *) 0 ; int *arg3 = (int *) 0 ; int temp2 ; int res2 = SWIG_TMPOBJ ; int temp3 ; int res3 = SWIG_TMPOBJ ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_int _matrix1; arg2 = &temp2; arg3 = &temp3; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_int_minmax",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_int_minmax((gsl_matrix_int const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); if (SWIG_IsTmpObj(res2)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_int((*arg2))); } else { int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_int, new_flags)); } if (SWIG_IsTmpObj(res3)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_int((*arg3))); } else { int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_int, new_flags)); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_int_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_int _matrix1; size_t _size_t_temp2; size_t _size_t_temp3; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_int_max_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_int_max_index((gsl_matrix_int const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_int_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_int _matrix1; size_t _size_t_temp2; size_t _size_t_temp3; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_int_min_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_int_min_index((gsl_matrix_int const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_int_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; size_t *arg4 = (size_t *) 0 ; size_t *arg5 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_int _matrix1; size_t _size_t_temp2; size_t _size_t_temp3; size_t _size_t_temp4; size_t _size_t_temp5; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } { _size_t_temp4 = 0; arg4 = &_size_t_temp4; } { _size_t_temp5 = 0; arg5 = &_size_t_temp5; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_int_minmax_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_int_minmax_index((gsl_matrix_int const *)arg1,arg2,arg3,arg4,arg5); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg4)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg5)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_int_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_int _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_int_isnull",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_int_isnull((gsl_matrix_int const *)arg1); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_int_diagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; gsl_vector_int_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_int _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_int_diagonal",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS) goto fail; } result = gsl_matrix_int_diagonal(arg1); { PyArrayObject * out = NULL; gsl_vector_int_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_int_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_int_subdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN",(char *) "k", NULL }; gsl_vector_int_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_int _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_int_subdiagonal",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_int_subdiagonal" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = gsl_matrix_int_subdiagonal(arg1,arg2); { PyArrayObject * out = NULL; gsl_vector_int_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_int_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_int_superdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN",(char *) "k", NULL }; gsl_vector_int_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_int _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_int_superdiagonal",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_int_superdiagonal" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = gsl_matrix_int_superdiagonal(arg1,arg2); { PyArrayObject * out = NULL; gsl_vector_int_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_int_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_short_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_short *arg1 = (gsl_vector_short *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_short _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_short_set_zero",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector_short, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } gsl_vector_short_set_zero(arg1); resultobj = SWIG_Py_Void(); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_short_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_short *arg1 = (gsl_vector_short *) 0 ; short arg2 ; short val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "IN", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_short _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_short_set_all",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector_short, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } ecode2 = SWIG_AsVal_short(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_vector_short_set_all" "', argument " "2"" of type '" "short""'"); } arg2 = (short)(val2); gsl_vector_short_set_all(arg1,arg2); resultobj = SWIG_Py_Void(); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_short_set_basis(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_short *arg1 = (gsl_vector_short *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "i", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_short _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_short_set_basis",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector_short, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_vector_short_set_basis" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = (int)gsl_vector_short_set_basis(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_short_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_short *arg2 = (gsl_vector_short *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_short _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_short_fread",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; int flag; _vector2.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2, PyGSL_OUTPUT_ARRAY, gsl_vector_short, 2, &stride); if (flag != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_short_fread(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_short_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_short *arg2 = (gsl_vector_short *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_short _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_short_fwrite",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_INPUT_ARRAY, gsl_vector_short, 2, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_short_fwrite(arg1,(gsl_vector_short const *)arg2); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_short_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_short *arg2 = (gsl_vector_short *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_short _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_short_fscanf",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; int flag; _vector2.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2, PyGSL_OUTPUT_ARRAY, gsl_vector_short, 2, &stride); if (flag != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_short_fscanf(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_short_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_short *arg2 = (gsl_vector_short *) 0 ; char *arg3 = (char *) 0 ; int res3 ; char *buf3 = 0 ; int alloc3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN",(char *) "format", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_short _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_vector_short_fprintf",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_INPUT_ARRAY, gsl_vector_short, 2, &stride) != GSL_SUCCESS){ goto fail; } } res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "gsl_vector_short_fprintf" "', argument " "3"" of type '" "char const *""'"); } arg3 = (char *)(buf3); result = (int)gsl_vector_short_fprintf(arg1,(gsl_vector_short const *)arg2,(char const *)arg3); resultobj = SWIG_From_int((int)(result)); if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return resultobj; fail: if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_short_reverse(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_short *arg1 = (gsl_vector_short *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "INOUT", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_short _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_short_reverse",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector_short, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_short_reverse(arg1); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_short_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_short *arg1 = (gsl_vector_short *) 0 ; gsl_vector_short *arg2 = (gsl_vector_short *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "INOUT", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_short _vector1; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_short _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_short_swap",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector_short, 1, &stride) != GSL_SUCCESS){ goto fail; } } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_IO_ARRAY, gsl_vector_short, 2, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_short_swap(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_short_swap_elements(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_short *arg1 = (gsl_vector_short *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_short _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_vector_short_swap_elements",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector_short, 1, &stride) != GSL_SUCCESS){ goto fail; } } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_vector_short_swap_elements" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_vector_short_swap_elements" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_vector_short_swap_elements(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_short_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_short *arg1 = (gsl_vector_short *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_short _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_short_max",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_short, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (double)gsl_vector_short_max((gsl_vector_short const *)arg1); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_short_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_short *arg1 = (gsl_vector_short *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_short _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_short_min",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_short, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (double)gsl_vector_short_min((gsl_vector_short const *)arg1); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_short_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_short *arg1 = (gsl_vector_short *) 0 ; short *arg2 = (short *) 0 ; short *arg3 = (short *) 0 ; short temp2 ; int res2 = SWIG_TMPOBJ ; short temp3 ; int res3 = SWIG_TMPOBJ ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_short _vector1; arg2 = &temp2; arg3 = &temp3; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_short_minmax",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_short, 1, &stride) != GSL_SUCCESS){ goto fail; } } gsl_vector_short_minmax((gsl_vector_short const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); if (SWIG_IsTmpObj(res2)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_short((*arg2))); } else { int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_short, new_flags)); } if (SWIG_IsTmpObj(res3)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_short((*arg3))); } else { int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_short, new_flags)); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_short_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_short *arg1 = (gsl_vector_short *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; size_t result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_short _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_short_max_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_short, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (size_t)gsl_vector_short_max_index((gsl_vector_short const *)arg1); resultobj = SWIG_From_size_t((size_t)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_short_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_short *arg1 = (gsl_vector_short *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; size_t result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_short _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_short_min_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_short, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (size_t)gsl_vector_short_min_index((gsl_vector_short const *)arg1); resultobj = SWIG_From_size_t((size_t)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_short_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_short *arg1 = (gsl_vector_short *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_short _vector1; size_t _size_t_temp2; size_t _size_t_temp3; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_short_minmax_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_short, 1, &stride) != GSL_SUCCESS){ goto fail; } } gsl_vector_short_minmax_index((gsl_vector_short const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_short_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_short *arg1 = (gsl_vector_short *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_short _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_short_isnull",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_short, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_short_isnull((gsl_vector_short const *)arg1); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_short_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_short _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_short_set_zero",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_short, 1, &stride) !=GSL_SUCCESS) goto fail; } gsl_matrix_short_set_zero(arg1); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_short_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ; short arg2 ; short val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_short _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_short_set_all",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_short, 1, &stride) !=GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_short(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_short_set_all" "', argument " "2"" of type '" "short""'"); } arg2 = (short)(val2); gsl_matrix_short_set_all(arg1,arg2); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_short_set_identity(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_short _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_short_set_identity",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_short, 1, &stride) !=GSL_SUCCESS) goto fail; } gsl_matrix_short_set_identity(arg1); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_short_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_short *arg2 = (gsl_matrix_short *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_short _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_short_fread",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_short, 2, &stride) !=GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_short_fread(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_short_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_short *arg2 = (gsl_matrix_short *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_short _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_short_fwrite",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_INPUT_ARRAY, gsl_matrix_short, 2, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_short_fwrite(arg1,(gsl_matrix_short const *)arg2); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_short_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_short *arg2 = (gsl_matrix_short *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_short _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_short_fscanf",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_short, 2, &stride) !=GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_short_fscanf(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_short_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_short *arg2 = (gsl_matrix_short *) 0 ; char *arg3 = (char *) 0 ; int res3 ; char *buf3 = 0 ; int alloc3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN",(char *) "format", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_short _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_short_fprintf",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_INPUT_ARRAY, gsl_matrix_short, 2, &stride) != GSL_SUCCESS) goto fail; } res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "gsl_matrix_short_fprintf" "', argument " "3"" of type '" "char const *""'"); } arg3 = (char *)(buf3); result = (int)gsl_matrix_short_fprintf(arg1,(gsl_matrix_short const *)arg2,(char const *)arg3); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_short_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ; gsl_matrix_short *arg2 = (gsl_matrix_short *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "INOUT", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_short _matrix1; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_short _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_short_swap",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS) goto fail; } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_IO_ARRAY, gsl_matrix_short, 2, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_short_swap(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_short_swap_rows(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_short _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_short_swap_rows",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_short_swap_rows" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_short_swap_rows" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_short_swap_rows(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_short_swap_columns(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_short _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_short_swap_columns",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_short_swap_columns" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_short_swap_columns" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_short_swap_columns(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_short_swap_rowcol(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_short _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_short_swap_rowcol",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_short_swap_rowcol" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_short_swap_rowcol" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_short_swap_rowcol(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_short_transpose(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "INOUT", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_short _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_short_transpose",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_short_transpose(arg1); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_short_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_short _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_short_max",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS) goto fail; } result = (double)gsl_matrix_short_max((gsl_matrix_short const *)arg1); resultobj = SWIG_From_double((double)(result)); { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_short_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_short _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_short_min",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS) goto fail; } result = (double)gsl_matrix_short_min((gsl_matrix_short const *)arg1); resultobj = SWIG_From_double((double)(result)); { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_short_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ; short *arg2 = (short *) 0 ; short *arg3 = (short *) 0 ; short temp2 ; int res2 = SWIG_TMPOBJ ; short temp3 ; int res3 = SWIG_TMPOBJ ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_short _matrix1; arg2 = &temp2; arg3 = &temp3; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_short_minmax",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_short_minmax((gsl_matrix_short const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); if (SWIG_IsTmpObj(res2)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_short((*arg2))); } else { int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_short, new_flags)); } if (SWIG_IsTmpObj(res3)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_short((*arg3))); } else { int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_short, new_flags)); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_short_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_short _matrix1; size_t _size_t_temp2; size_t _size_t_temp3; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_short_max_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_short_max_index((gsl_matrix_short const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_short_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_short _matrix1; size_t _size_t_temp2; size_t _size_t_temp3; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_short_min_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_short_min_index((gsl_matrix_short const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_short_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; size_t *arg4 = (size_t *) 0 ; size_t *arg5 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_short _matrix1; size_t _size_t_temp2; size_t _size_t_temp3; size_t _size_t_temp4; size_t _size_t_temp5; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } { _size_t_temp4 = 0; arg4 = &_size_t_temp4; } { _size_t_temp5 = 0; arg5 = &_size_t_temp5; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_short_minmax_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_short_minmax_index((gsl_matrix_short const *)arg1,arg2,arg3,arg4,arg5); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg4)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg5)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_short_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_short _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_short_isnull",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_short_isnull((gsl_matrix_short const *)arg1); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_short_diagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; gsl_vector_short_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_short _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_short_diagonal",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS) goto fail; } result = gsl_matrix_short_diagonal(arg1); { PyArrayObject * out = NULL; gsl_vector_short_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_short_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_short_subdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN",(char *) "k", NULL }; gsl_vector_short_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_short _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_short_subdiagonal",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_short_subdiagonal" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = gsl_matrix_short_subdiagonal(arg1,arg2); { PyArrayObject * out = NULL; gsl_vector_short_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_short_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_short_superdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN",(char *) "k", NULL }; gsl_vector_short_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_short _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_short_superdiagonal",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_short_superdiagonal" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = gsl_matrix_short_superdiagonal(arg1,arg2); { PyArrayObject * out = NULL; gsl_vector_short_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_short_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_char_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_char *arg1 = (gsl_vector_char *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_char _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_char_set_zero",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector_char, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } gsl_vector_char_set_zero(arg1); resultobj = SWIG_Py_Void(); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_char_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_char *arg1 = (gsl_vector_char *) 0 ; char arg2 ; char val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "IN", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_char _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_char_set_all",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector_char, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } ecode2 = SWIG_AsVal_char(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_vector_char_set_all" "', argument " "2"" of type '" "char""'"); } arg2 = (char)(val2); gsl_vector_char_set_all(arg1,arg2); resultobj = SWIG_Py_Void(); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_char_set_basis(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_char *arg1 = (gsl_vector_char *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "i", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_char _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_char_set_basis",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector_char, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_vector_char_set_basis" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = (int)gsl_vector_char_set_basis(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_char_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_char *arg2 = (gsl_vector_char *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_char _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_char_fread",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; int flag; _vector2.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2, PyGSL_OUTPUT_ARRAY, gsl_vector_char, 2, &stride); if (flag != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_char_fread(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_char_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_char *arg2 = (gsl_vector_char *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_char _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_char_fwrite",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_INPUT_ARRAY, gsl_vector_char, 2, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_char_fwrite(arg1,(gsl_vector_char const *)arg2); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_char_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_char *arg2 = (gsl_vector_char *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_char _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_char_fscanf",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; int flag; _vector2.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2, PyGSL_OUTPUT_ARRAY, gsl_vector_char, 2, &stride); if (flag != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_char_fscanf(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_char_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_char *arg2 = (gsl_vector_char *) 0 ; char *arg3 = (char *) 0 ; int res3 ; char *buf3 = 0 ; int alloc3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN",(char *) "format", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_char _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_vector_char_fprintf",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_INPUT_ARRAY, gsl_vector_char, 2, &stride) != GSL_SUCCESS){ goto fail; } } res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "gsl_vector_char_fprintf" "', argument " "3"" of type '" "char const *""'"); } arg3 = (char *)(buf3); result = (int)gsl_vector_char_fprintf(arg1,(gsl_vector_char const *)arg2,(char const *)arg3); resultobj = SWIG_From_int((int)(result)); if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return resultobj; fail: if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_char_reverse(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_char *arg1 = (gsl_vector_char *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "INOUT", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_char _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_char_reverse",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector_char, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_char_reverse(arg1); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_char_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_char *arg1 = (gsl_vector_char *) 0 ; gsl_vector_char *arg2 = (gsl_vector_char *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "INOUT", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_char _vector1; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_char _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_char_swap",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector_char, 1, &stride) != GSL_SUCCESS){ goto fail; } } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_IO_ARRAY, gsl_vector_char, 2, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_char_swap(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_char_swap_elements(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_char *arg1 = (gsl_vector_char *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_char _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_vector_char_swap_elements",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector_char, 1, &stride) != GSL_SUCCESS){ goto fail; } } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_vector_char_swap_elements" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_vector_char_swap_elements" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_vector_char_swap_elements(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_char_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_char *arg1 = (gsl_vector_char *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_char _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_char_max",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_char, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (double)gsl_vector_char_max((gsl_vector_char const *)arg1); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_char_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_char *arg1 = (gsl_vector_char *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_char _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_char_min",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_char, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (double)gsl_vector_char_min((gsl_vector_char const *)arg1); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_char_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_char *arg1 = (gsl_vector_char *) 0 ; char *arg2 = (char *) 0 ; char *arg3 = (char *) 0 ; char temp2 ; int res2 = SWIG_TMPOBJ ; char temp3 ; int res3 = SWIG_TMPOBJ ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_char _vector1; arg2 = &temp2; arg3 = &temp3; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_char_minmax",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_char, 1, &stride) != GSL_SUCCESS){ goto fail; } } gsl_vector_char_minmax((gsl_vector_char const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); if (SWIG_IsTmpObj(res2)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_char((*arg2))); } else { int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_char, new_flags)); } if (SWIG_IsTmpObj(res3)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_char((*arg3))); } else { int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_char, new_flags)); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_char_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_char *arg1 = (gsl_vector_char *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; size_t result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_char _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_char_max_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_char, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (size_t)gsl_vector_char_max_index((gsl_vector_char const *)arg1); resultobj = SWIG_From_size_t((size_t)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_char_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_char *arg1 = (gsl_vector_char *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; size_t result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_char _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_char_min_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_char, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (size_t)gsl_vector_char_min_index((gsl_vector_char const *)arg1); resultobj = SWIG_From_size_t((size_t)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_char_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_char *arg1 = (gsl_vector_char *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_char _vector1; size_t _size_t_temp2; size_t _size_t_temp3; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_char_minmax_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_char, 1, &stride) != GSL_SUCCESS){ goto fail; } } gsl_vector_char_minmax_index((gsl_vector_char const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_char_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_char *arg1 = (gsl_vector_char *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_char _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_char_isnull",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_char, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_char_isnull((gsl_vector_char const *)arg1); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_char_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_char _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_char_set_zero",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_char, 1, &stride) !=GSL_SUCCESS) goto fail; } gsl_matrix_char_set_zero(arg1); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_char_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ; char arg2 ; char val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_char _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_char_set_all",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_char, 1, &stride) !=GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_char(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_char_set_all" "', argument " "2"" of type '" "char""'"); } arg2 = (char)(val2); gsl_matrix_char_set_all(arg1,arg2); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_char_set_identity(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_char _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_char_set_identity",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_char, 1, &stride) !=GSL_SUCCESS) goto fail; } gsl_matrix_char_set_identity(arg1); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_char_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_char *arg2 = (gsl_matrix_char *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_char _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_char_fread",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_char, 2, &stride) !=GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_char_fread(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_char_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_char *arg2 = (gsl_matrix_char *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_char _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_char_fwrite",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_INPUT_ARRAY, gsl_matrix_char, 2, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_char_fwrite(arg1,(gsl_matrix_char const *)arg2); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_char_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_char *arg2 = (gsl_matrix_char *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_char _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_char_fscanf",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_char, 2, &stride) !=GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_char_fscanf(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_char_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_char *arg2 = (gsl_matrix_char *) 0 ; char *arg3 = (char *) 0 ; int res3 ; char *buf3 = 0 ; int alloc3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN",(char *) "format", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_char _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_char_fprintf",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_INPUT_ARRAY, gsl_matrix_char, 2, &stride) != GSL_SUCCESS) goto fail; } res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "gsl_matrix_char_fprintf" "', argument " "3"" of type '" "char const *""'"); } arg3 = (char *)(buf3); result = (int)gsl_matrix_char_fprintf(arg1,(gsl_matrix_char const *)arg2,(char const *)arg3); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_char_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ; gsl_matrix_char *arg2 = (gsl_matrix_char *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "INOUT", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_char _matrix1; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_char _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_char_swap",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS) goto fail; } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_IO_ARRAY, gsl_matrix_char, 2, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_char_swap(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_char_swap_rows(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_char _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_char_swap_rows",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_char_swap_rows" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_char_swap_rows" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_char_swap_rows(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_char_swap_columns(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_char _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_char_swap_columns",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_char_swap_columns" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_char_swap_columns" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_char_swap_columns(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_char_swap_rowcol(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_char _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_char_swap_rowcol",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_char_swap_rowcol" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_char_swap_rowcol" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_char_swap_rowcol(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_char_transpose(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "INOUT", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_char _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_char_transpose",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_char_transpose(arg1); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_char_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_char _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_char_max",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS) goto fail; } result = (double)gsl_matrix_char_max((gsl_matrix_char const *)arg1); resultobj = SWIG_From_double((double)(result)); { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_char_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; double result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_char _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_char_min",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS) goto fail; } result = (double)gsl_matrix_char_min((gsl_matrix_char const *)arg1); resultobj = SWIG_From_double((double)(result)); { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_char_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ; char *arg2 = (char *) 0 ; char *arg3 = (char *) 0 ; char temp2 ; int res2 = SWIG_TMPOBJ ; char temp3 ; int res3 = SWIG_TMPOBJ ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_char _matrix1; arg2 = &temp2; arg3 = &temp3; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_char_minmax",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_char_minmax((gsl_matrix_char const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); if (SWIG_IsTmpObj(res2)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_char((*arg2))); } else { int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_char, new_flags)); } if (SWIG_IsTmpObj(res3)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_char((*arg3))); } else { int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_char, new_flags)); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_char_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_char _matrix1; size_t _size_t_temp2; size_t _size_t_temp3; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_char_max_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_char_max_index((gsl_matrix_char const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_char_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_char _matrix1; size_t _size_t_temp2; size_t _size_t_temp3; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_char_min_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_char_min_index((gsl_matrix_char const *)arg1,arg2,arg3); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_char_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ; size_t *arg2 = (size_t *) 0 ; size_t *arg3 = (size_t *) 0 ; size_t *arg4 = (size_t *) 0 ; size_t *arg5 = (size_t *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_char _matrix1; size_t _size_t_temp2; size_t _size_t_temp3; size_t _size_t_temp4; size_t _size_t_temp5; { _size_t_temp2 = 0; arg2 = &_size_t_temp2; } { _size_t_temp3 = 0; arg3 = &_size_t_temp3; } { _size_t_temp4 = 0; arg4 = &_size_t_temp4; } { _size_t_temp5 = 0; arg5 = &_size_t_temp5; } if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_char_minmax_index",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS) goto fail; } gsl_matrix_char_minmax_index((gsl_matrix_char const *)arg1,arg2,arg3,arg4,arg5); resultobj = SWIG_Py_Void(); { PyObject *o; o = PyInt_FromLong((long) (*arg2)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg3)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg4)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { PyObject *o; o = PyInt_FromLong((long) (*arg5)); resultobj = SWIG_Python_AppendOutput(resultobj, o); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_char_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_char _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_char_isnull",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_char_isnull((gsl_matrix_char const *)arg1); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_char_diagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; gsl_vector_char_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_char _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_char_diagonal",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS) goto fail; } result = gsl_matrix_char_diagonal(arg1); { PyArrayObject * out = NULL; gsl_vector_char_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_char_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_char_subdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN",(char *) "k", NULL }; gsl_vector_char_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_char _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_char_subdiagonal",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_char_subdiagonal" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = gsl_matrix_char_subdiagonal(arg1,arg2); { PyArrayObject * out = NULL; gsl_vector_char_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_char_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_char_superdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN",(char *) "k", NULL }; gsl_vector_char_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_char _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_char_superdiagonal",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_char_superdiagonal" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = gsl_matrix_char_superdiagonal(arg1,arg2); { PyArrayObject * out = NULL; gsl_vector_char_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_char_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_complex_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_complex *arg1 = (gsl_vector_complex *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_complex _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_complex_set_zero",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector_complex, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } gsl_vector_complex_set_zero(arg1); resultobj = SWIG_Py_Void(); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_complex_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_complex *arg1 = (gsl_vector_complex *) 0 ; gsl_complex arg2 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "IN", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_complex _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_complex_set_all",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector_complex, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } { gsl_complex tmp; if(PyGSL_PyCOMPLEX_TO_gsl_complex(obj1, &tmp) != GSL_SUCCESS) goto fail; arg2 = tmp; } gsl_vector_complex_set_all(arg1,arg2); resultobj = SWIG_Py_Void(); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_complex_set_basis(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_complex *arg1 = (gsl_vector_complex *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "i", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_complex _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_complex_set_basis",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector_complex, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_vector_complex_set_basis" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = (int)gsl_vector_complex_set_basis(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_complex_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_complex *arg2 = (gsl_vector_complex *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_complex _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_complex_fread",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; int flag; _vector2.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2, PyGSL_OUTPUT_ARRAY, gsl_vector_complex, 2, &stride); if (flag != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_complex_fread(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_complex_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_complex *arg2 = (gsl_vector_complex *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_complex _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_complex_fwrite",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_INPUT_ARRAY, gsl_vector_complex, 2, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_complex_fwrite(arg1,(gsl_vector_complex const *)arg2); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_complex_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_complex *arg2 = (gsl_vector_complex *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_complex _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_complex_fscanf",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; int flag; _vector2.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2, PyGSL_OUTPUT_ARRAY, gsl_vector_complex, 2, &stride); if (flag != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_complex_fscanf(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_complex_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_complex *arg2 = (gsl_vector_complex *) 0 ; char *arg3 = (char *) 0 ; int res3 ; char *buf3 = 0 ; int alloc3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN",(char *) "format", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_complex _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_vector_complex_fprintf",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_INPUT_ARRAY, gsl_vector_complex, 2, &stride) != GSL_SUCCESS){ goto fail; } } res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "gsl_vector_complex_fprintf" "', argument " "3"" of type '" "char const *""'"); } arg3 = (char *)(buf3); result = (int)gsl_vector_complex_fprintf(arg1,(gsl_vector_complex const *)arg2,(char const *)arg3); resultobj = SWIG_From_int((int)(result)); if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return resultobj; fail: if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_complex_reverse(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_complex *arg1 = (gsl_vector_complex *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "INOUT", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_complex _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_complex_reverse",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector_complex, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_complex_reverse(arg1); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_complex_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_complex *arg1 = (gsl_vector_complex *) 0 ; gsl_vector_complex *arg2 = (gsl_vector_complex *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "INOUT", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_complex _vector1; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_complex _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_complex_swap",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector_complex, 1, &stride) != GSL_SUCCESS){ goto fail; } } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_IO_ARRAY, gsl_vector_complex, 2, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_complex_swap(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_complex_swap_elements(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_complex *arg1 = (gsl_vector_complex *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_complex _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_vector_complex_swap_elements",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector_complex, 1, &stride) != GSL_SUCCESS){ goto fail; } } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_vector_complex_swap_elements" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_vector_complex_swap_elements" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_vector_complex_swap_elements(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_complex_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_complex *arg1 = (gsl_vector_complex *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_complex _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_complex_isnull",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_complex, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_complex_isnull((gsl_vector_complex const *)arg1); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_complex_set_zero",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_complex, 1, &stride) !=GSL_SUCCESS) goto fail; } gsl_matrix_complex_set_zero(arg1); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ; gsl_complex arg2 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_complex_set_all",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_complex, 1, &stride) !=GSL_SUCCESS) goto fail; } { gsl_complex tmp; if(PyGSL_PyCOMPLEX_TO_gsl_complex(obj1, &tmp) != GSL_SUCCESS) goto fail; arg2 = tmp; } gsl_matrix_complex_set_all(arg1,arg2); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_set_identity(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_complex_set_identity",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_complex, 1, &stride) !=GSL_SUCCESS) goto fail; } gsl_matrix_complex_set_identity(arg1); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_complex *arg2 = (gsl_matrix_complex *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_complex _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_complex_fread",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_complex, 2, &stride) !=GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_complex_fread(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_complex *arg2 = (gsl_matrix_complex *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_complex _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_complex_fwrite",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_INPUT_ARRAY, gsl_matrix_complex, 2, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_complex_fwrite(arg1,(gsl_matrix_complex const *)arg2); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_complex *arg2 = (gsl_matrix_complex *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_complex _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_complex_fscanf",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_complex, 2, &stride) !=GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_complex_fscanf(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_complex *arg2 = (gsl_matrix_complex *) 0 ; char *arg3 = (char *) 0 ; int res3 ; char *buf3 = 0 ; int alloc3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN",(char *) "format", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_complex _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_complex_fprintf",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_INPUT_ARRAY, gsl_matrix_complex, 2, &stride) != GSL_SUCCESS) goto fail; } res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "gsl_matrix_complex_fprintf" "', argument " "3"" of type '" "char const *""'"); } arg3 = (char *)(buf3); result = (int)gsl_matrix_complex_fprintf(arg1,(gsl_matrix_complex const *)arg2,(char const *)arg3); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ; gsl_matrix_complex *arg2 = (gsl_matrix_complex *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "INOUT", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex _matrix1; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_complex _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_complex_swap",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_complex, 1, &stride) != GSL_SUCCESS) goto fail; } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_IO_ARRAY, gsl_matrix_complex, 2, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_complex_swap(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_swap_rows(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_complex_swap_rows",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_complex, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_complex_swap_rows" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_complex_swap_rows" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_complex_swap_rows(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_swap_columns(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_complex_swap_columns",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_complex, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_complex_swap_columns" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_complex_swap_columns" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_complex_swap_columns(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_swap_rowcol(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_complex_swap_rowcol",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_complex, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_complex_swap_rowcol" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_complex_swap_rowcol" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_complex_swap_rowcol(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_transpose(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "INOUT", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_complex_transpose",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_complex, 1, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_complex_transpose(arg1); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_complex_isnull",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_complex, 1, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_complex_isnull((gsl_matrix_complex const *)arg1); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_diagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; gsl_vector_complex_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_complex_diagonal",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_complex, 1, &stride) != GSL_SUCCESS) goto fail; } result = gsl_matrix_complex_diagonal(arg1); { PyArrayObject * out = NULL; gsl_vector_complex_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_complex_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_subdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN",(char *) "k", NULL }; gsl_vector_complex_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_complex_subdiagonal",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_complex, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_complex_subdiagonal" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = gsl_matrix_complex_subdiagonal(arg1,arg2); { PyArrayObject * out = NULL; gsl_vector_complex_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_complex_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_superdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN",(char *) "k", NULL }; gsl_vector_complex_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_complex_superdiagonal",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_complex, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_complex_superdiagonal" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = gsl_matrix_complex_superdiagonal(arg1,arg2); { PyArrayObject * out = NULL; gsl_vector_complex_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_complex_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_complex_float_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_complex_float *arg1 = (gsl_vector_complex_float *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_complex_float _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_complex_float_set_zero",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector_complex_float, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } gsl_vector_complex_float_set_zero(arg1); resultobj = SWIG_Py_Void(); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_complex_float_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_complex_float *arg1 = (gsl_vector_complex_float *) 0 ; gsl_complex_float arg2 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "IN", NULL }; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_complex_float _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_complex_float_set_all",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector_complex_float, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } { gsl_complex_float tmp; if(PyGSL_PyCOMPLEX_TO_gsl_complex_float(obj1, &tmp) != GSL_SUCCESS) goto fail; arg2 = tmp; } gsl_vector_complex_float_set_all(arg1,arg2); resultobj = SWIG_Py_Void(); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_complex_float_set_basis(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_complex_float *arg1 = (gsl_vector_complex_float *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "i", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_complex_float _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_complex_float_set_basis",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; int flag; _vector1.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1, PyGSL_OUTPUT_ARRAY, gsl_vector_complex_float, 1, &stride); if (flag != GSL_SUCCESS){ goto fail; } } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_vector_complex_float_set_basis" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = (int)gsl_vector_complex_float_set_basis(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_complex_float_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_complex_float *arg2 = (gsl_vector_complex_float *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_complex_float _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_complex_float_fread",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; int flag; _vector2.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2, PyGSL_OUTPUT_ARRAY, gsl_vector_complex_float, 2, &stride); if (flag != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_complex_float_fread(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_complex_float_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_complex_float *arg2 = (gsl_vector_complex_float *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_complex_float _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_complex_float_fwrite",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_INPUT_ARRAY, gsl_vector_complex_float, 2, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_complex_float_fwrite(arg1,(gsl_vector_complex_float const *)arg2); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_complex_float_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_complex_float *arg2 = (gsl_vector_complex_float *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_complex_float _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_complex_float_fscanf",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; int flag; _vector2.vector.data = NULL; flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2, PyGSL_OUTPUT_ARRAY, gsl_vector_complex_float, 2, &stride); if (flag != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_complex_float_fscanf(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_complex_float_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_vector_complex_float *arg2 = (gsl_vector_complex_float *) 0 ; char *arg3 = (char *) 0 ; int res3 ; char *buf3 = 0 ; int alloc3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN",(char *) "format", NULL }; int result; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_complex_float _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_vector_complex_float_fprintf",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_INPUT_ARRAY, gsl_vector_complex_float, 2, &stride) != GSL_SUCCESS){ goto fail; } } res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "gsl_vector_complex_float_fprintf" "', argument " "3"" of type '" "char const *""'"); } arg3 = (char *)(buf3); result = (int)gsl_vector_complex_float_fprintf(arg1,(gsl_vector_complex_float const *)arg2,(char const *)arg3); resultobj = SWIG_From_int((int)(result)); if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return resultobj; fail: if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_complex_float_reverse(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_complex_float *arg1 = (gsl_vector_complex_float *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "INOUT", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_complex_float _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_complex_float_reverse",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector_complex_float, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_complex_float_reverse(arg1); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_complex_float_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_complex_float *arg1 = (gsl_vector_complex_float *) 0 ; gsl_vector_complex_float *arg2 = (gsl_vector_complex_float *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "INOUT", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_complex_float _vector1; PyArrayObject * volatile _PyVector2 = NULL; TYPE_VIEW_gsl_vector_complex_float _vector2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_vector_complex_float_swap",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector_complex_float, 1, &stride) != GSL_SUCCESS){ goto fail; } } { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2, PyGSL_IO_ARRAY, gsl_vector_complex_float, 2, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_complex_float_swap(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } { assert(_PyVector2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector2)); _PyVector2 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_complex_float_swap_elements(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_complex_float *arg1 = (gsl_vector_complex_float *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_complex_float _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_vector_complex_float_swap_elements",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_IO_ARRAY, gsl_vector_complex_float, 1, &stride) != GSL_SUCCESS){ goto fail; } } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_vector_complex_float_swap_elements" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_vector_complex_float_swap_elements" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_vector_complex_float_swap_elements(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert(_PyVector1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyVector1)); _PyVector1 = NULL; FUNC_MESS_END(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_vector_complex_float_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_vector_complex_float *arg1 = (gsl_vector_complex_float *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; int result; PyArrayObject * volatile _PyVector1 = NULL; TYPE_VIEW_gsl_vector_complex_float _vector1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_vector_complex_float_isnull",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride=0; if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1, PyGSL_INPUT_ARRAY, gsl_vector_complex_float, 1, &stride) != GSL_SUCCESS){ goto fail; } } result = (int)gsl_vector_complex_float_isnull((gsl_vector_complex_float const *)arg1); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_complex_float_set_zero",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_complex_float, 1, &stride) !=GSL_SUCCESS) goto fail; } gsl_matrix_complex_float_set_zero(arg1); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ; gsl_complex_float arg2 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT",(char *) "IN", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_complex_float_set_all",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_complex_float, 1, &stride) !=GSL_SUCCESS) goto fail; } { gsl_complex_float tmp; if(PyGSL_PyCOMPLEX_TO_gsl_complex_float(obj1, &tmp) != GSL_SUCCESS) goto fail; arg2 = tmp; } gsl_matrix_complex_float_set_all(arg1,arg2); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_set_identity(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN_SIZE_OUT", NULL }; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_complex_float_set_identity",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_complex_float, 1, &stride) !=GSL_SUCCESS) goto fail; } gsl_matrix_complex_float_set_identity(arg1); resultobj = SWIG_Py_Void(); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_complex_float *arg2 = (gsl_matrix_complex_float *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_complex_float _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_complex_float_fread",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_complex_float, 2, &stride) !=GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_complex_float_fread(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_complex_float *arg2 = (gsl_matrix_complex_float *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_complex_float _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_complex_float_fwrite",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_INPUT_ARRAY, gsl_matrix_complex_float, 2, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_complex_float_fwrite(arg1,(gsl_matrix_complex_float const *)arg2); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_complex_float *arg2 = (gsl_matrix_complex_float *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN_SIZE_OUT", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_complex_float _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_complex_float_fscanf",kwnames,&obj0,&obj1)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_complex_float, 2, &stride) !=GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_complex_float_fscanf(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; FILE *arg1 = (FILE *) 0 ; gsl_matrix_complex_float *arg2 = (gsl_matrix_complex_float *) 0 ; char *arg3 = (char *) 0 ; int res3 ; char *buf3 = 0 ; int alloc3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "stream",(char *) "IN",(char *) "format", NULL }; int result; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_complex_float _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_complex_float_fprintf",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { FUNC_MESS_BEGIN(); HANDLE_MINGW(); if (!PyFile_Check(obj0)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); PyGSL_add_traceback(NULL, "typemaps/file_typemaps.i", __FUNCTION__, 33); goto fail; } FUNC_MESS("Convert Python File to C File"); arg1 = PyFile_AsFile(obj0); DEBUG_MESS(2, "Using file at %p with filedes %d", (void *) arg1, fileno(arg1)); assert(arg1 != NULL); } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_INPUT_ARRAY, gsl_matrix_complex_float, 2, &stride) != GSL_SUCCESS) goto fail; } res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "gsl_matrix_complex_float_fprintf" "', argument " "3"" of type '" "char const *""'"); } arg3 = (char *)(buf3); result = (int)gsl_matrix_complex_float_fprintf(arg1,(gsl_matrix_complex_float const *)arg2,(char const *)arg3); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return resultobj; fail: { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ; gsl_matrix_complex_float *arg2 = (gsl_matrix_complex_float *) 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "INOUT", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex_float _matrix1; PyArrayObject * _PyMatrix2 = NULL; TYPE_VIEW_gsl_matrix_complex_float _matrix2; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_complex_float_swap",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_complex_float, 1, &stride) != GSL_SUCCESS) goto fail; } { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_IO_ARRAY, gsl_matrix_complex_float, 2, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_complex_float_swap(arg1,arg2); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { assert((PyObject *) _PyMatrix2 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix2)); _PyMatrix2 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix2); _PyMatrix2 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_swap_rows(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_complex_float_swap_rows",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_complex_float, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_complex_float_swap_rows" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_complex_float_swap_rows" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_complex_float_swap_rows(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_swap_columns(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_complex_float_swap_columns",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_complex_float, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_complex_float_swap_columns" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_complex_float_swap_columns" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_complex_float_swap_columns(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_swap_rowcol(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ; size_t arg2 ; size_t arg3 ; size_t val2 ; int ecode2 = 0 ; size_t val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; char * kwnames[] = { (char *) "INOUT",(char *) "i",(char *) "j", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OOO:gsl_matrix_complex_float_swap_rowcol",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_complex_float, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_complex_float_swap_rowcol" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_size_t(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "gsl_matrix_complex_float_swap_rowcol" "', argument " "3"" of type '" "size_t""'"); } arg3 = (size_t)(val3); result = (int)gsl_matrix_complex_float_swap_rowcol(arg1,arg2,arg3); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_transpose(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "INOUT", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_complex_float_transpose",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_IO_ARRAY, gsl_matrix_complex_float, 1, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_complex_float_transpose(arg1); resultobj = SWIG_From_int((int)(result)); { assert((PyObject *) _PyMatrix1 != NULL); resultobj = SWIG_Python_AppendOutput(resultobj, PyGSL_array_return(_PyMatrix1)); _PyMatrix1 = NULL; FUNC_MESS_END(); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; int result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_complex_float_isnull",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_complex_float, 1, &stride) != GSL_SUCCESS) goto fail; } result = (int)gsl_matrix_complex_float_isnull((gsl_matrix_complex_float const *)arg1); resultobj = SWIG_From_int((int)(result)); { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_diagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ; PyObject * obj0 = 0 ; char * kwnames[] = { (char *) "IN", NULL }; gsl_vector_complex_float_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"O:gsl_matrix_complex_float_diagonal",kwnames,&obj0)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_complex_float, 1, &stride) != GSL_SUCCESS) goto fail; } result = gsl_matrix_complex_float_diagonal(arg1); { PyArrayObject * out = NULL; gsl_vector_complex_float_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_complex_float_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_subdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN",(char *) "k", NULL }; gsl_vector_complex_float_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_complex_float_subdiagonal",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_complex_float, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_complex_float_subdiagonal" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = gsl_matrix_complex_float_subdiagonal(arg1,arg2); { PyArrayObject * out = NULL; gsl_vector_complex_float_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_complex_float_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } SWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_superdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { PyObject *resultobj = 0; gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ; size_t arg2 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; char * kwnames[] = { (char *) "IN",(char *) "k", NULL }; gsl_vector_complex_float_view result; PyArrayObject * _PyMatrix1 = NULL; TYPE_VIEW_gsl_matrix_complex_float _matrix1; if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"OO:gsl_matrix_complex_float_superdiagonal",kwnames,&obj0,&obj1)) SWIG_fail; { PyGSL_array_index_t stride; if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_INPUT_ARRAY, gsl_matrix_complex_float, 1, &stride) != GSL_SUCCESS) goto fail; } ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "gsl_matrix_complex_float_superdiagonal" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = gsl_matrix_complex_float_superdiagonal(arg1,arg2); { PyArrayObject * out = NULL; gsl_vector_complex_float_view vectmp; PyGSL_array_index_t tmp; if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_complex_float_view, vectmp, tmp) != GSL_SUCCESS){ goto fail; } resultobj = PyGSL_array_return(out); } { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return resultobj; fail: { Py_XDECREF(_PyMatrix1); _PyMatrix1 = NULL; FUNC_MESS_END(); } return NULL; } static PyMethodDef SwigMethods[] = { { (char *)"gsl_vector_set_zero", (PyCFunction) _wrap_gsl_vector_set_zero, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_set_all", (PyCFunction) _wrap_gsl_vector_set_all, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_set_basis", (PyCFunction) _wrap_gsl_vector_set_basis, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_fread", (PyCFunction) _wrap_gsl_vector_fread, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_fwrite", (PyCFunction) _wrap_gsl_vector_fwrite, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_fscanf", (PyCFunction) _wrap_gsl_vector_fscanf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_fprintf", (PyCFunction) _wrap_gsl_vector_fprintf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_reverse", (PyCFunction) _wrap_gsl_vector_reverse, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_swap", (PyCFunction) _wrap_gsl_vector_swap, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_swap_elements", (PyCFunction) _wrap_gsl_vector_swap_elements, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_max", (PyCFunction) _wrap_gsl_vector_max, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_min", (PyCFunction) _wrap_gsl_vector_min, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_minmax", (PyCFunction) _wrap_gsl_vector_minmax, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_max_index", (PyCFunction) _wrap_gsl_vector_max_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_min_index", (PyCFunction) _wrap_gsl_vector_min_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_minmax_index", (PyCFunction) _wrap_gsl_vector_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_isnull", (PyCFunction) _wrap_gsl_vector_isnull, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_set_zero", (PyCFunction) _wrap_gsl_matrix_set_zero, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_set_all", (PyCFunction) _wrap_gsl_matrix_set_all, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_set_identity", (PyCFunction) _wrap_gsl_matrix_set_identity, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_fread", (PyCFunction) _wrap_gsl_matrix_fread, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_fwrite", (PyCFunction) _wrap_gsl_matrix_fwrite, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_fscanf", (PyCFunction) _wrap_gsl_matrix_fscanf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_fprintf", (PyCFunction) _wrap_gsl_matrix_fprintf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_swap", (PyCFunction) _wrap_gsl_matrix_swap, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_swap_rows", (PyCFunction) _wrap_gsl_matrix_swap_rows, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_swap_columns", (PyCFunction) _wrap_gsl_matrix_swap_columns, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_swap_rowcol", (PyCFunction) _wrap_gsl_matrix_swap_rowcol, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_transpose", (PyCFunction) _wrap_gsl_matrix_transpose, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_max", (PyCFunction) _wrap_gsl_matrix_max, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_min", (PyCFunction) _wrap_gsl_matrix_min, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_minmax", (PyCFunction) _wrap_gsl_matrix_minmax, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_max_index", (PyCFunction) _wrap_gsl_matrix_max_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_min_index", (PyCFunction) _wrap_gsl_matrix_min_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_minmax_index", (PyCFunction) _wrap_gsl_matrix_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_isnull", (PyCFunction) _wrap_gsl_matrix_isnull, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_diagonal", (PyCFunction) _wrap_gsl_matrix_diagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_subdiagonal", (PyCFunction) _wrap_gsl_matrix_subdiagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_superdiagonal", (PyCFunction) _wrap_gsl_matrix_superdiagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_float_set_zero", (PyCFunction) _wrap_gsl_vector_float_set_zero, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_float_set_all", (PyCFunction) _wrap_gsl_vector_float_set_all, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_float_set_basis", (PyCFunction) _wrap_gsl_vector_float_set_basis, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_float_fread", (PyCFunction) _wrap_gsl_vector_float_fread, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_float_fwrite", (PyCFunction) _wrap_gsl_vector_float_fwrite, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_float_fscanf", (PyCFunction) _wrap_gsl_vector_float_fscanf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_float_fprintf", (PyCFunction) _wrap_gsl_vector_float_fprintf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_float_reverse", (PyCFunction) _wrap_gsl_vector_float_reverse, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_float_swap", (PyCFunction) _wrap_gsl_vector_float_swap, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_float_swap_elements", (PyCFunction) _wrap_gsl_vector_float_swap_elements, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_float_max", (PyCFunction) _wrap_gsl_vector_float_max, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_float_min", (PyCFunction) _wrap_gsl_vector_float_min, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_float_minmax", (PyCFunction) _wrap_gsl_vector_float_minmax, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_float_max_index", (PyCFunction) _wrap_gsl_vector_float_max_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_float_min_index", (PyCFunction) _wrap_gsl_vector_float_min_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_float_minmax_index", (PyCFunction) _wrap_gsl_vector_float_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_float_isnull", (PyCFunction) _wrap_gsl_vector_float_isnull, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_float_set_zero", (PyCFunction) _wrap_gsl_matrix_float_set_zero, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_float_set_all", (PyCFunction) _wrap_gsl_matrix_float_set_all, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_float_set_identity", (PyCFunction) _wrap_gsl_matrix_float_set_identity, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_float_fread", (PyCFunction) _wrap_gsl_matrix_float_fread, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_float_fwrite", (PyCFunction) _wrap_gsl_matrix_float_fwrite, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_float_fscanf", (PyCFunction) _wrap_gsl_matrix_float_fscanf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_float_fprintf", (PyCFunction) _wrap_gsl_matrix_float_fprintf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_float_swap", (PyCFunction) _wrap_gsl_matrix_float_swap, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_float_swap_rows", (PyCFunction) _wrap_gsl_matrix_float_swap_rows, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_float_swap_columns", (PyCFunction) _wrap_gsl_matrix_float_swap_columns, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_float_swap_rowcol", (PyCFunction) _wrap_gsl_matrix_float_swap_rowcol, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_float_transpose", (PyCFunction) _wrap_gsl_matrix_float_transpose, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_float_max", (PyCFunction) _wrap_gsl_matrix_float_max, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_float_min", (PyCFunction) _wrap_gsl_matrix_float_min, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_float_minmax", (PyCFunction) _wrap_gsl_matrix_float_minmax, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_float_max_index", (PyCFunction) _wrap_gsl_matrix_float_max_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_float_min_index", (PyCFunction) _wrap_gsl_matrix_float_min_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_float_minmax_index", (PyCFunction) _wrap_gsl_matrix_float_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_float_isnull", (PyCFunction) _wrap_gsl_matrix_float_isnull, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_float_diagonal", (PyCFunction) _wrap_gsl_matrix_float_diagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_float_subdiagonal", (PyCFunction) _wrap_gsl_matrix_float_subdiagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_float_superdiagonal", (PyCFunction) _wrap_gsl_matrix_float_superdiagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_long_set_zero", (PyCFunction) _wrap_gsl_vector_long_set_zero, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_long_set_all", (PyCFunction) _wrap_gsl_vector_long_set_all, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_long_set_basis", (PyCFunction) _wrap_gsl_vector_long_set_basis, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_long_fread", (PyCFunction) _wrap_gsl_vector_long_fread, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_long_fwrite", (PyCFunction) _wrap_gsl_vector_long_fwrite, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_long_fscanf", (PyCFunction) _wrap_gsl_vector_long_fscanf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_long_fprintf", (PyCFunction) _wrap_gsl_vector_long_fprintf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_long_reverse", (PyCFunction) _wrap_gsl_vector_long_reverse, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_long_swap", (PyCFunction) _wrap_gsl_vector_long_swap, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_long_swap_elements", (PyCFunction) _wrap_gsl_vector_long_swap_elements, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_long_max", (PyCFunction) _wrap_gsl_vector_long_max, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_long_min", (PyCFunction) _wrap_gsl_vector_long_min, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_long_minmax", (PyCFunction) _wrap_gsl_vector_long_minmax, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_long_max_index", (PyCFunction) _wrap_gsl_vector_long_max_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_long_min_index", (PyCFunction) _wrap_gsl_vector_long_min_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_long_minmax_index", (PyCFunction) _wrap_gsl_vector_long_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_long_isnull", (PyCFunction) _wrap_gsl_vector_long_isnull, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_long_set_zero", (PyCFunction) _wrap_gsl_matrix_long_set_zero, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_long_set_all", (PyCFunction) _wrap_gsl_matrix_long_set_all, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_long_set_identity", (PyCFunction) _wrap_gsl_matrix_long_set_identity, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_long_fread", (PyCFunction) _wrap_gsl_matrix_long_fread, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_long_fwrite", (PyCFunction) _wrap_gsl_matrix_long_fwrite, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_long_fscanf", (PyCFunction) _wrap_gsl_matrix_long_fscanf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_long_fprintf", (PyCFunction) _wrap_gsl_matrix_long_fprintf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_long_swap", (PyCFunction) _wrap_gsl_matrix_long_swap, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_long_swap_rows", (PyCFunction) _wrap_gsl_matrix_long_swap_rows, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_long_swap_columns", (PyCFunction) _wrap_gsl_matrix_long_swap_columns, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_long_swap_rowcol", (PyCFunction) _wrap_gsl_matrix_long_swap_rowcol, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_long_transpose", (PyCFunction) _wrap_gsl_matrix_long_transpose, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_long_max", (PyCFunction) _wrap_gsl_matrix_long_max, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_long_min", (PyCFunction) _wrap_gsl_matrix_long_min, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_long_minmax", (PyCFunction) _wrap_gsl_matrix_long_minmax, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_long_max_index", (PyCFunction) _wrap_gsl_matrix_long_max_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_long_min_index", (PyCFunction) _wrap_gsl_matrix_long_min_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_long_minmax_index", (PyCFunction) _wrap_gsl_matrix_long_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_long_isnull", (PyCFunction) _wrap_gsl_matrix_long_isnull, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_long_diagonal", (PyCFunction) _wrap_gsl_matrix_long_diagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_long_subdiagonal", (PyCFunction) _wrap_gsl_matrix_long_subdiagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_long_superdiagonal", (PyCFunction) _wrap_gsl_matrix_long_superdiagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_int_set_zero", (PyCFunction) _wrap_gsl_vector_int_set_zero, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_int_set_all", (PyCFunction) _wrap_gsl_vector_int_set_all, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_int_set_basis", (PyCFunction) _wrap_gsl_vector_int_set_basis, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_int_fread", (PyCFunction) _wrap_gsl_vector_int_fread, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_int_fwrite", (PyCFunction) _wrap_gsl_vector_int_fwrite, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_int_fscanf", (PyCFunction) _wrap_gsl_vector_int_fscanf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_int_fprintf", (PyCFunction) _wrap_gsl_vector_int_fprintf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_int_reverse", (PyCFunction) _wrap_gsl_vector_int_reverse, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_int_swap", (PyCFunction) _wrap_gsl_vector_int_swap, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_int_swap_elements", (PyCFunction) _wrap_gsl_vector_int_swap_elements, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_int_max", (PyCFunction) _wrap_gsl_vector_int_max, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_int_min", (PyCFunction) _wrap_gsl_vector_int_min, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_int_minmax", (PyCFunction) _wrap_gsl_vector_int_minmax, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_int_max_index", (PyCFunction) _wrap_gsl_vector_int_max_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_int_min_index", (PyCFunction) _wrap_gsl_vector_int_min_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_int_minmax_index", (PyCFunction) _wrap_gsl_vector_int_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_int_isnull", (PyCFunction) _wrap_gsl_vector_int_isnull, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_int_set_zero", (PyCFunction) _wrap_gsl_matrix_int_set_zero, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_int_set_all", (PyCFunction) _wrap_gsl_matrix_int_set_all, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_int_set_identity", (PyCFunction) _wrap_gsl_matrix_int_set_identity, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_int_fread", (PyCFunction) _wrap_gsl_matrix_int_fread, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_int_fwrite", (PyCFunction) _wrap_gsl_matrix_int_fwrite, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_int_fscanf", (PyCFunction) _wrap_gsl_matrix_int_fscanf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_int_fprintf", (PyCFunction) _wrap_gsl_matrix_int_fprintf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_int_swap", (PyCFunction) _wrap_gsl_matrix_int_swap, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_int_swap_rows", (PyCFunction) _wrap_gsl_matrix_int_swap_rows, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_int_swap_columns", (PyCFunction) _wrap_gsl_matrix_int_swap_columns, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_int_swap_rowcol", (PyCFunction) _wrap_gsl_matrix_int_swap_rowcol, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_int_transpose", (PyCFunction) _wrap_gsl_matrix_int_transpose, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_int_max", (PyCFunction) _wrap_gsl_matrix_int_max, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_int_min", (PyCFunction) _wrap_gsl_matrix_int_min, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_int_minmax", (PyCFunction) _wrap_gsl_matrix_int_minmax, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_int_max_index", (PyCFunction) _wrap_gsl_matrix_int_max_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_int_min_index", (PyCFunction) _wrap_gsl_matrix_int_min_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_int_minmax_index", (PyCFunction) _wrap_gsl_matrix_int_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_int_isnull", (PyCFunction) _wrap_gsl_matrix_int_isnull, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_int_diagonal", (PyCFunction) _wrap_gsl_matrix_int_diagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_int_subdiagonal", (PyCFunction) _wrap_gsl_matrix_int_subdiagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_int_superdiagonal", (PyCFunction) _wrap_gsl_matrix_int_superdiagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_short_set_zero", (PyCFunction) _wrap_gsl_vector_short_set_zero, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_short_set_all", (PyCFunction) _wrap_gsl_vector_short_set_all, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_short_set_basis", (PyCFunction) _wrap_gsl_vector_short_set_basis, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_short_fread", (PyCFunction) _wrap_gsl_vector_short_fread, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_short_fwrite", (PyCFunction) _wrap_gsl_vector_short_fwrite, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_short_fscanf", (PyCFunction) _wrap_gsl_vector_short_fscanf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_short_fprintf", (PyCFunction) _wrap_gsl_vector_short_fprintf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_short_reverse", (PyCFunction) _wrap_gsl_vector_short_reverse, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_short_swap", (PyCFunction) _wrap_gsl_vector_short_swap, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_short_swap_elements", (PyCFunction) _wrap_gsl_vector_short_swap_elements, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_short_max", (PyCFunction) _wrap_gsl_vector_short_max, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_short_min", (PyCFunction) _wrap_gsl_vector_short_min, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_short_minmax", (PyCFunction) _wrap_gsl_vector_short_minmax, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_short_max_index", (PyCFunction) _wrap_gsl_vector_short_max_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_short_min_index", (PyCFunction) _wrap_gsl_vector_short_min_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_short_minmax_index", (PyCFunction) _wrap_gsl_vector_short_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_short_isnull", (PyCFunction) _wrap_gsl_vector_short_isnull, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_short_set_zero", (PyCFunction) _wrap_gsl_matrix_short_set_zero, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_short_set_all", (PyCFunction) _wrap_gsl_matrix_short_set_all, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_short_set_identity", (PyCFunction) _wrap_gsl_matrix_short_set_identity, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_short_fread", (PyCFunction) _wrap_gsl_matrix_short_fread, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_short_fwrite", (PyCFunction) _wrap_gsl_matrix_short_fwrite, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_short_fscanf", (PyCFunction) _wrap_gsl_matrix_short_fscanf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_short_fprintf", (PyCFunction) _wrap_gsl_matrix_short_fprintf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_short_swap", (PyCFunction) _wrap_gsl_matrix_short_swap, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_short_swap_rows", (PyCFunction) _wrap_gsl_matrix_short_swap_rows, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_short_swap_columns", (PyCFunction) _wrap_gsl_matrix_short_swap_columns, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_short_swap_rowcol", (PyCFunction) _wrap_gsl_matrix_short_swap_rowcol, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_short_transpose", (PyCFunction) _wrap_gsl_matrix_short_transpose, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_short_max", (PyCFunction) _wrap_gsl_matrix_short_max, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_short_min", (PyCFunction) _wrap_gsl_matrix_short_min, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_short_minmax", (PyCFunction) _wrap_gsl_matrix_short_minmax, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_short_max_index", (PyCFunction) _wrap_gsl_matrix_short_max_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_short_min_index", (PyCFunction) _wrap_gsl_matrix_short_min_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_short_minmax_index", (PyCFunction) _wrap_gsl_matrix_short_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_short_isnull", (PyCFunction) _wrap_gsl_matrix_short_isnull, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_short_diagonal", (PyCFunction) _wrap_gsl_matrix_short_diagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_short_subdiagonal", (PyCFunction) _wrap_gsl_matrix_short_subdiagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_short_superdiagonal", (PyCFunction) _wrap_gsl_matrix_short_superdiagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_char_set_zero", (PyCFunction) _wrap_gsl_vector_char_set_zero, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_char_set_all", (PyCFunction) _wrap_gsl_vector_char_set_all, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_char_set_basis", (PyCFunction) _wrap_gsl_vector_char_set_basis, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_char_fread", (PyCFunction) _wrap_gsl_vector_char_fread, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_char_fwrite", (PyCFunction) _wrap_gsl_vector_char_fwrite, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_char_fscanf", (PyCFunction) _wrap_gsl_vector_char_fscanf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_char_fprintf", (PyCFunction) _wrap_gsl_vector_char_fprintf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_char_reverse", (PyCFunction) _wrap_gsl_vector_char_reverse, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_char_swap", (PyCFunction) _wrap_gsl_vector_char_swap, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_char_swap_elements", (PyCFunction) _wrap_gsl_vector_char_swap_elements, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_char_max", (PyCFunction) _wrap_gsl_vector_char_max, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_char_min", (PyCFunction) _wrap_gsl_vector_char_min, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_char_minmax", (PyCFunction) _wrap_gsl_vector_char_minmax, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_char_max_index", (PyCFunction) _wrap_gsl_vector_char_max_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_char_min_index", (PyCFunction) _wrap_gsl_vector_char_min_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_char_minmax_index", (PyCFunction) _wrap_gsl_vector_char_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_char_isnull", (PyCFunction) _wrap_gsl_vector_char_isnull, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_char_set_zero", (PyCFunction) _wrap_gsl_matrix_char_set_zero, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_char_set_all", (PyCFunction) _wrap_gsl_matrix_char_set_all, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_char_set_identity", (PyCFunction) _wrap_gsl_matrix_char_set_identity, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_char_fread", (PyCFunction) _wrap_gsl_matrix_char_fread, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_char_fwrite", (PyCFunction) _wrap_gsl_matrix_char_fwrite, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_char_fscanf", (PyCFunction) _wrap_gsl_matrix_char_fscanf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_char_fprintf", (PyCFunction) _wrap_gsl_matrix_char_fprintf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_char_swap", (PyCFunction) _wrap_gsl_matrix_char_swap, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_char_swap_rows", (PyCFunction) _wrap_gsl_matrix_char_swap_rows, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_char_swap_columns", (PyCFunction) _wrap_gsl_matrix_char_swap_columns, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_char_swap_rowcol", (PyCFunction) _wrap_gsl_matrix_char_swap_rowcol, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_char_transpose", (PyCFunction) _wrap_gsl_matrix_char_transpose, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_char_max", (PyCFunction) _wrap_gsl_matrix_char_max, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_char_min", (PyCFunction) _wrap_gsl_matrix_char_min, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_char_minmax", (PyCFunction) _wrap_gsl_matrix_char_minmax, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_char_max_index", (PyCFunction) _wrap_gsl_matrix_char_max_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_char_min_index", (PyCFunction) _wrap_gsl_matrix_char_min_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_char_minmax_index", (PyCFunction) _wrap_gsl_matrix_char_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_char_isnull", (PyCFunction) _wrap_gsl_matrix_char_isnull, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_char_diagonal", (PyCFunction) _wrap_gsl_matrix_char_diagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_char_subdiagonal", (PyCFunction) _wrap_gsl_matrix_char_subdiagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_char_superdiagonal", (PyCFunction) _wrap_gsl_matrix_char_superdiagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_complex_set_zero", (PyCFunction) _wrap_gsl_vector_complex_set_zero, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_complex_set_all", (PyCFunction) _wrap_gsl_vector_complex_set_all, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_complex_set_basis", (PyCFunction) _wrap_gsl_vector_complex_set_basis, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_complex_fread", (PyCFunction) _wrap_gsl_vector_complex_fread, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_complex_fwrite", (PyCFunction) _wrap_gsl_vector_complex_fwrite, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_complex_fscanf", (PyCFunction) _wrap_gsl_vector_complex_fscanf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_complex_fprintf", (PyCFunction) _wrap_gsl_vector_complex_fprintf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_complex_reverse", (PyCFunction) _wrap_gsl_vector_complex_reverse, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_complex_swap", (PyCFunction) _wrap_gsl_vector_complex_swap, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_complex_swap_elements", (PyCFunction) _wrap_gsl_vector_complex_swap_elements, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_complex_isnull", (PyCFunction) _wrap_gsl_vector_complex_isnull, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_set_zero", (PyCFunction) _wrap_gsl_matrix_complex_set_zero, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_set_all", (PyCFunction) _wrap_gsl_matrix_complex_set_all, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_set_identity", (PyCFunction) _wrap_gsl_matrix_complex_set_identity, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_fread", (PyCFunction) _wrap_gsl_matrix_complex_fread, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_fwrite", (PyCFunction) _wrap_gsl_matrix_complex_fwrite, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_fscanf", (PyCFunction) _wrap_gsl_matrix_complex_fscanf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_fprintf", (PyCFunction) _wrap_gsl_matrix_complex_fprintf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_swap", (PyCFunction) _wrap_gsl_matrix_complex_swap, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_swap_rows", (PyCFunction) _wrap_gsl_matrix_complex_swap_rows, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_swap_columns", (PyCFunction) _wrap_gsl_matrix_complex_swap_columns, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_swap_rowcol", (PyCFunction) _wrap_gsl_matrix_complex_swap_rowcol, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_transpose", (PyCFunction) _wrap_gsl_matrix_complex_transpose, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_isnull", (PyCFunction) _wrap_gsl_matrix_complex_isnull, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_diagonal", (PyCFunction) _wrap_gsl_matrix_complex_diagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_subdiagonal", (PyCFunction) _wrap_gsl_matrix_complex_subdiagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_superdiagonal", (PyCFunction) _wrap_gsl_matrix_complex_superdiagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_complex_float_set_zero", (PyCFunction) _wrap_gsl_vector_complex_float_set_zero, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_complex_float_set_all", (PyCFunction) _wrap_gsl_vector_complex_float_set_all, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_complex_float_set_basis", (PyCFunction) _wrap_gsl_vector_complex_float_set_basis, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_complex_float_fread", (PyCFunction) _wrap_gsl_vector_complex_float_fread, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_complex_float_fwrite", (PyCFunction) _wrap_gsl_vector_complex_float_fwrite, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_complex_float_fscanf", (PyCFunction) _wrap_gsl_vector_complex_float_fscanf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_complex_float_fprintf", (PyCFunction) _wrap_gsl_vector_complex_float_fprintf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_complex_float_reverse", (PyCFunction) _wrap_gsl_vector_complex_float_reverse, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_complex_float_swap", (PyCFunction) _wrap_gsl_vector_complex_float_swap, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_complex_float_swap_elements", (PyCFunction) _wrap_gsl_vector_complex_float_swap_elements, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_vector_complex_float_isnull", (PyCFunction) _wrap_gsl_vector_complex_float_isnull, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_float_set_zero", (PyCFunction) _wrap_gsl_matrix_complex_float_set_zero, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_float_set_all", (PyCFunction) _wrap_gsl_matrix_complex_float_set_all, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_float_set_identity", (PyCFunction) _wrap_gsl_matrix_complex_float_set_identity, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_float_fread", (PyCFunction) _wrap_gsl_matrix_complex_float_fread, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_float_fwrite", (PyCFunction) _wrap_gsl_matrix_complex_float_fwrite, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_float_fscanf", (PyCFunction) _wrap_gsl_matrix_complex_float_fscanf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_float_fprintf", (PyCFunction) _wrap_gsl_matrix_complex_float_fprintf, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_float_swap", (PyCFunction) _wrap_gsl_matrix_complex_float_swap, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_float_swap_rows", (PyCFunction) _wrap_gsl_matrix_complex_float_swap_rows, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_float_swap_columns", (PyCFunction) _wrap_gsl_matrix_complex_float_swap_columns, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_float_swap_rowcol", (PyCFunction) _wrap_gsl_matrix_complex_float_swap_rowcol, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_float_transpose", (PyCFunction) _wrap_gsl_matrix_complex_float_transpose, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_float_isnull", (PyCFunction) _wrap_gsl_matrix_complex_float_isnull, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_float_diagonal", (PyCFunction) _wrap_gsl_matrix_complex_float_diagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_float_subdiagonal", (PyCFunction) _wrap_gsl_matrix_complex_float_subdiagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { (char *)"gsl_matrix_complex_float_superdiagonal", (PyCFunction) _wrap_gsl_matrix_complex_float_superdiagonal, METH_VARARGS | METH_KEYWORDS, NULL}, { NULL, NULL, 0, NULL } }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ static swig_type_info _swigt__p_FILE = {"_p_FILE", "FILE *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_double = {"_p_double", "double *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_float = {"_p_float", "float *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_gsl_complex = {"_p_gsl_complex", "gsl_complex *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_gsl_complex_float = {"_p_gsl_complex_float", "gsl_complex_float *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_gsl_matrix = {"_p_gsl_matrix", "gsl_matrix *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_gsl_matrix_char = {"_p_gsl_matrix_char", "gsl_matrix_char *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_gsl_matrix_complex = {"_p_gsl_matrix_complex", "gsl_matrix_complex *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_gsl_matrix_complex_float = {"_p_gsl_matrix_complex_float", "gsl_matrix_complex_float *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_gsl_matrix_float = {"_p_gsl_matrix_float", "gsl_matrix_float *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_gsl_matrix_int = {"_p_gsl_matrix_int", "gsl_matrix_int *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_gsl_matrix_long = {"_p_gsl_matrix_long", "gsl_matrix_long *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_gsl_matrix_short = {"_p_gsl_matrix_short", "gsl_matrix_short *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_gsl_vector = {"_p_gsl_vector", "gsl_vector *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_gsl_vector_char = {"_p_gsl_vector_char", "gsl_vector_char *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_gsl_vector_complex = {"_p_gsl_vector_complex", "gsl_vector_complex *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_gsl_vector_complex_float = {"_p_gsl_vector_complex_float", "gsl_vector_complex_float *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_gsl_vector_float = {"_p_gsl_vector_float", "gsl_vector_float *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_gsl_vector_int = {"_p_gsl_vector_int", "gsl_vector_int *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_gsl_vector_long = {"_p_gsl_vector_long", "gsl_vector_long *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_gsl_vector_short = {"_p_gsl_vector_short", "gsl_vector_short *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_int = {"_p_int", "int *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_long = {"_p_long", "long *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_short = {"_p_short", "short *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_unsigned_int = {"_p_unsigned_int", "size_t *|unsigned int *", 0, 0, (void*)0, 0}; static swig_type_info *swig_type_initial[] = { &_swigt__p_FILE, &_swigt__p_char, &_swigt__p_double, &_swigt__p_float, &_swigt__p_gsl_complex, &_swigt__p_gsl_complex_float, &_swigt__p_gsl_matrix, &_swigt__p_gsl_matrix_char, &_swigt__p_gsl_matrix_complex, &_swigt__p_gsl_matrix_complex_float, &_swigt__p_gsl_matrix_float, &_swigt__p_gsl_matrix_int, &_swigt__p_gsl_matrix_long, &_swigt__p_gsl_matrix_short, &_swigt__p_gsl_vector, &_swigt__p_gsl_vector_char, &_swigt__p_gsl_vector_complex, &_swigt__p_gsl_vector_complex_float, &_swigt__p_gsl_vector_float, &_swigt__p_gsl_vector_int, &_swigt__p_gsl_vector_long, &_swigt__p_gsl_vector_short, &_swigt__p_int, &_swigt__p_long, &_swigt__p_short, &_swigt__p_unsigned_int, }; static swig_cast_info _swigc__p_FILE[] = { {&_swigt__p_FILE, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_double[] = { {&_swigt__p_double, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_float[] = { {&_swigt__p_float, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_gsl_complex[] = { {&_swigt__p_gsl_complex, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_gsl_complex_float[] = { {&_swigt__p_gsl_complex_float, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_gsl_matrix[] = { {&_swigt__p_gsl_matrix, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_gsl_matrix_char[] = { {&_swigt__p_gsl_matrix_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_gsl_matrix_complex[] = { {&_swigt__p_gsl_matrix_complex, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_gsl_matrix_complex_float[] = { {&_swigt__p_gsl_matrix_complex_float, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_gsl_matrix_float[] = { {&_swigt__p_gsl_matrix_float, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_gsl_matrix_int[] = { {&_swigt__p_gsl_matrix_int, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_gsl_matrix_long[] = { {&_swigt__p_gsl_matrix_long, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_gsl_matrix_short[] = { {&_swigt__p_gsl_matrix_short, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_gsl_vector[] = { {&_swigt__p_gsl_vector, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_gsl_vector_char[] = { {&_swigt__p_gsl_vector_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_gsl_vector_complex[] = { {&_swigt__p_gsl_vector_complex, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_gsl_vector_complex_float[] = { {&_swigt__p_gsl_vector_complex_float, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_gsl_vector_float[] = { {&_swigt__p_gsl_vector_float, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_gsl_vector_int[] = { {&_swigt__p_gsl_vector_int, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_gsl_vector_long[] = { {&_swigt__p_gsl_vector_long, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_gsl_vector_short[] = { {&_swigt__p_gsl_vector_short, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_int[] = { {&_swigt__p_int, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_long[] = { {&_swigt__p_long, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_short[] = { {&_swigt__p_short, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_unsigned_int[] = { {&_swigt__p_unsigned_int, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info *swig_cast_initial[] = { _swigc__p_FILE, _swigc__p_char, _swigc__p_double, _swigc__p_float, _swigc__p_gsl_complex, _swigc__p_gsl_complex_float, _swigc__p_gsl_matrix, _swigc__p_gsl_matrix_char, _swigc__p_gsl_matrix_complex, _swigc__p_gsl_matrix_complex_float, _swigc__p_gsl_matrix_float, _swigc__p_gsl_matrix_int, _swigc__p_gsl_matrix_long, _swigc__p_gsl_matrix_short, _swigc__p_gsl_vector, _swigc__p_gsl_vector_char, _swigc__p_gsl_vector_complex, _swigc__p_gsl_vector_complex_float, _swigc__p_gsl_vector_float, _swigc__p_gsl_vector_int, _swigc__p_gsl_vector_long, _swigc__p_gsl_vector_short, _swigc__p_int, _swigc__p_long, _swigc__p_short, _swigc__p_unsigned_int, }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ static swig_const_info swig_const_table[] = { {0, 0, 0, 0.0, 0, 0}}; #ifdef __cplusplus } #endif /* ----------------------------------------------------------------------------- * Type initialization: * This problem is tough by the requirement that no dynamic * memory is used. Also, since swig_type_info structures store pointers to * swig_cast_info structures and swig_cast_info structures store pointers back * to swig_type_info structures, we need some lookup code at initialization. * The idea is that swig generates all the structures that are needed. * The runtime then collects these partially filled structures. * The SWIG_InitializeModule function takes these initial arrays out of * swig_module, and does all the lookup, filling in the swig_module.types * array with the correct data and linking the correct swig_cast_info * structures together. * * The generated swig_type_info structures are assigned staticly to an initial * array. We just loop through that array, and handle each type individually. * First we lookup if this type has been already loaded, and if so, use the * loaded structure instead of the generated one. Then we have to fill in the * cast linked list. The cast data is initially stored in something like a * two-dimensional array. Each row corresponds to a type (there are the same * number of rows as there are in the swig_type_initial array). Each entry in * a column is one of the swig_cast_info structures for that type. * The cast_initial array is actually an array of arrays, because each row has * a variable number of columns. So to actually build the cast linked list, * we find the array of casts associated with the type, and loop through it * adding the casts to the list. The one last trick we need to do is making * sure the type pointer in the swig_cast_info struct is correct. * * First off, we lookup the cast->type name to see if it is already loaded. * There are three cases to handle: * 1) If the cast->type has already been loaded AND the type we are adding * casting info to has not been loaded (it is in this module), THEN we * replace the cast->type pointer with the type pointer that has already * been loaded. * 2) If BOTH types (the one we are adding casting info to, and the * cast->type) are loaded, THEN the cast info has already been loaded by * the previous module so we just ignore it. * 3) Finally, if cast->type has not already been loaded, then we add that * swig_cast_info to the linked list (because the cast->type) pointer will * be correct. * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #if 0 } /* c-mode */ #endif #endif #if 0 #define SWIGRUNTIME_DEBUG #endif SWIGRUNTIME void SWIG_InitializeModule(void *clientdata) { size_t i; swig_module_info *module_head, *iter; int found, init; clientdata = clientdata; /* check to see if the circular list has been setup, if not, set it up */ if (swig_module.next==0) { /* Initialize the swig_module */ swig_module.type_initial = swig_type_initial; swig_module.cast_initial = swig_cast_initial; swig_module.next = &swig_module; init = 1; } else { init = 0; } /* Try and load any already created modules */ module_head = SWIG_GetModule(clientdata); if (!module_head) { /* This is the first module loaded for this interpreter */ /* so set the swig module into the interpreter */ SWIG_SetModule(clientdata, &swig_module); module_head = &swig_module; } else { /* the interpreter has loaded a SWIG module, but has it loaded this one? */ found=0; iter=module_head; do { if (iter==&swig_module) { found=1; break; } iter=iter->next; } while (iter!= module_head); /* if the is found in the list, then all is done and we may leave */ if (found) return; /* otherwise we must add out module into the list */ swig_module.next = module_head->next; module_head->next = &swig_module; } /* When multiple interpeters are used, a module could have already been initialized in a different interpreter, but not yet have a pointer in this interpreter. In this case, we do not want to continue adding types... everything should be set up already */ if (init == 0) return; /* Now work on filling in swig_module.types */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: size %d\n", swig_module.size); #endif for (i = 0; i < swig_module.size; ++i) { swig_type_info *type = 0; swig_type_info *ret; swig_cast_info *cast; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); #endif /* if there is another module already loaded */ if (swig_module.next != &swig_module) { type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); } if (type) { /* Overwrite clientdata field */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found type %s\n", type->name); #endif if (swig_module.type_initial[i]->clientdata) { type->clientdata = swig_module.type_initial[i]->clientdata; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); #endif } } else { type = swig_module.type_initial[i]; } /* Insert casting types */ cast = swig_module.cast_initial[i]; while (cast->type) { /* Don't need to add information already in the list */ ret = 0; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); #endif if (swig_module.next != &swig_module) { ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); #ifdef SWIGRUNTIME_DEBUG if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); #endif } if (ret) { if (type == swig_module.type_initial[i]) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: skip old type %s\n", ret->name); #endif cast->type = ret; ret = 0; } else { /* Check for casting already in the list */ swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); #ifdef SWIGRUNTIME_DEBUG if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); #endif if (!ocast) ret = 0; } } if (!ret) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); #endif if (type->cast) { type->cast->prev = cast; cast->next = type->cast; } type->cast = cast; } cast++; } /* Set entry in modules->types array equal to the type */ swig_module.types[i] = type; } swig_module.types[i] = 0; #ifdef SWIGRUNTIME_DEBUG printf("**** SWIG_InitializeModule: Cast List ******\n"); for (i = 0; i < swig_module.size; ++i) { int j = 0; swig_cast_info *cast = swig_module.cast_initial[i]; printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); while (cast->type) { printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); cast++; ++j; } printf("---- Total casts: %d\n",j); } printf("**** SWIG_InitializeModule: Cast List ******\n"); #endif } /* This function will propagate the clientdata field of type to * any new swig_type_info structures that have been added into the list * of equivalent types. It is like calling * SWIG_TypeClientData(type, clientdata) a second time. */ SWIGRUNTIME void SWIG_PropagateClientData(void) { size_t i; swig_cast_info *equiv; static int init_run = 0; if (init_run) return; init_run = 1; for (i = 0; i < swig_module.size; i++) { if (swig_module.types[i]->clientdata) { equiv = swig_module.types[i]->cast; while (equiv) { if (!equiv->converter) { if (equiv->type && !equiv->type->clientdata) SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); } equiv = equiv->next; } } } } #ifdef __cplusplus #if 0 { /* c-mode */ #endif } #endif #ifdef __cplusplus extern "C" { #endif /* Python-specific SWIG API */ #define SWIG_newvarlink() SWIG_Python_newvarlink() #define SWIG_addvarlink(p, name, get_attr, set_attr) SWIG_Python_addvarlink(p, name, get_attr, set_attr) #define SWIG_InstallConstants(d, constants) SWIG_Python_InstallConstants(d, constants) /* ----------------------------------------------------------------------------- * global variable support code. * ----------------------------------------------------------------------------- */ typedef struct swig_globalvar { char *name; /* Name of global variable */ PyObject *(*get_attr)(void); /* Return the current value */ int (*set_attr)(PyObject *); /* Set the value */ struct swig_globalvar *next; } swig_globalvar; typedef struct swig_varlinkobject { PyObject_HEAD swig_globalvar *vars; } swig_varlinkobject; SWIGINTERN PyObject * swig_varlink_repr(swig_varlinkobject *SWIGUNUSEDPARM(v)) { return PyString_FromString("<Swig global variables>"); } SWIGINTERN PyObject * swig_varlink_str(swig_varlinkobject *v) { PyObject *str = PyString_FromString("("); swig_globalvar *var; for (var = v->vars; var; var=var->next) { PyString_ConcatAndDel(&str,PyString_FromString(var->name)); if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(", ")); } PyString_ConcatAndDel(&str,PyString_FromString(")")); return str; } SWIGINTERN int swig_varlink_print(swig_varlinkobject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { PyObject *str = swig_varlink_str(v); fprintf(fp,"Swig global variables "); fprintf(fp,"%s\n", PyString_AsString(str)); Py_DECREF(str); return 0; } SWIGINTERN void swig_varlink_dealloc(swig_varlinkobject *v) { swig_globalvar *var = v->vars; while (var) { swig_globalvar *n = var->next; free(var->name); free(var); var = n; } } SWIGINTERN PyObject * swig_varlink_getattr(swig_varlinkobject *v, char *n) { PyObject *res = NULL; swig_globalvar *var = v->vars; while (var) { if (strcmp(var->name,n) == 0) { res = (*var->get_attr)(); break; } var = var->next; } if (res == NULL && !PyErr_Occurred()) { PyErr_SetString(PyExc_NameError,"Unknown C global variable"); } return res; } SWIGINTERN int swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) { int res = 1; swig_globalvar *var = v->vars; while (var) { if (strcmp(var->name,n) == 0) { res = (*var->set_attr)(p); break; } var = var->next; } if (res == 1 && !PyErr_Occurred()) { PyErr_SetString(PyExc_NameError,"Unknown C global variable"); } return res; } SWIGINTERN PyTypeObject* swig_varlink_type(void) { static char varlink__doc__[] = "Swig var link object"; static PyTypeObject varlink_type; static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { PyObject_HEAD_INIT(NULL) 0, /* Number of items in variable part (ob_size) */ (char *)"swigvarlink", /* Type name (tp_name) */ sizeof(swig_varlinkobject), /* Basic size (tp_basicsize) */ 0, /* Itemsize (tp_itemsize) */ (destructor) swig_varlink_dealloc, /* Deallocator (tp_dealloc) */ (printfunc) swig_varlink_print, /* Print (tp_print) */ (getattrfunc) swig_varlink_getattr, /* get attr (tp_getattr) */ (setattrfunc) swig_varlink_setattr, /* Set attr (tp_setattr) */ 0, /* tp_compare */ (reprfunc) swig_varlink_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc)swig_varlink_str, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0, /* tp_flags */ varlink__doc__, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ #if PY_VERSION_HEX >= 0x02020000 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */ #endif #if PY_VERSION_HEX >= 0x02030000 0, /* tp_del */ #endif #ifdef COUNT_ALLOCS 0,0,0,0 /* tp_alloc -> tp_next */ #endif }; varlink_type = tmp; varlink_type.ob_type = &PyType_Type; type_init = 1; } return &varlink_type; } /* Create a variable linking object for use later */ SWIGINTERN PyObject * SWIG_Python_newvarlink(void) { swig_varlinkobject *result = PyObject_NEW(swig_varlinkobject, swig_varlink_type()); if (result) { result->vars = 0; } return ((PyObject*) result); } SWIGINTERN void SWIG_Python_addvarlink(PyObject *p, char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) { swig_varlinkobject *v = (swig_varlinkobject *) p; swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar)); if (gv) { size_t size = strlen(name)+1; gv->name = (char *)malloc(size); if (gv->name) { strncpy(gv->name,name,size); gv->get_attr = get_attr; gv->set_attr = set_attr; gv->next = v->vars; } } v->vars = gv; } SWIGINTERN PyObject * SWIG_globals(void) { static PyObject *_SWIG_globals = 0; if (!_SWIG_globals) _SWIG_globals = SWIG_newvarlink(); return _SWIG_globals; } /* ----------------------------------------------------------------------------- * constants/methods manipulation * ----------------------------------------------------------------------------- */ /* Install Constants */ SWIGINTERN void SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) { PyObject *obj = 0; size_t i; for (i = 0; constants[i].type; ++i) { switch(constants[i].type) { case SWIG_PY_POINTER: obj = SWIG_NewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0); break; case SWIG_PY_BINARY: obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype)); break; default: obj = 0; break; } if (obj) { PyDict_SetItemString(d, constants[i].name, obj); Py_DECREF(obj); } } } /* -----------------------------------------------------------------------------*/ /* Fix SwigMethods to carry the callback ptrs when needed */ /* -----------------------------------------------------------------------------*/ SWIGINTERN void SWIG_Python_FixMethods(PyMethodDef *methods, swig_const_info *const_table, swig_type_info **types, swig_type_info **types_initial) { size_t i; for (i = 0; methods[i].ml_name; ++i) { const char *c = methods[i].ml_doc; if (c && (c = strstr(c, "swig_ptr: "))) { int j; swig_const_info *ci = 0; const char *name = c + 10; for (j = 0; const_table[j].type; ++j) { if (strncmp(const_table[j].name, name, strlen(const_table[j].name)) == 0) { ci = &(const_table[j]); break; } } if (ci) { size_t shift = (ci->ptype) - types; swig_type_info *ty = types_initial[shift]; size_t ldoc = (c - methods[i].ml_doc); size_t lptr = strlen(ty->name)+2*sizeof(void*)+2; char *ndoc = (char*)malloc(ldoc + lptr + 10); if (ndoc) { char *buff = ndoc; void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0; if (ptr) { strncpy(buff, methods[i].ml_doc, ldoc); buff += ldoc; strncpy(buff, "swig_ptr: ", 10); buff += 10; SWIG_PackVoidPtr(buff, ptr, ty->name, lptr); methods[i].ml_doc = ndoc; } } } } } } #ifdef __cplusplus } #endif /* -----------------------------------------------------------------------------* * Partial Init method * -----------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" #endif SWIGEXPORT void SWIG_init(void) { PyObject *m, *d; /* Fix SwigMethods to carry the callback ptrs when needed */ SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial); m = Py_InitModule((char *) SWIG_name, SwigMethods); d = PyModule_GetDict(m); SWIG_InitializeModule(0); SWIG_InstallConstants(d,swig_const_table); init_pygsl(); pygsl_module_for_error_treatment = m; }
{ "alphanum_fraction": 0.6712413198, "avg_line_length": 28.9711195073, "ext": "c", "hexsha": "be2bfb86925c9e0e8c5d6ce8f63fe00a5e074c4b", "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/swig_src/block_wrap.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/swig_src/block_wrap.c", "max_line_length": 150, "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/swig_src/block_wrap.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 173790, "size": 559751 }
/* specfunc/legendre_con.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * Copyright (C) 2010 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. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_poly.h> #include <gsl/gsl_sf_exp.h> #include <gsl/gsl_sf_trig.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_sf_ellint.h> #include <gsl/gsl_sf_pow_int.h> #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_sf_hyperg.h> #include <gsl/gsl_sf_legendre.h> #include "error.h" #include "legendre.h" #define Root_2OverPi_ 0.797884560802865355879892 #define locEPS (1000.0*GSL_DBL_EPSILON) /*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/ #define RECURSE_LARGE (1.0e-5*GSL_DBL_MAX) #define RECURSE_SMALL (1.0e+5*GSL_DBL_MIN) /* Continued fraction for f_{ell+1}/f_ell * f_ell := P^{-mu-ell}_{-1/2 + I tau}(x), x < 1.0 * * Uses standard CF method from Temme's book. */ static int conicalP_negmu_xlt1_CF1(const double mu, const int ell, const double tau, const double x, gsl_sf_result * result) { const double RECUR_BIG = GSL_SQRT_DBL_MAX; const int maxiter = 5000; int n = 1; double xi = x/(sqrt(1.0-x)*sqrt(1.0+x)); double Anm2 = 1.0; double Bnm2 = 0.0; double Anm1 = 0.0; double Bnm1 = 1.0; double a1 = 1.0; double b1 = 2.0*(mu + ell + 1.0) * xi; double An = b1*Anm1 + a1*Anm2; double Bn = b1*Bnm1 + a1*Bnm2; double an, bn; double fn = An/Bn; while(n < maxiter) { double old_fn; double del; n++; Anm2 = Anm1; Bnm2 = Bnm1; Anm1 = An; Bnm1 = Bn; an = tau*tau + (mu - 0.5 + ell + n)*(mu - 0.5 + ell + n); bn = 2.0*(ell + mu + n) * xi; An = bn*Anm1 + an*Anm2; Bn = bn*Bnm1 + an*Bnm2; if(fabs(An) > RECUR_BIG || fabs(Bn) > RECUR_BIG) { An /= RECUR_BIG; Bn /= RECUR_BIG; Anm1 /= RECUR_BIG; Bnm1 /= RECUR_BIG; Anm2 /= RECUR_BIG; Bnm2 /= RECUR_BIG; } old_fn = fn; fn = An/Bn; del = old_fn/fn; if(fabs(del - 1.0) < 2.0*GSL_DBL_EPSILON) break; } result->val = fn; result->err = 4.0 * GSL_DBL_EPSILON * (sqrt(n) + 1.0) * fabs(fn); if(n >= maxiter) GSL_ERROR ("error", GSL_EMAXITER); else return GSL_SUCCESS; } /* Continued fraction for f_{ell+1}/f_ell * f_ell := P^{-mu-ell}_{-1/2 + I tau}(x), x >= 1.0 * * Uses Gautschi (Euler) equivalent series. */ static int conicalP_negmu_xgt1_CF1(const double mu, const int ell, const double tau, const double x, gsl_sf_result * result) { const int maxk = 20000; const double gamma = 1.0-1.0/(x*x); const double pre = sqrt(x-1.0)*sqrt(x+1.0) / (x*(2.0*(ell+mu+1.0))); double tk = 1.0; double sum = 1.0; double rhok = 0.0; int k; for(k=1; k<maxk; k++) { double tlk = 2.0*(ell + mu + k); double l1k = (ell + mu - 0.5 + 1.0 + k); double ak = -(tau*tau + l1k*l1k)/(tlk*(tlk+2.0)) * gamma; rhok = -ak*(1.0 + rhok)/(1.0 + ak*(1.0 + rhok)); tk *= rhok; sum += tk; if(fabs(tk/sum) < GSL_DBL_EPSILON) break; } result->val = pre * sum; result->err = fabs(pre * tk); result->err += 2.0 * GSL_DBL_EPSILON * (sqrt(k) + 1.0) * fabs(pre*sum); if(k >= maxk) GSL_ERROR ("error", GSL_EMAXITER); else return GSL_SUCCESS; } /* Implementation of large negative mu asymptotic * [Dunster, Proc. Roy. Soc. Edinburgh 119A, 311 (1991), p. 326] */ inline static double olver_U1(double beta2, double p) { return (p-1.0)/(24.0*(1.0+beta2)) * (3.0 + beta2*(2.0 + 5.0*p*(1.0+p))); } inline static double olver_U2(double beta2, double p) { double beta4 = beta2*beta2; double p2 = p*p; double poly1 = 4.0*beta4 + 84.0*beta2 - 63.0; double poly2 = 16.0*beta4 + 90.0*beta2 - 81.0; double poly3 = beta2*p2*(97.0*beta2 - 432.0 + 77.0*p*(beta2-6.0) - 385.0*beta2*p2*(1.0 + p)); return (1.0-p)/(1152.0*(1.0+beta2)) * (poly1 + poly2 + poly3); } static const double U3c1[] = { -1307.0, -1647.0, 3375.0, 3675.0 }; static const double U3c2[] = { 29366.0, 35835.0, -252360.0, -272630.0, 276810.0, 290499.0 }; static const double U3c3[] = { -29748.0, -8840.0, 1725295.0, 1767025.0, -7313470.0, -754778.0, 6309875.0, 6480045.0 }; static const double U3c4[] = { 2696.0, -16740.0, -524250.0, -183975.0, 14670540.0, 14172939.0, -48206730.0, -48461985.0, 36756720.0, 37182145.0 }; static const double U3c5[] = { 9136.0, 22480.0, 12760.0, -252480.0, -4662165.0, -1705341.0, 92370135.0, 86244015.0, -263678415.0, -260275015.0, 185910725.0, 185910725.0 }; #if 0 static double olver_U3(double beta2, double p) { double beta4 = beta2*beta2; double beta6 = beta4*beta2; double opb2s = (1.0+beta2)*(1.0+beta2); double den = 39813120.0 * opb2s*opb2s; double poly1 = gsl_poly_eval(U3c1, 4, p); double poly2 = gsl_poly_eval(U3c2, 6, p); double poly3 = gsl_poly_eval(U3c3, 8, p); double poly4 = gsl_poly_eval(U3c4, 10, p); double poly5 = gsl_poly_eval(U3c5, 12, p); return (p-1.0)*( 1215.0*poly1 + 324.0*beta2*poly2 + 54.0*beta4*poly3 + 12.0*beta6*poly4 + beta4*beta4*poly5 ) / den; } #endif /* 0 */ /* Large negative mu asymptotic * P^{-mu}_{-1/2 + I tau}, mu -> Inf * |x| < 1 * * [Dunster, Proc. Roy. Soc. Edinburgh 119A, 311 (1991), p. 326] */ int gsl_sf_conicalP_xlt1_large_neg_mu_e(double mu, double tau, double x, gsl_sf_result * result, double * ln_multiplier) { double beta = tau/mu; double beta2 = beta*beta; double S = beta * acos((1.0-beta2)/(1.0+beta2)); double p = x/sqrt(beta2*(1.0-x*x) + 1.0); gsl_sf_result lg_mup1; int lg_stat = gsl_sf_lngamma_e(mu+1.0, &lg_mup1); double ln_pre_1 = 0.5*mu*(S - log(1.0+beta2) + log((1.0-p)/(1.0+p))) - lg_mup1.val; double ln_pre_2 = -0.25 * log(1.0 + beta2*(1.0-x)); double ln_pre_3 = -tau * atan(p*beta); double ln_pre = ln_pre_1 + ln_pre_2 + ln_pre_3; double sum = 1.0 - olver_U1(beta2, p)/mu + olver_U2(beta2, p)/(mu*mu); if(sum == 0.0) { result->val = 0.0; result->err = 0.0; *ln_multiplier = 0.0; return GSL_SUCCESS; } else { int stat_e = gsl_sf_exp_mult_e(ln_pre, sum, result); if(stat_e != GSL_SUCCESS) { result->val = sum; result->err = 2.0 * GSL_DBL_EPSILON * fabs(sum); *ln_multiplier = ln_pre; } else { *ln_multiplier = 0.0; } return lg_stat; } } /* Implementation of large tau asymptotic * * A_n^{-mu}, B_n^{-mu} [Olver, p.465, 469] */ inline static double olver_B0_xi(double mu, double xi) { return (1.0 - 4.0*mu*mu)/(8.0*xi) * (1.0/tanh(xi) - 1.0/xi); } static double olver_A1_xi(double mu, double xi, double x) { double B = olver_B0_xi(mu, xi); double psi; if(fabs(x - 1.0) < GSL_ROOT4_DBL_EPSILON) { double y = x - 1.0; double s = -1.0/3.0 + y*(2.0/15.0 - y *(61.0/945.0 - 452.0/14175.0*y)); psi = (4.0*mu*mu - 1.0)/16.0 * s; } else { psi = (4.0*mu*mu - 1.0)/16.0 * (1.0/(x*x-1.0) - 1.0/(xi*xi)); } return 0.5*xi*xi*B*B + (mu+0.5)*B - psi + mu/6.0*(0.25 - mu*mu); } inline static double olver_B0_th(double mu, double theta) { return -(1.0 - 4.0*mu*mu)/(8.0*theta) * (1.0/tan(theta) - 1.0/theta); } static double olver_A1_th(double mu, double theta, double x) { double B = olver_B0_th(mu, theta); double psi; if(fabs(x - 1.0) < GSL_ROOT4_DBL_EPSILON) { double y = 1.0 - x; double s = -1.0/3.0 + y*(2.0/15.0 - y *(61.0/945.0 - 452.0/14175.0*y)); psi = (4.0*mu*mu - 1.0)/16.0 * s; } else { psi = (4.0*mu*mu - 1.0)/16.0 * (1.0/(x*x-1.0) + 1.0/(theta*theta)); } return -0.5*theta*theta*B*B + (mu+0.5)*B - psi + mu/6.0*(0.25 - mu*mu); } /* Large tau uniform asymptotics * P^{-mu}_{-1/2 + I tau} * 1 < x * tau -> Inf * [Olver, p. 469] */ int gsl_sf_conicalP_xgt1_neg_mu_largetau_e(const double mu, const double tau, const double x, double acosh_x, gsl_sf_result * result, double * ln_multiplier) { double xi = acosh_x; double ln_xi_pre; double ln_pre; double sumA, sumB, sum; double arg; gsl_sf_result J_mup1; gsl_sf_result J_mu; double J_mum1; if(xi < GSL_ROOT4_DBL_EPSILON) { ln_xi_pre = -xi*xi/6.0; /* log(1.0 - xi*xi/6.0) */ } else { gsl_sf_result lnshxi; gsl_sf_lnsinh_e(xi, &lnshxi); ln_xi_pre = log(xi) - lnshxi.val; /* log(xi/sinh(xi) */ } ln_pre = 0.5*ln_xi_pre - mu*log(tau); arg = tau*xi; gsl_sf_bessel_Jnu_e(mu + 1.0, arg, &J_mup1); gsl_sf_bessel_Jnu_e(mu, arg, &J_mu); J_mum1 = -J_mup1.val + 2.0*mu/arg*J_mu.val; /* careful of mu < 1 */ sumA = 1.0 - olver_A1_xi(-mu, xi, x)/(tau*tau); sumB = olver_B0_xi(-mu, xi); sum = J_mu.val * sumA - xi/tau * J_mum1 * sumB; if(sum == 0.0) { result->val = 0.0; result->err = 0.0; *ln_multiplier = 0.0; return GSL_SUCCESS; } else { int stat_e = gsl_sf_exp_mult_e(ln_pre, sum, result); if(stat_e != GSL_SUCCESS) { result->val = sum; result->err = 2.0 * GSL_DBL_EPSILON * fabs(sum); *ln_multiplier = ln_pre; } else { *ln_multiplier = 0.0; } return GSL_SUCCESS; } } /* Large tau uniform asymptotics * P^{-mu}_{-1/2 + I tau} * -1 < x < 1 * tau -> Inf * [Olver, p. 473] */ int gsl_sf_conicalP_xlt1_neg_mu_largetau_e(const double mu, const double tau, const double x, const double acos_x, gsl_sf_result * result, double * ln_multiplier) { double theta = acos_x; double ln_th_pre; double ln_pre; double sumA, sumB, sum, sumerr; double arg; gsl_sf_result I_mup1, I_mu; double I_mum1; if(theta < GSL_ROOT4_DBL_EPSILON) { ln_th_pre = theta*theta/6.0; /* log(1.0 + theta*theta/6.0) */ } else { ln_th_pre = log(theta/sin(theta)); } ln_pre = 0.5 * ln_th_pre - mu * log(tau); arg = tau*theta; gsl_sf_bessel_Inu_e(mu + 1.0, arg, &I_mup1); gsl_sf_bessel_Inu_e(mu, arg, &I_mu); I_mum1 = I_mup1.val + 2.0*mu/arg * I_mu.val; /* careful of mu < 1 */ sumA = 1.0 - olver_A1_th(-mu, theta, x)/(tau*tau); sumB = olver_B0_th(-mu, theta); sum = I_mu.val * sumA - theta/tau * I_mum1 * sumB; sumerr = fabs(I_mu.err * sumA); sumerr += fabs(I_mup1.err * theta/tau * sumB); sumerr += fabs(I_mu.err * theta/tau * sumB * 2.0 * mu/arg); if(sum == 0.0) { result->val = 0.0; result->err = 0.0; *ln_multiplier = 0.0; return GSL_SUCCESS; } else { int stat_e = gsl_sf_exp_mult_e(ln_pre, sum, result); if(stat_e != GSL_SUCCESS) { result->val = sum; result->err = sumerr; result->err += GSL_DBL_EPSILON * fabs(sum); *ln_multiplier = ln_pre; } else { *ln_multiplier = 0.0; } return GSL_SUCCESS; } } /* Hypergeometric function which appears in the * large x expansion below: * * 2F1(1/4 - mu/2 - I tau/2, 3/4 - mu/2 - I tau/2, 1 - I tau, y) * * Note that for the usage below y = 1/x^2; */ static int conicalP_hyperg_large_x(const double mu, const double tau, const double y, double * reF, double * imF) { const int kmax = 1000; const double re_a = 0.25 - 0.5*mu; const double re_b = 0.75 - 0.5*mu; const double re_c = 1.0; const double im_a = -0.5*tau; const double im_b = -0.5*tau; const double im_c = -tau; double re_sum = 1.0; double im_sum = 0.0; double re_term = 1.0; double im_term = 0.0; int k; for(k=1; k<=kmax; k++) { double re_ak = re_a + k - 1.0; double re_bk = re_b + k - 1.0; double re_ck = re_c + k - 1.0; double im_ak = im_a; double im_bk = im_b; double im_ck = im_c; double den = re_ck*re_ck + im_ck*im_ck; double re_multiplier = ((re_ak*re_bk - im_ak*im_bk)*re_ck + im_ck*(im_ak*re_bk + re_ak*im_bk)) / den; double im_multiplier = ((im_ak*re_bk + re_ak*im_bk)*re_ck - im_ck*(re_ak*re_bk - im_ak*im_bk)) / den; double re_tmp = re_multiplier*re_term - im_multiplier*im_term; double im_tmp = im_multiplier*re_term + re_multiplier*im_term; double asum = fabs(re_sum) + fabs(im_sum); re_term = y/k * re_tmp; im_term = y/k * im_tmp; if(fabs(re_term/asum) < GSL_DBL_EPSILON && fabs(im_term/asum) < GSL_DBL_EPSILON) break; re_sum += re_term; im_sum += im_term; } *reF = re_sum; *imF = im_sum; if(k == kmax) GSL_ERROR ("error", GSL_EMAXITER); else return GSL_SUCCESS; } /* P^{mu}_{-1/2 + I tau} * x->Inf */ int gsl_sf_conicalP_large_x_e(const double mu, const double tau, const double x, gsl_sf_result * result, double * ln_multiplier) { /* 2F1 term */ double y = ( x < 0.5*GSL_SQRT_DBL_MAX ? 1.0/(x*x) : 0.0 ); double reF, imF; int stat_F = conicalP_hyperg_large_x(mu, tau, y, &reF, &imF); /* f = Gamma(+i tau)/Gamma(1/2 - mu + i tau) * FIXME: shift so it's better for tau-> 0 */ gsl_sf_result lgr_num, lgth_num; gsl_sf_result lgr_den, lgth_den; int stat_gn = gsl_sf_lngamma_complex_e(0.0,tau,&lgr_num,&lgth_num); int stat_gd = gsl_sf_lngamma_complex_e(0.5-mu,tau,&lgr_den,&lgth_den); double angle = lgth_num.val - lgth_den.val + atan2(imF,reF); double lnx = log(x); double lnxp1 = log(x+1.0); double lnxm1 = log(x-1.0); double lnpre_const = 0.5*M_LN2 - 0.5*M_LNPI; double lnpre_comm = (mu-0.5)*lnx - 0.5*mu*(lnxp1 + lnxm1); double lnpre_err = GSL_DBL_EPSILON * (0.5*M_LN2 + 0.5*M_LNPI) + GSL_DBL_EPSILON * fabs((mu-0.5)*lnx) + GSL_DBL_EPSILON * fabs(0.5*mu)*(fabs(lnxp1)+fabs(lnxm1)); /* result = pre*|F|*|f| * cos(angle - tau * (log(x)+M_LN2)) */ gsl_sf_result cos_result; int stat_cos = gsl_sf_cos_e(angle + tau*(log(x) + M_LN2), &cos_result); int status = GSL_ERROR_SELECT_4(stat_cos, stat_gd, stat_gn, stat_F); if(cos_result.val == 0.0) { result->val = 0.0; result->err = 0.0; return status; } else { double lnFf_val = 0.5*log(reF*reF+imF*imF) + lgr_num.val - lgr_den.val; double lnFf_err = lgr_num.err + lgr_den.err + GSL_DBL_EPSILON * fabs(lnFf_val); double lnnoc_val = lnpre_const + lnpre_comm + lnFf_val; double lnnoc_err = lnpre_err + lnFf_err + GSL_DBL_EPSILON * fabs(lnnoc_val); int stat_e = gsl_sf_exp_mult_err_e(lnnoc_val, lnnoc_err, cos_result.val, cos_result.err, result); if(stat_e == GSL_SUCCESS) { *ln_multiplier = 0.0; } else { result->val = cos_result.val; result->err = cos_result.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); *ln_multiplier = lnnoc_val; } return status; } } /* P^{mu}_{-1/2 + I tau} first hypergeometric representation * -1 < x < 1 * This is more effective for |x| small, however it will work w/o * reservation for any x < 0 because everything is positive * definite in that case. * * [Kolbig, (3)] (note typo in args of gamma functions) * [Bateman, (22)] (correct form) */ static int conicalP_xlt1_hyperg_A(double mu, double tau, double x, gsl_sf_result * result) { double x2 = x*x; double err_amp = 1.0 + 1.0/(GSL_DBL_EPSILON + fabs(1.0-fabs(x))); double pre_val = M_SQRTPI / pow(0.5*sqrt(1-x2), mu); double pre_err = err_amp * GSL_DBL_EPSILON * (fabs(mu)+1.0) * fabs(pre_val) ; gsl_sf_result ln_g1, ln_g2, arg_g1, arg_g2; gsl_sf_result F1, F2; gsl_sf_result pre1, pre2; double t1_val, t1_err; double t2_val, t2_err; int stat_F1 = gsl_sf_hyperg_2F1_conj_e(0.25 - 0.5*mu, 0.5*tau, 0.5, x2, &F1); int stat_F2 = gsl_sf_hyperg_2F1_conj_e(0.75 - 0.5*mu, 0.5*tau, 1.5, x2, &F2); int status = GSL_ERROR_SELECT_2(stat_F1, stat_F2); gsl_sf_lngamma_complex_e(0.75 - 0.5*mu, -0.5*tau, &ln_g1, &arg_g1); gsl_sf_lngamma_complex_e(0.25 - 0.5*mu, -0.5*tau, &ln_g2, &arg_g2); gsl_sf_exp_err_e(-2.0*ln_g1.val, 2.0*ln_g1.err, &pre1); gsl_sf_exp_err_e(-2.0*ln_g2.val, 2.0*ln_g2.err, &pre2); pre2.val *= -2.0*x; pre2.err *= 2.0*fabs(x); pre2.err += GSL_DBL_EPSILON * fabs(pre2.val); t1_val = pre1.val * F1.val; t1_err = fabs(pre1.val) * F1.err + pre1.err * fabs(F1.val); t2_val = pre2.val * F2.val; t2_err = fabs(pre2.val) * F2.err + pre2.err * fabs(F2.val); result->val = pre_val * (t1_val + t2_val); result->err = pre_val * (t1_err + t2_err); result->err += pre_err * fabs(t1_val + t2_val); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return status; } /* P^{mu}_{-1/2 + I tau} * defining hypergeometric representation * [Abramowitz+Stegun, 8.1.2] * 1 < x < 3 * effective for x near 1 * */ #if 0 static int conicalP_def_hyperg(double mu, double tau, double x, double * result) { double F; int stat_F = gsl_sf_hyperg_2F1_conj_renorm_e(0.5, tau, 1.0-mu, 0.5*(1.0-x), &F); *result = pow((x+1.0)/(x-1.0), 0.5*mu) * F; return stat_F; } #endif /* 0 */ /* P^{mu}_{-1/2 + I tau} second hypergeometric representation * [Zhurina+Karmazina, (3.1)] * -1 < x < 3 * effective for x near 1 * */ #if 0 static int conicalP_xnear1_hyperg_C(double mu, double tau, double x, double * result) { double ln_pre, arg_pre; double ln_g1, arg_g1; double ln_g2, arg_g2; double F; int stat_F = gsl_sf_hyperg_2F1_conj_renorm_e(0.5+mu, tau, 1.0+mu, 0.5*(1.0-x), &F); gsl_sf_lngamma_complex_e(0.5+mu, tau, &ln_g1, &arg_g1); gsl_sf_lngamma_complex_e(0.5-mu, tau, &ln_g2, &arg_g2); ln_pre = mu*M_LN2 - 0.5*mu*log(fabs(x*x-1.0)) + ln_g1 - ln_g2; arg_pre = arg_g1 - arg_g2; *result = exp(ln_pre) * F; return stat_F; } #endif /* 0 */ /* V0, V1 from Kolbig, m = 0 */ static int conicalP_0_V(const double t, const double f, const double tau, const double sgn, double * V0, double * V1) { double C[8]; double T[8]; double H[8]; double V[12]; int i; T[0] = 1.0; H[0] = 1.0; V[0] = 1.0; for(i=1; i<=7; i++) { T[i] = T[i-1] * t; H[i] = H[i-1] * (t*f); } for(i=1; i<=11; i++) { V[i] = V[i-1] * tau; } C[0] = 1.0; C[1] = (H[1]-1.0)/(8.0*T[1]); C[2] = (9.0*H[2] + 6.0*H[1] - 15.0 - sgn*8.0*T[2])/(128.0*T[2]); C[3] = 5.0*(15.0*H[3] + 27.0*H[2] + 21.0*H[1] - 63.0 - sgn*T[2]*(16.0*H[1]+24.0))/(1024.0*T[3]); C[4] = 7.0*(525.0*H[4] + 1500.0*H[3] + 2430.0*H[2] + 1980.0*H[1] - 6435.0 + 192.0*T[4] - sgn*T[2]*(720.0*H[2]+1600.0*H[1]+2160.0) ) / (32768.0*T[4]); C[5] = 21.0*(2835.0*H[5] + 11025.0*H[4] + 24750.0*H[3] + 38610.0*H[2] + 32175.0*H[1] - 109395.0 + T[4]*(1984.0*H[1]+4032.0) - sgn*T[2]*(4800.0*H[3]+15120.0*H[2]+26400.0*H[1]+34320.0) ) / (262144.0*T[5]); C[6] = 11.0*(218295.0*H[6] + 1071630.0*H[5] + 3009825.0*H[4] + 6142500.0*H[3] + 9398025.0*H[2] + 7936110.0*H[1] - 27776385.0 + T[4]*(254016.0*H[2]+749952.0*H[1]+1100736.0) - sgn*T[2]*(441000.0*H[4] + 1814400.0*H[3] + 4127760.0*H[2] + 6552000.0*H[1] + 8353800.0 + 31232.0*T[4] ) ) / (4194304.0*T[6]); *V0 = C[0] + (-4.0*C[3]/T[1]+C[4])/V[4] + (-192.0*C[5]/T[3]+144.0*C[6]/T[2])/V[8] + sgn * (-C[2]/V[2] + (-24.0*C[4]/T[2]+12.0*C[5]/T[1]-C[6])/V[6] + (-1920.0*C[6]/T[4])/V[10] ); *V1 = C[1]/V[1] + (8.0*(C[3]/T[2]-C[4]/T[1])+C[5])/V[5] + (384.0*C[5]/T[4] - 768.0*C[6]/T[3])/V[9] + sgn * ((2.0*C[2]/T[1]-C[3])/V[3] + (48.0*C[4]/T[3]-72.0*C[5]/T[2] + 18.0*C[6]/T[1])/V[7] + (3840.0*C[6]/T[5])/V[11] ); return GSL_SUCCESS; } /* V0, V1 from Kolbig, m = 1 */ static int conicalP_1_V(const double t, const double f, const double tau, const double sgn, double * V0, double * V1) { double Cm1; double C[8]; double T[8]; double H[8]; double V[12]; int i; T[0] = 1.0; H[0] = 1.0; V[0] = 1.0; for(i=1; i<=7; i++) { T[i] = T[i-1] * t; H[i] = H[i-1] * (t*f); } for(i=1; i<=11; i++) { V[i] = V[i-1] * tau; } Cm1 = -1.0; C[0] = 3.0*(1.0-H[1])/(8.0*T[1]); C[1] = (-15.0*H[2]+6.0*H[1]+9.0+sgn*8.0*T[2])/(128.0*T[2]); C[2] = 3.0*(-35.0*H[3] - 15.0*H[2] + 15.0*H[1] + 35.0 + sgn*T[2]*(32.0*H[1]+8.0))/(1024.0*T[3]); C[3] = (-4725.0*H[4] - 6300.0*H[3] - 3150.0*H[2] + 3780.0*H[1] + 10395.0 -1216.0*T[4] + sgn*T[2]*(6000.0*H[2]+5760.0*H[1]+1680.0)) / (32768.0*T[4]); C[4] = 7.0*(-10395.0*H[5] - 23625.0*H[4] - 28350.0*H[3] - 14850.0*H[2] +19305.0*H[1] + 57915.0 - T[4]*(6336.0*H[1]+6080.0) + sgn*T[2]*(16800.0*H[3] + 30000.0*H[2] + 25920.0*H[1] + 7920.0) ) / (262144.0*T[5]); C[5] = (-2837835.0*H[6] - 9168390.0*H[5] - 16372125.0*H[4] - 18918900*H[3] -10135125.0*H[2] + 13783770.0*H[1] + 43648605.0 -T[4]*(3044160.0*H[2] + 5588352.0*H[1] + 4213440.0) +sgn*T[2]*(5556600.0*H[4] + 14817600.0*H[3] + 20790000.0*H[2] + 17297280.0*H[1] + 5405400.0 + 323072.0*T[4] ) ) / (4194304.0*T[6]); C[6] = 0.0; *V0 = C[0] + (-4.0*C[3]/T[1]+C[4])/V[4] + (-192.0*C[5]/T[3]+144.0*C[6]/T[2])/V[8] + sgn * (-C[2]/V[2] + (-24.0*C[4]/T[2]+12.0*C[5]/T[1]-C[6])/V[6] ); *V1 = C[1]/V[1] + (8.0*(C[3]/T[2]-C[4]/T[1])+C[5])/V[5] + (384.0*C[5]/T[4] - 768.0*C[6]/T[3])/V[9] + sgn * (Cm1*V[1] + (2.0*C[2]/T[1]-C[3])/V[3] + (48.0*C[4]/T[3]-72.0*C[5]/T[2] + 18.0*C[6]/T[1])/V[7] ); return GSL_SUCCESS; } /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ /* P^0_{-1/2 + I lambda} */ int gsl_sf_conicalP_0_e(const double lambda, const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x <= -1.0) { DOMAIN_ERROR(result); } else if(x == 1.0) { result->val = 1.0; result->err = 0.0; return GSL_SUCCESS; } else if(lambda == 0.0) { gsl_sf_result K; int stat_K; if(x < 1.0) { const double th = acos(x); const double s = sin(0.5*th); stat_K = gsl_sf_ellint_Kcomp_e(s, GSL_MODE_DEFAULT, &K); result->val = 2.0/M_PI * K.val; result->err = 2.0/M_PI * K.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_K; } else { const double xi = acosh(x); const double c = cosh(0.5*xi); const double t = tanh(0.5*xi); stat_K = gsl_sf_ellint_Kcomp_e(t, GSL_MODE_DEFAULT, &K); result->val = 2.0/M_PI / c * K.val; result->err = 2.0/M_PI / c * K.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_K; } } else if( (x <= 0.0 && lambda < 1000.0) || (x < 0.1 && lambda < 17.0) || (x < 0.2 && lambda < 5.0 ) ) { return conicalP_xlt1_hyperg_A(0.0, lambda, x, result); } else if( (x <= 0.2 && lambda < 17.0) || (x <= 1.5 && lambda < 20.0) ) { return gsl_sf_hyperg_2F1_conj_e(0.5, lambda, 1.0, (1.0-x)/2, result); } else if(1.5 < x && lambda < GSL_MAX(x,20.0)) { gsl_sf_result P; double lm; int stat_P = gsl_sf_conicalP_large_x_e(0.0, lambda, x, &P, &lm ); int stat_e = gsl_sf_exp_mult_err_e(lm, 2.0*GSL_DBL_EPSILON * fabs(lm), P.val, P.err, result); return GSL_ERROR_SELECT_2(stat_e, stat_P); } else { double V0, V1; if(x < 1.0) { double th = acos(x); double sth = sqrt(1.0-x*x); /* sin(th) */ gsl_sf_result I0, I1; int stat_I0 = gsl_sf_bessel_I0_scaled_e(th * lambda, &I0); int stat_I1 = gsl_sf_bessel_I1_scaled_e(th * lambda, &I1); int stat_I = GSL_ERROR_SELECT_2(stat_I0, stat_I1); int stat_V = conicalP_0_V(th, x/sth, lambda, -1.0, &V0, &V1); double bessterm = V0 * I0.val + V1 * I1.val; double besserr = fabs(V0) * I0.err + fabs(V1) * I1.err; double arg1 = th*lambda; double sqts = sqrt(th/sth); int stat_e = gsl_sf_exp_mult_err_e(arg1, 4.0 * GSL_DBL_EPSILON * fabs(arg1), sqts * bessterm, sqts * besserr, result); return GSL_ERROR_SELECT_3(stat_e, stat_V, stat_I); } else { double sh = sqrt(x-1.0)*sqrt(x+1.0); /* sinh(xi) */ double xi = log(x + sh); /* xi = acosh(x) */ gsl_sf_result J0, J1; int stat_J0 = gsl_sf_bessel_J0_e(xi * lambda, &J0); int stat_J1 = gsl_sf_bessel_J1_e(xi * lambda, &J1); int stat_J = GSL_ERROR_SELECT_2(stat_J0, stat_J1); int stat_V = conicalP_0_V(xi, x/sh, lambda, 1.0, &V0, &V1); double bessterm = V0 * J0.val + V1 * J1.val; double besserr = fabs(V0) * J0.err + fabs(V1) * J1.err; double pre_val = sqrt(xi/sh); double pre_err = 2.0 * fabs(pre_val); result->val = pre_val * bessterm; result->err = pre_val * besserr; result->err += pre_err * fabs(bessterm); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_ERROR_SELECT_2(stat_V, stat_J); } } } /* P^1_{-1/2 + I lambda} */ int gsl_sf_conicalP_1_e(const double lambda, const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x <= -1.0) { DOMAIN_ERROR(result); } else if(lambda == 0.0) { gsl_sf_result K, E; int stat_K, stat_E; if(x == 1.0) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else if(x < 1.0) { if(1.0-x < GSL_SQRT_DBL_EPSILON) { double err_amp = GSL_MAX_DBL(1.0, 1.0/(GSL_DBL_EPSILON + fabs(1.0-x))); result->val = 0.25/M_SQRT2 * sqrt(1.0-x) * (1.0 + 5.0/16.0 * (1.0-x)); result->err = err_amp * 3.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { const double th = acos(x); const double s = sin(0.5*th); const double c2 = 1.0 - s*s; const double sth = sin(th); const double pre = 2.0/(M_PI*sth); stat_K = gsl_sf_ellint_Kcomp_e(s, GSL_MODE_DEFAULT, &K); stat_E = gsl_sf_ellint_Ecomp_e(s, GSL_MODE_DEFAULT, &E); result->val = pre * (E.val - c2 * K.val); result->err = pre * (E.err + fabs(c2) * K.err); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_ERROR_SELECT_2(stat_K, stat_E); } } else { if(x-1.0 < GSL_SQRT_DBL_EPSILON) { double err_amp = GSL_MAX_DBL(1.0, 1.0/(GSL_DBL_EPSILON + fabs(1.0-x))); result->val = -0.25/M_SQRT2 * sqrt(x-1.0) * (1.0 - 5.0/16.0 * (x-1.0)); result->err = err_amp * 3.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { const double xi = acosh(x); const double c = cosh(0.5*xi); const double t = tanh(0.5*xi); const double sxi = sinh(xi); const double pre = 2.0/(M_PI*sxi) * c; stat_K = gsl_sf_ellint_Kcomp_e(t, GSL_MODE_DEFAULT, &K); stat_E = gsl_sf_ellint_Ecomp_e(t, GSL_MODE_DEFAULT, &E); result->val = pre * (E.val - K.val); result->err = pre * (E.err + K.err); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_ERROR_SELECT_2(stat_K, stat_E); } } } else if( (x <= 0.0 && lambda < 1000.0) || (x < 0.1 && lambda < 17.0) || (x < 0.2 && lambda < 5.0 ) ) { return conicalP_xlt1_hyperg_A(1.0, lambda, x, result); } else if( (x <= 0.2 && lambda < 17.0) || (x < 1.5 && lambda < 20.0) ) { const double arg = fabs(x*x - 1.0); const double sgn = GSL_SIGN(1.0 - x); const double pre = 0.5*(lambda*lambda + 0.25) * sgn * sqrt(arg); gsl_sf_result F; int stat_F = gsl_sf_hyperg_2F1_conj_e(1.5, lambda, 2.0, (1.0-x)/2, &F); result->val = pre * F.val; result->err = fabs(pre) * F.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_F; } else if(1.5 <= x && lambda < GSL_MAX(x,20.0)) { gsl_sf_result P; double lm; int stat_P = gsl_sf_conicalP_large_x_e(1.0, lambda, x, &P, &lm ); int stat_e = gsl_sf_exp_mult_err_e(lm, 2.0 * GSL_DBL_EPSILON * fabs(lm), P.val, P.err, result); return GSL_ERROR_SELECT_2(stat_e, stat_P); } else { double V0, V1; if(x < 1.0) { const double sqrt_1mx = sqrt(1.0 - x); const double sqrt_1px = sqrt(1.0 + x); const double th = acos(x); const double sth = sqrt_1mx * sqrt_1px; /* sin(th) */ gsl_sf_result I0, I1; int stat_I0 = gsl_sf_bessel_I0_scaled_e(th * lambda, &I0); int stat_I1 = gsl_sf_bessel_I1_scaled_e(th * lambda, &I1); int stat_I = GSL_ERROR_SELECT_2(stat_I0, stat_I1); int stat_V = conicalP_1_V(th, x/sth, lambda, -1.0, &V0, &V1); double bessterm = V0 * I0.val + V1 * I1.val; double besserr = fabs(V0) * I0.err + fabs(V1) * I1.err + 2.0 * GSL_DBL_EPSILON * fabs(V0 * I0.val) + 2.0 * GSL_DBL_EPSILON * fabs(V1 * I1.val); double arg1 = th * lambda; double sqts = sqrt(th/sth); int stat_e = gsl_sf_exp_mult_err_e(arg1, 2.0 * GSL_DBL_EPSILON * fabs(arg1), sqts * bessterm, sqts * besserr, result); result->err *= 1.0/sqrt_1mx; return GSL_ERROR_SELECT_3(stat_e, stat_V, stat_I); } else { const double sqrt_xm1 = sqrt(x - 1.0); const double sqrt_xp1 = sqrt(x + 1.0); const double sh = sqrt_xm1 * sqrt_xp1; /* sinh(xi) */ const double xi = log(x + sh); /* xi = acosh(x) */ const double xi_lam = xi * lambda; gsl_sf_result J0, J1; const int stat_J0 = gsl_sf_bessel_J0_e(xi_lam, &J0); const int stat_J1 = gsl_sf_bessel_J1_e(xi_lam, &J1); const int stat_J = GSL_ERROR_SELECT_2(stat_J0, stat_J1); const int stat_V = conicalP_1_V(xi, x/sh, lambda, 1.0, &V0, &V1); const double bessterm = V0 * J0.val + V1 * J1.val; const double besserr = fabs(V0) * J0.err + fabs(V1) * J1.err + 512.0 * 2.0 * GSL_DBL_EPSILON * fabs(V0 * J0.val) + 512.0 * 2.0 * GSL_DBL_EPSILON * fabs(V1 * J1.val) + GSL_DBL_EPSILON * fabs(xi_lam * V0 * J1.val) + GSL_DBL_EPSILON * fabs(xi_lam * V1 * J0.val); const double pre = sqrt(xi/sh); result->val = pre * bessterm; result->err = pre * besserr * sqrt_xp1 / sqrt_xm1; result->err += 4.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_ERROR_SELECT_2(stat_V, stat_J); } } } /* P^{1/2}_{-1/2 + I lambda} (x) * [Abramowitz+Stegun 8.6.8, 8.6.12] * checked OK [GJ] Fri May 8 12:24:36 MDT 1998 */ int gsl_sf_conicalP_half_e(const double lambda, const double x, gsl_sf_result * result ) { /* CHECK_POINTER(result) */ if(x <= -1.0) { DOMAIN_ERROR(result); } else if(x < 1.0) { double err_amp = 1.0 + 1.0/(GSL_DBL_EPSILON + fabs(1.0-fabs(x))); double ac = acos(x); double den = sqrt(sqrt(1.0-x)*sqrt(1.0+x)); result->val = Root_2OverPi_ / den * cosh(ac * lambda); result->err = err_amp * 3.0 * GSL_DBL_EPSILON * fabs(result->val); result->err *= fabs(ac * lambda) + 1.0; return GSL_SUCCESS; } else if(x == 1.0) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else { /* x > 1 */ double err_amp = 1.0 + 1.0/(GSL_DBL_EPSILON + fabs(1.0-fabs(x))); double sq_term = sqrt(x-1.0)*sqrt(x+1.0); double ln_term = log(x + sq_term); double den = sqrt(sq_term); double carg_val = lambda * ln_term; double carg_err = 2.0 * GSL_DBL_EPSILON * fabs(carg_val); gsl_sf_result cos_result; int stat_cos = gsl_sf_cos_err_e(carg_val, carg_err, &cos_result); result->val = Root_2OverPi_ / den * cos_result.val; result->err = err_amp * Root_2OverPi_ / den * cos_result.err; result->err += 4.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_cos; } } /* P^{-1/2}_{-1/2 + I lambda} (x) * [Abramowitz+Stegun 8.6.9, 8.6.14] * checked OK [GJ] Fri May 8 12:24:43 MDT 1998 */ int gsl_sf_conicalP_mhalf_e(const double lambda, const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x <= -1.0) { DOMAIN_ERROR(result); } else if(x < 1.0) { double ac = acos(x); double den = sqrt(sqrt(1.0-x)*sqrt(1.0+x)); double arg = ac * lambda; double err_amp = 1.0 + 1.0/(GSL_DBL_EPSILON + fabs(1.0-fabs(x))); if(fabs(arg) < GSL_SQRT_DBL_EPSILON) { result->val = Root_2OverPi_ / den * ac; result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); result->err *= err_amp; } else { result->val = Root_2OverPi_ / (den*lambda) * sinh(arg); result->err = GSL_DBL_EPSILON * (fabs(arg)+1.0) * fabs(result->val); result->err *= err_amp; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); } return GSL_SUCCESS; } else if(x == 1.0) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else { /* x > 1 */ double sq_term = sqrt(x-1.0)*sqrt(x+1.0); double ln_term = log(x + sq_term); double den = sqrt(sq_term); double arg_val = lambda * ln_term; double arg_err = 2.0 * GSL_DBL_EPSILON * fabs(arg_val); if(arg_val < GSL_SQRT_DBL_EPSILON) { result->val = Root_2OverPi_ / den * ln_term; result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { gsl_sf_result sin_result; int stat_sin = gsl_sf_sin_err_e(arg_val, arg_err, &sin_result); result->val = Root_2OverPi_ / (den*lambda) * sin_result.val; result->err = Root_2OverPi_ / fabs(den*lambda) * sin_result.err; result->err += 3.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_sin; } } } int gsl_sf_conicalP_sph_reg_e(const int l, const double lambda, const double x, gsl_sf_result * result ) { /* CHECK_POINTER(result) */ if(x <= -1.0 || l < -1) { DOMAIN_ERROR(result); } else if(l == -1) { return gsl_sf_conicalP_half_e(lambda, x, result); } else if(l == 0) { return gsl_sf_conicalP_mhalf_e(lambda, x, result); } else if(x == 1.0) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else if(x < 0.0) { double c = 1.0/sqrt(1.0-x*x); gsl_sf_result r_Pellm1; gsl_sf_result r_Pell; int stat_0 = gsl_sf_conicalP_half_e(lambda, x, &r_Pellm1); /* P^( 1/2) */ int stat_1 = gsl_sf_conicalP_mhalf_e(lambda, x, &r_Pell); /* P^(-1/2) */ int stat_P = GSL_ERROR_SELECT_2(stat_0, stat_1); double Pellm1 = r_Pellm1.val; double Pell = r_Pell.val; double Pellp1; int ell; for(ell=0; ell<l; ell++) { double d = (ell+1.0)*(ell+1.0) + lambda*lambda; Pellp1 = (Pellm1 - (2.0*ell+1.0)*c*x * Pell) / d; Pellm1 = Pell; Pell = Pellp1; } result->val = Pell; result->err = (0.5*l + 1.0) * GSL_DBL_EPSILON * fabs(Pell); result->err += GSL_DBL_EPSILON * l * fabs(result->val); return stat_P; } else if(x < 1.0) { const double xi = x/(sqrt(1.0-x)*sqrt(1.0+x)); gsl_sf_result rat; gsl_sf_result Phf; int stat_CF1 = conicalP_negmu_xlt1_CF1(0.5, l, lambda, x, &rat); int stat_Phf = gsl_sf_conicalP_half_e(lambda, x, &Phf); double Pellp1 = rat.val * GSL_SQRT_DBL_MIN; double Pell = GSL_SQRT_DBL_MIN; double Pellm1; int ell; for(ell=l; ell>=0; ell--) { double d = (ell+1.0)*(ell+1.0) + lambda*lambda; Pellm1 = (2.0*ell+1.0)*xi * Pell + d * Pellp1; Pellp1 = Pell; Pell = Pellm1; } result->val = GSL_SQRT_DBL_MIN * Phf.val / Pell; result->err = GSL_SQRT_DBL_MIN * Phf.err / fabs(Pell); result->err += fabs(rat.err/rat.val) * (l + 1.0) * fabs(result->val); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_ERROR_SELECT_2(stat_Phf, stat_CF1); } else if(x == 1.0) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else { /* x > 1.0 */ const double xi = x/sqrt((x-1.0)*(x+1.0)); gsl_sf_result rat; int stat_CF1 = conicalP_negmu_xgt1_CF1(0.5, l, lambda, x, &rat); int stat_P; double Pellp1 = rat.val * GSL_SQRT_DBL_MIN; double Pell = GSL_SQRT_DBL_MIN; double Pellm1; int ell; for(ell=l; ell>=0; ell--) { double d = (ell+1.0)*(ell+1.0) + lambda*lambda; Pellm1 = (2.0*ell+1.0)*xi * Pell - d * Pellp1; Pellp1 = Pell; Pell = Pellm1; } if(fabs(Pell) > fabs(Pellp1)){ gsl_sf_result Phf; stat_P = gsl_sf_conicalP_half_e(lambda, x, &Phf); result->val = GSL_SQRT_DBL_MIN * Phf.val / Pell; result->err = 2.0 * GSL_SQRT_DBL_MIN * Phf.err / fabs(Pell); result->err += 2.0 * fabs(rat.err/rat.val) * (l + 1.0) * fabs(result->val); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); } else { gsl_sf_result Pmhf; stat_P = gsl_sf_conicalP_mhalf_e(lambda, x, &Pmhf); result->val = GSL_SQRT_DBL_MIN * Pmhf.val / Pellp1; result->err = 2.0 * GSL_SQRT_DBL_MIN * Pmhf.err / fabs(Pellp1); result->err += 2.0 * fabs(rat.err/rat.val) * (l + 1.0) * fabs(result->val); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); } return GSL_ERROR_SELECT_2(stat_P, stat_CF1); } } int gsl_sf_conicalP_cyl_reg_e(const int m, const double lambda, const double x, gsl_sf_result * result ) { /* CHECK_POINTER(result) */ if(x <= -1.0 || m < -1) { DOMAIN_ERROR(result); } else if(m == -1) { return gsl_sf_conicalP_1_e(lambda, x, result); } else if(m == 0) { return gsl_sf_conicalP_0_e(lambda, x, result); } else if(x == 1.0) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else if(x < 0.0) { double c = 1.0/sqrt(1.0-x*x); gsl_sf_result r_Pkm1; gsl_sf_result r_Pk; int stat_0 = gsl_sf_conicalP_1_e(lambda, x, &r_Pkm1); /* P^1 */ int stat_1 = gsl_sf_conicalP_0_e(lambda, x, &r_Pk); /* P^0 */ int stat_P = GSL_ERROR_SELECT_2(stat_0, stat_1); double Pkm1 = r_Pkm1.val; double Pk = r_Pk.val; double Pkp1; int k; for(k=0; k<m; k++) { double d = (k+0.5)*(k+0.5) + lambda*lambda; Pkp1 = (Pkm1 - 2.0*k*c*x * Pk) / d; Pkm1 = Pk; Pk = Pkp1; } result->val = Pk; result->err = (m + 2.0) * GSL_DBL_EPSILON * fabs(Pk); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_P; } else if(x < 1.0) { const double xi = x/(sqrt(1.0-x)*sqrt(1.0+x)); gsl_sf_result rat; gsl_sf_result P0; int stat_CF1 = conicalP_negmu_xlt1_CF1(0.0, m, lambda, x, &rat); int stat_P0 = gsl_sf_conicalP_0_e(lambda, x, &P0); double Pkp1 = rat.val * GSL_SQRT_DBL_MIN; double Pk = GSL_SQRT_DBL_MIN; double Pkm1; int k; for(k=m; k>0; k--) { double d = (k+0.5)*(k+0.5) + lambda*lambda; Pkm1 = 2.0*k*xi * Pk + d * Pkp1; Pkp1 = Pk; Pk = Pkm1; } result->val = GSL_SQRT_DBL_MIN * P0.val / Pk; result->err = 2.0 * GSL_SQRT_DBL_MIN * P0.err / fabs(Pk); result->err += 2.0 * fabs(rat.err/rat.val) * (m + 1.0) * fabs(result->val); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_ERROR_SELECT_2(stat_P0, stat_CF1); } else if(x == 1.0) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else { /* x > 1.0 */ const double xi = x/sqrt((x-1.0)*(x+1.0)); gsl_sf_result rat; int stat_CF1 = conicalP_negmu_xgt1_CF1(0.0, m, lambda, x, &rat); int stat_P; double Pkp1 = rat.val * GSL_SQRT_DBL_MIN; double Pk = GSL_SQRT_DBL_MIN; double Pkm1; int k; for(k=m; k>-1; k--) { double d = (k+0.5)*(k+0.5) + lambda*lambda; Pkm1 = 2.0*k*xi * Pk - d * Pkp1; Pkp1 = Pk; Pk = Pkm1; } if(fabs(Pk) > fabs(Pkp1)){ gsl_sf_result P1; stat_P = gsl_sf_conicalP_1_e(lambda, x, &P1); result->val = GSL_SQRT_DBL_MIN * P1.val / Pk; result->err = 2.0 * GSL_SQRT_DBL_MIN * P1.err / fabs(Pk); result->err += 2.0 * fabs(rat.err/rat.val) * (m+2.0) * fabs(result->val); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); } else { gsl_sf_result P0; stat_P = gsl_sf_conicalP_0_e(lambda, x, &P0); result->val = GSL_SQRT_DBL_MIN * P0.val / Pkp1; result->err = 2.0 * GSL_SQRT_DBL_MIN * P0.err / fabs(Pkp1); result->err += 2.0 * fabs(rat.err/rat.val) * (m+2.0) * fabs(result->val); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); } return GSL_ERROR_SELECT_2(stat_P, stat_CF1); } } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_conicalP_0(const double lambda, const double x) { EVAL_RESULT(gsl_sf_conicalP_0_e(lambda, x, &result)); } double gsl_sf_conicalP_1(const double lambda, const double x) { EVAL_RESULT(gsl_sf_conicalP_1_e(lambda, x, &result)); } double gsl_sf_conicalP_half(const double lambda, const double x) { EVAL_RESULT(gsl_sf_conicalP_half_e(lambda, x, &result)); } double gsl_sf_conicalP_mhalf(const double lambda, const double x) { EVAL_RESULT(gsl_sf_conicalP_mhalf_e(lambda, x, &result)); } double gsl_sf_conicalP_sph_reg(const int l, const double lambda, const double x) { EVAL_RESULT(gsl_sf_conicalP_sph_reg_e(l, lambda, x, &result)); } double gsl_sf_conicalP_cyl_reg(const int m, const double lambda, const double x) { EVAL_RESULT(gsl_sf_conicalP_cyl_reg_e(m, lambda, x, &result)); }
{ "alphanum_fraction": 0.5596251933, "avg_line_length": 31.512, "ext": "c", "hexsha": "85dee57b788bfbd917d825cdde5b1b33998ba8b3", "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/specfunc/legendre_con.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/specfunc/legendre_con.c", "max_line_length": 105, "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/specfunc/legendre_con.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": 16442, "size": 43329 }
/** * THE BIG PICTURE * * This file: * 1) (libmtm.a, actually) loads and parses the input matrix * 2) iterates through a sequence of feature pairs specified in one of * a variety of ways * 3) for each pair it calls a high-level analysis method that selects * and executes an appropriate covariate analysis. * 4) routes the analysis results to either * a) immediate output using a specified formatter or * b) a cache to be post-processed (for FDR control) and subsequently * output. * * Implementation notes: * 1) If row labels are present then, by default, they are parsed to * infer the statistical class of the row. Moreover, the parser is * one for "TCGA" format by default. This is so that Sheila et al.'s * scripts need not pass an option for something they consider * "standard." In order to minimize the danger of mis-interpreted * row labels a conservative definition is used (by the * mtm_sclass_by_prefix function). The first two characters of the row * label must match /[BCDFNO][[:punct:]]/. * Otherwise, mtm_sclass_by_prefix returns MTM_STATCLASS_UNKNOWN, * and the class is inferred from the data content of the row. * Audit: * 1) All error exits return -1. When used as webservice proper status * returns is the least we can do... * 2) stdout is ONLY used for data output (at verbosity 0) * 3) Analysis failures (because of degeneracy) still return something * the web service can deal with. Striving for data-as-error, * instead of a separate error channel. * 4) Insure mtm_resort is called before named rows are used. * 5) Every statistical test must fully initialize 1st 4 members of * struct Statistic * 6) Casts, ALL casts! */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <time.h> #include <math.h> #include <signal.h> #include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <getopt.h> #include <stdbool.h> #include <assert.h> #include <ctype.h> #include <err.h> #include <alloca.h> #include <gsl/gsl_errno.h> #include "mtmatrix.h" #include "mtheader.h" #include "mtsclass.h" #include "mterror.h" #include "featpair.h" #include "stattest.h" #include "analysis.h" #include "varfmt.h" #include "fixfmt.h" #include "limits.h" #include "version.h" #ifdef HAVE_LUA #include "lua.h" #include "lauxlib.h" #include "lualib.h" #endif /*************************************************************************** * externs */ extern int mtm_sclass_by_prefix( const char *token ); extern int get_base10_ints( FILE *fp, int *index, int n ); /*************************************************************************** * Globals & statics */ static const char *MAGIC_SUFFIX = "-www"; static const char *MAGIC_FORMAT_ID_STD = "std"; static const char *MAGIC_FORMAT_ID_TCGA = "tcga"; static const char *TYPE_PARSER_INFER = "auto"; const char *AUTHOR_EMAIL = "rkramer@systemsbiology.org"; /** * False Discovery Rate control state. */ static double arg_q_value = 0.0; #define USE_FDR_CONTROL (arg_q_value > 0.0) /** * This is used simply to preclude bloating the FDR cache with results * that can't possibly be relevant to the final BH-calculated p-value * threshold for FDR. * I'm setting this high for safety since it's just an optimization, but * it could probably be MUCH smaller. */ static double opt_fdr_cache_threshold = 0.5; // No default on opt_script because looking for a "default.lua" script // or any *.lua file invites all sorts of confusion with the defaults // and precedence of other row selection methods. static const char *opt_script = NULL; static bool opt_header = true; static bool opt_row_labels = true; static const char *opt_type_parser = NULL; static const char *opt_preproc_matrix = NULL; // ...or optarg static char *opt_single_pair = NULL; // non-const because it's split static const char *opt_pairlist_source = NULL; static const char *NO_ROW_LABELS = "matrix has no row labels"; static bool opt_by_name = false; #ifdef HAVE_LUA static const char *DEFAULT_COROUTINE = "pair_generator"; #endif static const char *opt_coroutine = NULL; static bool opt_dry_run = false; static const char *opt_format = "tcga"; static bool opt_warnings_are_fatal = false; /** * Primary output and critical error messages. */ #define V_ESSENTIAL (1) /** * Non-critical information that may, nonetheless, be helpful. */ #define V_WARNINGS (2) /** * Purely informational. */ #define V_INFO (3) static int opt_verbosity = V_ESSENTIAL; #ifdef _DEBUG static bool dbg_silent = false; #endif #define GLOBAL GLOBAL unsigned arg_min_cell_count = 5; GLOBAL unsigned arg_min_mixb_count = 1; GLOBAL unsigned arg_min_sample_count = 2; // < 2 NEVER makes sense #undef GLOBAL static const char *opt_na_regex = NULL; // must be initialized in main static double opt_p_value = 1.0; /** * Eventually it is (was) intended to support delegating row label * interpretation--in particular inference of a row's statistical class * based on its row label--to a user-provided Lua function. * Currently, only the default interpreter built into libmtm is actually * supported, which interprets row labels according to "ISB conventions." */ static MTM_ROW_LABEL_INTERPRETER _interpret_row_label = mtm_sclass_by_prefix; static unsigned opt_status_mask = COVAN_E_MASK; #ifdef HAVE_LUA static lua_State *_L = NULL; /** * Delegate inference of a row's statistical class to a user-provided * function. */ int _lua_statclass_inference( const char *label ) { fprintf( stderr, "interpret %s\n", label ); return MTM_STATCLASS_UNKNOWN; } static void _freeLua() { lua_close( _L ); } /** * <source> may be literal Lua code or a filename reference. */ static int _load_script( const char *source, lua_State *state ) { struct stat info; return (access( source, R_OK ) == 0) && (stat( source, &info ) == 0) ? luaL_dofile( state, source ) : luaL_dostring( state, source ); } #endif static FILE *_fp_output = NULL; static void (*_emit)( EMITTER_SIG ) = format_tcga; static bool _sigint_received = false; /** * Records the number of pairwise tests COMPLETED WITHOUT ERROR * but not emitted (because they didn't pass the p-value threshold * for emission. * * This is NOT used when FDR control is active in pairwise; rather it is * for use in FDR control calculations *outside* the context of pairwise. * * Note that the total number of tests *attempted* is *not* separately * counted because it is assumed that that is known to the caller who * set up the run, after all. */ static unsigned _insignificant = 0; static unsigned _untested = 0; /** * The binary matrix is accessed at runtime through this variable. * Notice, in particular, that the analysis code (analysis.cpp) * only has access to pairs of rows, NOT the whole matrix. * The matrix' structure and implementation is strictly encapsulated * within this file, and code in here dolls out just what analysis * requires: row pairs. */ static struct mtm_matrix _matrix; static void _freeMatrix( void ) { _matrix.destroy( &_matrix ); } static void _interrupt( int n ) { _sigint_received = true; } /*************************************************************************** * Pipeline * A) explicit pairs * 1. row pair -> analysis -> filtering -> output * B) all-pairs or Lua generated pair lists * 1. row pair -> analysis -> filtering -> output * 2. row pair -> analysis -> fdr aggregation -> re-processing ->output */ /** * Analysis results on feature pairs are passed EITHER to: * 1. an emitter for immediate output (single pair only) * 2. a filter (and then possibly to an emitter) * 3. an aggregator (to be filtered and stored for later emission) * * All three of these methods must have the same signature. */ #define ANALYSIS_FN_SIG const struct feature_pair *pair typedef void (*ANALYSIS_FN)( ANALYSIS_FN_SIG ); /*************************************************************************** * Encapsulates all the decision making regarding actual emission of * results. */ static void _filter( ANALYSIS_FN_SIG ) { struct CovariateAnalysis covan; memset( &covan, 0, sizeof(covan) ); covan_exec( pair, &covan ); // One last thing to check before filtering to insure corner cases // don't fall through the following conditionals.... if( ! ( isfinite( covan.result.probability ) && fpclassify( covan.result.probability ) != FP_SUBNORMAL ) ) { covan.result.probability = 1.0; covan.status = COVAN_E_MATH; // The assumption is that if a NaN shows up in the result, it was // triggered by an un"pre"detected degeneracy, and so the pair was // in fact untestable (how it will be interpreted below). } #ifdef _DEBUG if( ! dbg_silent ) { #endif if( ( covan.status & opt_status_mask ) == 0 ) { if( covan.result.probability <= opt_p_value ) _emit( pair, &covan, _fp_output ); else _insignificant += 1; } else _untested += 1; #ifdef _DEBUG } #endif } static ANALYSIS_FN _analyze = _filter; static void _error_handler(const char * reason, const char * file, int line, int gsl_errno) { fprintf( stderr, "#GSL error(%d): %s\n" "#GSL error at: %s:%d\n", gsl_errno, reason, file, line ); } static FILE *_fdr_cache_fp = NULL; /*************************************************************************** * FDR processing * This currently involves some redundant computation in the interest of * simplicity. Since the whole point of FDR is to limit output, though, the * actual runtime cost should be bearabe. Specifically... * * 1. Two passes are made over the (selected) pairs. * 2. The offsets and p-value of the result of the first pass are cached * in a tmp file. * 3. After completion, the p-value appropriate for the given q-value is * determined and results from the 1st pass with sufficiently low * p-values are recalculated and, this time, fully emitted. * * TODO: Optimization: Pairs with very high p-values (i.e. *clearly* * uninteresting pairs) can be omitted from the cache even in the first * pass and merely counted as tests since their recomputation will *almost* * certainly, depending ultimately on the threshold, not be required. */ struct FDRCacheRecord { double p; unsigned a,b; } __attribute__((packed)); typedef struct FDRCacheRecord FDRCacheRecord_t; typedef const FDRCacheRecord_t FDRCACHERECORD_T; static int _cmp_fdr_cache_records( const void *pvl, const void *pvr ) { FDRCACHERECORD_T *l = (FDRCACHERECORD_T*)pvl; FDRCACHERECORD_T *r = (FDRCACHERECORD_T*)pvr; if( l->p == r->p ) return 0; else return (l->p < r->p) ? -1 : +1; } static int _fdr_uncached_count = 0; /** * Analyze the pair and cache just the offsets and p-value of the result * for possible recalculation during post-processing--after FDR control * has calculated an appropriate p-value threshold from the q-value. */ static void _fdr_cache( ANALYSIS_FN_SIG ) { struct CovariateAnalysis covan; memset( &covan, 0, sizeof(covan) ); covan_exec( pair, &covan ); // Failed tests (for reasons of one kind of degeneracy or another) // do not contribute to the calculation of the p-value threshold. if( covan.status == 0 && isfinite( covan.result.probability ) ) { // ...then, whatever the p-value, the test was at least // successfully *executed*. if( covan.result.probability <= opt_fdr_cache_threshold ) { struct FDRCacheRecord rec = { .p = covan.result.probability, .a = pair->l.offset, .b = pair->r.offset }; fwrite( &rec, sizeof(rec), 1, _fdr_cache_fp ); } else _fdr_uncached_count += 1; } } /** * This implements the Benjamini-Hochberg algorithm as described on * page 49 of "Large-Scale Inference", Bradley Efron, Cambridge. * "...for a fixed value of q in (0,1), let i_max be the largest * index for which * p_(i) <= (i/N)q * * ...and reject H_{0(i)}, the null hypothesis corresponding to * p_(i), if * i <= i_max, * * ...accepting H_{0(i)} otherwise." * * [...And i is 1-based in this notation!] */ static void _fdr_postprocess( FILE *cache, double Q, FILE *final_output, bool minimal_output ) { const unsigned CACHED_COUNT = ftell( cache ) / sizeof(struct FDRCacheRecord); const unsigned TESTED_COUNT = CACHED_COUNT + _fdr_uncached_count; struct FDRCacheRecord *prec, *sortbuf = calloc( CACHED_COUNT, sizeof(struct FDRCacheRecord) ); const double RATIO = Q/TESTED_COUNT; int i = 0; // Load and sort the cached test records... rewind( cache ); fread( sortbuf, sizeof(struct FDRCacheRecord), CACHED_COUNT, cache ); qsort( sortbuf, CACHED_COUNT, sizeof(struct FDRCacheRecord), _cmp_fdr_cache_records ); // ...and recompute the full statistics of all earlier tests that // pass the now-established p-value threshold. prec = sortbuf; if( minimal_output ) { while( prec->p <= (i+1)*RATIO && i < CACHED_COUNT) fprintf( final_output, "%d\t%d\t%.3e\n", prec->a, prec->b, prec->p ); } else { while( prec->p <= (i+1)*RATIO && i < CACHED_COUNT) { struct feature_pair fpair; struct CovariateAnalysis covan; memset( &covan, 0, sizeof(covan) ); fpair.l.offset = prec->a; fpair.r.offset = prec->b; fetch_by_offset( &_matrix, &fpair ); covan_exec( &fpair, &covan ); // At this point emission is unconditional; FDR control has // already filtered all that will be filtered... _emit( &fpair, &covan, final_output ); if( _sigint_received ) { time_t now = time(NULL); fprintf( stderr, "# FDR postprocess interrupted @ %s", ctime(&now) ); break; } prec += 1; i += 1; } } // However, the preceding loop exited if( opt_verbosity >= V_WARNINGS ) { if( i > 0 ) fprintf( final_output, "# max p-value %.3f\n", sortbuf[i-1].p ); else fprintf( final_output, "# no values passed FDR control\n" ); } if( sortbuf ) free( sortbuf ); } /*************************************************************************** * Row selection iterators * Each of these 5 methods takes arguments specific to the * source of input pairs and uses file static state for output. * All but the first delegate to the _analyze function which may be a * filter on immediate-mode output or a caching function for FDR. */ // BEGIN:RSI static int /*ANCP*/ _analyze_cross_product( const struct mtm_matrix_header *hdr, FILE *fp[] ) { bool completed = true; struct feature_pair fpair; struct mtm_row *rrid; /** * Location of left data won't change: same buffer, same offset for * duration of iteration. */ fpair.l.data = calloc( _matrix.columns, sizeof(mtm_int_t) ); /** * TODO: I actually could enumerate the disk-resident matrix' * row names just as I do the descriptors. In general, the * pervasive assumption throughout this source that the input * is exactly one matrix needs to be revisited. */ fpair.l.name = NULL; if( fpair.l.data == NULL ) return -1; assert( ! _matrix.lexigraphic_order /* should be row order */ ); for(fpair.l.offset = 0; fpair.l.offset < hdr->rows; fpair.l.offset++ ) { /** * Read the "left" feature's data and descriptor */ if( fread( (void*)fpair.l.data, sizeof(mtm_int_t), hdr->columns, fp[0] ) != hdr->columns ) break; if( fread( &fpair.l.desc, sizeof(struct mtm_descriptor), 1, fp[1] ) != 1 ) break; /** * RAM-resident matrix is *fully* reset for each row of disk- * resident matrix... */ fpair.r.data = _matrix.data; rrid = _matrix.row_map; // may be NULL for(fpair.r.offset = 0; fpair.r.offset < _matrix.rows; fpair.r.offset++ ) { fpair.r.name = rrid ? rrid->string : ""; fpair.r.desc = _matrix.desc[ fpair.r.offset ]; _analyze( &fpair ); if( _sigint_received ) { time_t now = time(NULL); fprintf( stderr, "# main analysis loop interrupted @ %s", ctime(&now) ); completed = false; break; } fpair.r.data += _matrix.columns; if( rrid ) rrid += 1; } // inner for } if( ferror( fp[0] ) || ferror( fp[1] ) ) { warn( "reading row %d of preprocessed matrix", fpair.l.offset ); completed = false; } if( fpair.l.data ) free( (void*)fpair.l.data ); return completed ? 0 : -1; } static bool _is_integer( const char *pc ) { while( *pc ) if( ! isdigit(*pc++) ) return false; return true; } static int _analyze_single_pair( const char *csv, const bool HAVE_ROW_LABELS ) { static const char *MISSING_MSG = "you specified row %s for a matrix without row names.\n"; int econd; char *right, *left = alloca( strlen(csv)+1 ); struct CovariateAnalysis covan; struct feature_pair pair; memset( &pair, 0, sizeof(pair) ); memset( &covan, 0, sizeof(covan) ); // Split the string in two... strcpy( left, csv ); right = strchr( left, ',' ); if( NULL == right ) errx( -1, "missing comma separator in feature pair \"%s\"", left ); *right++ = '\0'; // Lookup each part.(They need not be the same format.) if( _is_integer( left ) ) { pair.l.offset = atoi( left ); mtm_resort_rowmap( &_matrix, MTM_RESORT_BYROWOFFSET ); econd = mtm_fetch_by_offset( &_matrix, &(pair.l) ); } else if( HAVE_ROW_LABELS ) { pair.l.name = left; if( mtm_resort_rowmap( &_matrix, MTM_RESORT_LEXIGRAPHIC ) ) errx( -1, NO_ROW_LABELS ); econd = mtm_fetch_by_name( &_matrix, &(pair.l) ); } else errx( -1, MISSING_MSG, left ); if( _is_integer( right ) ) { pair.r.offset = atoi( right ); mtm_resort_rowmap( &_matrix, MTM_RESORT_BYROWOFFSET ); econd = mtm_fetch_by_offset( &_matrix, &(pair.r) ); } else if( HAVE_ROW_LABELS ) { pair.r.name = right; if( mtm_resort_rowmap( &_matrix, MTM_RESORT_LEXIGRAPHIC ) ) errx( -1, NO_ROW_LABELS ); econd = mtm_fetch_by_name( &_matrix, &(pair.r) ); } else errx( -1, MISSING_MSG, right ); covan_exec( &pair, &covan ); _emit( &pair, &covan, _fp_output ); return 0; } static int /*ANAM*/ _analyze_named_pair_list( FILE *fp ) { struct feature_pair fpair; size_t blen = 0; ssize_t llen; char *right, *left = NULL; while( ( llen = getline( &left, &blen, fp ) ) > 0 ) { // Trim off the newline char. if( left[llen-1] == '\n' ) left[--llen] = '\0'; // Strip the NL // Parse the two names out of the line. right = strchr( left, '\t' ); if( right ) *right++ = '\0'; else { fprintf( stderr, "error: no tab found in '%s'.\n", left ); if( opt_warnings_are_fatal ) break; else continue; // no reason we -can't- continue } fpair.l.name = left; fpair.r.name = right; if( fetch_by_name( &_matrix, &fpair ) ) { warnx( "error: one or both of...\n" "\t1) %s\n" "\t2) %s\n" "\t...not found.\n", fpair.l.name, fpair.r.name ); if( opt_warnings_are_fatal ) break; else continue; // no reason we -can't- continue } else _analyze( &fpair ); } if( left ) free( left ); return 0; } static int /*ANUM*/ _analyze_pair_list( FILE *fp ) { struct feature_pair fpair; int arr[2]; while( get_base10_ints( fp, arr, 2 ) == 2 ) { fpair.l.offset = arr[0]; fpair.r.offset = arr[1]; if( fetch_by_offset( &_matrix, &fpair ) ) { warnx( "error: one of row indices (%d,%d) not in [0,%d)\n" "\tjust before byte offset %ld in the stream.\n" "\tAborting...\n", fpair.l.offset, fpair.r.offset, _matrix.rows, ftell( fp ) ); if( opt_warnings_are_fatal ) break; else continue; // no reason we -can't- continue } else _analyze( &fpair ); } return 0; } #ifdef HAVE_LUA static int /*ALUA*/ _analyze_generated_pair_list( lua_State *state ) { struct feature_pair fpair; int isnum, lua_status; lua_getglobal( _L, opt_coroutine ); assert( ! lua_isnil( _L, -1 ) /* because it was checked early */ ); do { lua_pushnumber( _L, _matrix.rows ); lua_status = lua_resume( _L, NULL, 1 ); if( lua_status == LUA_YIELD ) { fpair.r.offset = lua_tonumberx( _L, -1, &isnum ); fpair.l.offset = lua_tonumberx( _L, -2, &isnum ); lua_pop( _L, 2 ); if( fetch_by_offset( &_matrix, &fpair ) ) { warnx( "one or both of %s-generated row indices (%d,%d) not in [0,%d)\n", opt_coroutine, fpair.l.offset, fpair.r.offset, _matrix.rows ); if( opt_warnings_are_fatal ) break; else continue; // no reason we -can't- continue } else _analyze( &fpair ); } else if( lua_status == LUA_OK ) break; else { // some sort of error occurred. fputs( lua_tostring( _L, -1 ), stderr ); } if( _sigint_received ) { time_t now = time(NULL); fprintf( stderr, "analysis loop interrupted @ %s", ctime(&now) ); break; } } while( lua_status == LUA_YIELD ); return 0; } #endif /** * This clause serves the primary use case motivating this * application: FAST, EXHAUSTIVE (n-choose-2) pairwise analysis. * As a result, the coding of this iteration schema is quite * different from the others. In particular: * 1. Since I -know- the order of feature pair evaluation I can * preclude lots of useless work by entirely skipping outer loop * features with univariate degeneracy. This isn't feasible in * the other iteration sc * I'm dispensing with "pretty" and doing the * pointer arithmetic locally to eek out maximum possible speed. * In particular, I set up lots of ptrs below to obviate * redundant pointer arithmetic--only do fixed additions. */ static int /*AALL*/ _analyze_all_pairs( void ) { bool completed = true; struct feature_pair fpair; struct mtm_row *lrid, *rrid; assert( ! _matrix.lexigraphic_order /* should be row order */ ); fpair.l.data = _matrix.data; lrid = _matrix.row_map; // may be NULL for(fpair.l.offset = 0; fpair.l.offset < _matrix.rows; fpair.l.offset++ ) { fpair.l.name = lrid ? lrid->string : ""; fpair.l.desc = _matrix.desc[ fpair.l.offset ]; fpair.r.data = fpair.l.data + _matrix.columns; rrid = lrid ? lrid + 1 : NULL; for(fpair.r.offset = fpair.l.offset+1; fpair.r.offset < _matrix.rows; fpair.r.offset++ ) { fpair.r.name = rrid ? rrid->string : ""; fpair.r.desc = _matrix.desc[ fpair.r.offset ]; _analyze( &fpair ); if( _sigint_received ) { time_t now = time(NULL); fprintf( stderr, "# main analysis loop interrupted @ %s", ctime(&now) ); completed = false; break; } fpair.r.data += _matrix.columns; if( rrid ) rrid += 1; } // inner for fpair.l.data += _matrix.columns; if( lrid ) lrid += 1; } return completed ? 0 : -1; } // END:RSI /** * Initializations for which static initialization can't/shouldn't * be relied upon. Common to executable and Python extension. */ static void _jit_initialization( void ) { opt_na_regex = mtm_default_NA_regex; memset( &_matrix, 0, sizeof(struct mtm_matrix) ); gsl_set_error_handler( _error_handler ); } /*************************************************************************** * Online help */ static const char *_YN( bool y ) { return y ? "yes" : "no"; } #define USAGE_SHORT false #define USAGE_LONG true static void _print_usage( const char *exename, FILE *fp, bool exhaustive ) { extern const char *USAGE_UNABRIDGED; extern const char *USAGE_ABRIDGED; char debug_state[64]; debug_state[0] = 0; #ifdef _DEBUG sprintf( debug_state, "(DEBUG) Compiled %s %s", __DATE__,__TIME__ ); #endif if( exhaustive ) fprintf( fp, USAGE_UNABRIDGED, exename, VER_MAJOR, VER_MINOR, VER_PATCH, VER_TAG, debug_state, exename, exename, TYPE_PARSER_INFER, opt_na_regex, #ifdef HAVE_LUA DEFAULT_COROUTINE, #endif arg_min_cell_count, arg_min_mixb_count, arg_min_sample_count, opt_p_value, opt_status_mask, opt_format, MAGIC_FORMAT_ID_STD, MAGIC_FORMAT_ID_TCGA, _YN(opt_warnings_are_fatal), opt_verbosity, MAGIC_SUFFIX, MAX_CATEGORY_COUNT, MTM_MAX_MISSING_VALUES, AUTHOR_EMAIL ); else fprintf( fp, USAGE_ABRIDGED, exename, VER_MAJOR, VER_MINOR, VER_PATCH, VER_TAG, debug_state, exename, opt_p_value, AUTHOR_EMAIL ); } int main( int argc, char *argv[] ) { int exit_status = EXIT_SUCCESS; const char *i_file = NULL; const char *o_file = NULL; FILE *fp = NULL; if( argc < 2 ) { // absolute minimum args: <executable name> <input matrix> _print_usage( argv[0], stdout, USAGE_SHORT ); exit( EXIT_SUCCESS ); } _jit_initialization(); do { static const char *CHAR_OPTIONS #ifdef HAVE_LUA = "s:hrt:N:C:P:n:x:c:DM:p:f:q:v:?X"; #else = "hrt:N:C:P:n:x:DM:p:f:q:v:?X"; #endif static struct option LONG_OPTIONS[] = { #ifdef HAVE_LUA {"script", required_argument, 0,'s'}, #endif {"no-header", no_argument, 0,'h'}, {"no-row-labels", no_argument, 0,'r'}, {"type-parser", required_argument, 0,'t'}, {"na-regex", required_argument, 0,'N'}, {"crossprod", required_argument, 0,'C'}, {"pair", required_argument, 0,'P'}, {"by-name", required_argument, 0,'n'}, {"by-index", required_argument, 0,'x'}, #ifdef HAVE_LUA {"coroutine", required_argument, 0,'c'}, #endif {"dry-run", no_argument, 0,'D'}, {"min-ct-cell", required_argument, 0, 256 }, // no short equivalents {"min-mx-cell", required_argument, 0, 257 }, // no short equivalents {"min-samples", required_argument, 0,'M'}, {"p-value", required_argument, 0,'p'}, {"format", required_argument, 0,'f'}, {"fdr", required_argument, 0,'q'}, {"verbosity", required_argument, 0,'v'}, #ifdef _DEBUG {"debug", required_argument, 0, 258 }, // no short equivalents #endif {"help", no_argument, 0,'?'}, { NULL, 0, 0, 0 } }; int arg_index = 0; const int c = getopt_long( argc, argv, CHAR_OPTIONS, LONG_OPTIONS, &arg_index ); switch (c) { case 's': // script opt_script = optarg; break; case 'h': // no-header opt_header = false; break; case 'r': // no-row-labels opt_row_labels = false; break; case 't': // type-parser opt_type_parser = optarg; break; case 'N': // na-regex opt_na_regex = optarg; break; case 'C': // cross-product of matrices opt_preproc_matrix = optarg; break; case 'P': // pair opt_single_pair = optarg; break; case 'n': // by-name opt_pairlist_source = optarg; opt_by_name = true; break; case 'x': // by-index opt_pairlist_source = optarg; opt_by_name = false; break; case 'c': // coroutine opt_coroutine = optarg; break; case 'D': // dry-run opt_dry_run = true; break; //////////////////////////////////////////////////////////////////// case 256: // ...because I haven't defined a short form for this arg_min_cell_count = atoi( optarg ); break; case 257: // ...because I haven't defined a short form for this arg_min_mixb_count = atoi( optarg ); break; case 'M': arg_min_sample_count = atoi( optarg ); if( arg_min_sample_count < 2 ) { warnx( "Seriously...%d samples is acceptable?\n" "I don't think so... ;)\n", arg_min_sample_count ); exit( EXIT_FAILURE ); } break; //////////////////////////////////////////////////////////////////// case 'p': opt_p_value = atof( optarg ); if( ! ( 0 < opt_p_value ) ) { warnx( "specified p-value %.3f will preclude all output.\n", opt_p_value ); abort(); } else if( ! ( opt_p_value < 1.0 ) ) { warnx( "p-value %.3f will filter nothing.\n" "\tIs this really what you want?\n", opt_p_value ); } break; case 'J': // JSON format case 'f': // tabular format // Check for magic-value strings first if( strcmp( MAGIC_FORMAT_ID_STD, optarg ) == 0 ) _emit = format_standard; else if( strcmp( MAGIC_FORMAT_ID_TCGA, optarg ) == 0 ) _emit = format_tcga; else { const char *specifier = emit_config( optarg, c=='J' ? FORMAT_JSON : FORMAT_TABULAR ); if( specifier ) { errx( -1, "invalid specifier \"%s\"", specifier ); } _emit = emit_exec; } break; case 'q': arg_q_value = atof( optarg ); _analyze = _fdr_cache; break; case 'v': // verbosity opt_verbosity = atoi( optarg ); break; case '?': // help _print_usage( argv[0], stdout, USAGE_SHORT ); exit( EXIT_SUCCESS ); break; case 'X': // help _print_usage( argv[0], stdout, USAGE_LONG ); exit( EXIT_SUCCESS ); break; #ifdef _DEBUG case 258: if( strchr( optarg, 'X' ) != NULL ) { // Turn OFF all filtering to turn on "exhaustive" // output mode. opt_status_mask = 0; opt_p_value = 1.0; } dbg_silent = strchr( optarg, 'S' ) != NULL; break; #endif case -1: // ...signals no more options. break; default: printf ("error: unknown option: %c\n", c ); exit( EXIT_FAILURE ); } if( -1 == c ) break; } while( true ); #ifdef HAVE_LUA if( opt_script ) { /** * Create a Lua state machine and load/run the Lua script from file * or command line before anything else. */ _L = luaL_newstate(); if( _L ) { atexit( _freeLua ); // ...so lua_close needed NOWHERE else. luaL_openlibs( _L ); if( _load_script( opt_script, _L ) != LUA_OK ) { errx( -1, "in \"%s\": %s", opt_script, lua_tostring( _L,-1) ); } } else errx( -1, "failed creating Lua statespace" ); /** * Fail early! * If the user provided a coroutine name, check for its presence. * Otherwise, see if the default coroutine is present. * Otherwise, Lua is not being used to generate pairs. */ if( opt_coroutine ) { lua_getglobal( _L, opt_coroutine ); if( lua_isnil( _L, -1 ) ) { errx( -1, "pair generator coroutine \"%s\" not defined in \"%s\"", opt_coroutine, opt_script ); } } else { lua_getglobal( _L, DEFAULT_COROUTINE ); if( ! lua_isnil( _L, -1 ) ) opt_coroutine = DEFAULT_COROUTINE; // Non-existence of DEFAULT_COROUTINE is not an error; // we assume user does NOT intend Lua to generate the pairs. } lua_pop( _L, 1 ); // clean the stack /** * Similarly verify NOW that the a specified type parser is present. */ if( opt_type_parser ) { lua_getglobal( _L, opt_type_parser ); if( lua_isnil( _L, -1 ) ) { errx( -1, "pair generator coroutine \"%s\" not defined in \"%s\"", opt_type_parser, opt_script ); } lua_pop( _L, 1 ); // clean the stack } /** * Load Lua script and execute a dry-run if applicable. * This is in advance of other argument validation since other * arguments will be ignored... */ if( opt_dry_run && opt_coroutine != NULL ) { const int COUNT = getenv("DRY_RUN_COUNT") ? atoi( getenv("DRY_RUN_COUNT") ) : 8; int isnum, lua_status = LUA_YIELD; lua_getglobal( _L, opt_coroutine ); if( lua_isnil( _L, -1 ) ) errx( -1, "%s not defined (in Lua's global namespace)", opt_coroutine ); while( lua_status == LUA_YIELD ) { lua_pushnumber( _L, COUNT ); lua_status = lua_resume( _L, NULL, 1 ); if( lua_status <= LUA_YIELD /* OK == 0, YIELD == 1*/ ) { // Only output coroutine.yield'ed values... if( lua_status == LUA_YIELD ) { const int b = lua_tonumberx( _L, -1, &isnum ); const int a = lua_tonumberx( _L, -2, &isnum ); lua_pop( _L, 2 ); fprintf( stdout, "%d %d\n", a, b ); } } else fputs( lua_tostring( _L, -1 ), stderr ); } exit( EXIT_SUCCESS ); } } else if( opt_coroutine ) { errx( -1, "coroutine specified (\"%s\") but no script", opt_coroutine ); } #endif /** * Catch simple argument inconsistencies and fail early! */ if( opt_single_pair ) { if( USE_FDR_CONTROL ) { warnx( "FDR is senseless on a single pair.\n" ); if( opt_warnings_are_fatal ) abort(); else arg_q_value = 0.0; } } /** * The last two positional arguments are expected to be filenames * ... <filename1> */ static const char *NAME_STDIN = "stdin"; static const char *NAME_STDOUT = "stdout"; switch( argc - optind ) { case 0: // input MUST be stdin, output stdout i_file = NAME_STDIN; o_file = NAME_STDOUT; break; case 1: if( access( argv[ optind ], R_OK ) == 0 ) { i_file = argv[ optind++ ]; o_file = NAME_STDOUT; } else { i_file = NAME_STDIN; o_file = argv[ optind++ ]; } break; case 2: default: i_file = argv[ optind++ ]; o_file = argv[ optind++ ]; if( (argc-optind) > 0 && opt_verbosity >= V_ESSENTIAL ) { // This behavior of ignoring "extra" arguments is implemented // ONLY so that this executable plays nicely with a job control // system which uses extra command line args NOT intended for // the executable. TODO: Revisit this! fprintf( stderr, "warning: ignoring %d trailing positional arguments.\n", argc-optind ); while( optind < argc ) fprintf( stderr, "\t\"%s\"\n", argv[optind++] ); if( opt_warnings_are_fatal ) exit( EXIT_FAILURE ); } } if( opt_pairlist_source != NULL && strcmp( opt_pairlist_source, i_file ) == 0 ) { errx( -1, "error: stdin specified (or implied) for both pair list and the input matrix\n" ); } /** * Emit intentions... */ if( opt_verbosity >= V_INFO ) { #define MAXLEN_FS 75 char feature_selection[MAXLEN_FS+1]; feature_selection[MAXLEN_FS] = 0; // insure NUL termination /** * Following conditional cascade must exactly match the larger * one below in order to accurately report feature selection method. */ if( opt_single_pair ) { strncpy( feature_selection, opt_single_pair, MAXLEN_FS ); } else if( opt_pairlist_source ) { snprintf( feature_selection, MAXLEN_FS, "by %s in %s", opt_by_name ? "name" : "offset", opt_pairlist_source ); } else { #ifdef HAVE_LUA if( opt_coroutine ) snprintf( feature_selection, MAXLEN_FS, "%s in %s", opt_coroutine, opt_script /* may be literal source */ ); else #endif strncpy( feature_selection, "all-pairs", MAXLEN_FS ); } fprintf( stderr, " input: %s\n" " select: %s\n" " output: %s\n" #ifdef _DEBUG " debug: silent: %s\n" #endif ,i_file, feature_selection, o_file #ifdef _DEBUG , _YN( dbg_silent ) #endif ); } /** * Load the input matrix. */ fp = strcmp( i_file, NAME_STDIN ) ? fopen( i_file, "r" ) : stdin; if( fp ) { const unsigned int FLAGS = ( opt_header ? MTM_MATRIX_HAS_HEADER : 0 ) | ( opt_row_labels ? MTM_MATRIX_HAS_ROW_NAMES : 0 ) | ( opt_verbosity & MTM_VERBOSITY_MASK); const int econd = mtm_parse( fp, FLAGS, opt_na_regex, MAX_CATEGORY_COUNT, opt_row_labels ? _interpret_row_label : NULL, NULL, // ...since no persistent binary matrix is needed. &_matrix ); fclose( fp ); if( econd ) errx( -1, "mtm_parse returned (%d)", econd ); else atexit( _freeMatrix ); } if( opt_dry_run ) { // a second possible exit( EXIT_SUCCESS ); } if( SIG_ERR == signal( SIGINT, _interrupt ) ) { warn( "failed installing interrupt handler\n" "\tCtrl-C will terminated gracelessly\n" ); } /** * Choose and open, if necessary, an output stream. */ _fp_output = (strcmp( o_file, NAME_STDOUT ) == 0 ) ? stdout : fopen( o_file, "w" ); if( NULL == _fp_output ) { err( -1, "opening output file \"%s\"", o_file ); } if( covan_init( _matrix.columns ) ) { err( -1, "error: covan_init(%d)\n", _matrix.columns ); } else atexit( covan_fini ); if( opt_verbosity >= V_INFO ) fprintf( _fp_output, "# %d rows/features X %d columns/samples\n", _matrix.rows, _matrix.columns ); if( USE_FDR_CONTROL ) { _fdr_cache_fp = tmpfile(); _fdr_uncached_count = 0; if( NULL == _fdr_cache_fp ) err( -1, "creating a temporary file" ); } /** * Here the main decision is made regarding feature selection. * In order of precedence: * 0. cross-product of matrices * 1. single pair * 2. explicit pairs (by name or by offset) * 3. Lua-generated offsets * 4. all-pairs */ if( opt_preproc_matrix ) { FILE *ppm[2]; ppm[0] = fopen( opt_preproc_matrix, "r" ); if( ppm[0] ) { struct mtm_matrix_header hdr; /** * Open a second stream on the file to access the * descriptor table. */ ppm[1] = fopen( opt_preproc_matrix, "r" ); /** * Read the header and verify compatibility */ if( mtm_load_header( ppm[0], &hdr ) != MTM_OK ) err( -1, "failed reading preprocessed matrix' (%s) header", opt_preproc_matrix ); // Verify file is the preprocessed matrix the user thinks it is. if( strcmp( hdr.sig, MTM_SIGNATURE ) ) errx( -1, "%s has wrong signature." "Are you sure this is a preprocessed matrix", opt_preproc_matrix ); // Verify equality of columns if( _matrix.columns != hdr.columns ) errx( -1, "processed matrix has %d columns; other has %d", hdr.columns, _matrix.columns ); // Skip past the header to the row data. if( fseek( ppm[0], hdr.section[ S_DATA ].offset, SEEK_SET ) ) err( -1, "failed seeking to start of data" ); // Skip to the descriptor table in the 2nd stream. if( fseek( ppm[1], hdr.section[ S_DESC ].offset, SEEK_SET ) ) err( -1, "failed seeking to start of data" ); _analyze_cross_product( &hdr, ppm ); fclose( ppm[1] ); fclose( ppm[0] ); } } else if( opt_single_pair ) { _analyze_single_pair( opt_single_pair, opt_row_labels ); } else if( opt_pairlist_source ) { FILE *fp = strcmp(opt_pairlist_source,NAME_STDIN) ? fopen( opt_pairlist_source, "r" ) : stdin; if( opt_by_name ) { if( mtm_resort_rowmap( &_matrix, MTM_RESORT_LEXIGRAPHIC ) ) errx( -1, NO_ROW_LABELS ); } if( fp ) { const int econd = opt_by_name ? _analyze_named_pair_list( fp ) : _analyze_pair_list( fp ); if( econd ) warn( "error (%d) analyzing%s pair list", econd, opt_by_name ? " named" : "" ); fclose( fp ); } else warn( "opening \"%s\"", opt_pairlist_source ); } else { #ifdef HAVE_LUA if( opt_coroutine ) _analyze_generated_pair_list( _L ); else #endif _analyze_all_pairs(); } // Post process results if FDR is in effect and the 1st pass was // allowed to complete. (Post-processing involves a repetition of // analysis FOR A SUBSET of the original input.) if( USE_FDR_CONTROL && (! _sigint_received) ) { _fdr_postprocess( _fdr_cache_fp, arg_q_value, _fp_output, opt_preproc_matrix != NULL ); } else if( opt_verbosity >= V_ESSENTIAL ) { fprintf( _fp_output, "# %d filtered for insignificance\n" "# %d filtered for some sort of degeneracy\n", _insignificant, _untested ); // ...which does not apply in FDR control context. } if( _fdr_cache_fp ) fclose( _fdr_cache_fp ); if( _fp_output ) fclose( _fp_output ); return exit_status; }
{ "alphanum_fraction": 0.636377516, "avg_line_length": 26.1122923588, "ext": "c", "hexsha": "4c89045c41c040fa4aa947590dee69dd03f19900", "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": "987eb145f1f99378fcf24d4f89664e986e7c2a81", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "IlyaLab/kramtools", "max_forks_repo_path": "pairwise/src/main.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "987eb145f1f99378fcf24d4f89664e986e7c2a81", "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": "IlyaLab/kramtools", "max_issues_repo_path": "pairwise/src/main.c", "max_line_length": 109, "max_stars_count": 1, "max_stars_repo_head_hexsha": "987eb145f1f99378fcf24d4f89664e986e7c2a81", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "IlyaLab/kramtools", "max_stars_repo_path": "pairwise/src/main.c", "max_stars_repo_stars_event_max_datetime": "2020-03-30T03:07:45.000Z", "max_stars_repo_stars_event_min_datetime": "2020-03-30T03:07:45.000Z", "num_tokens": 11341, "size": 39299 }
/* statistics/gsl_statistics_ulong.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Jim Davies, 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. */ #ifndef __GSL_STATISTICS_ULONG_H__ #define __GSL_STATISTICS_ULONG_H__ #include <stddef.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 GSL_EXPORT double gsl_stats_ulong_mean (const unsigned long data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_ulong_variance (const unsigned long data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_ulong_sd (const unsigned long data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_ulong_variance_with_fixed_mean (const unsigned long data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_ulong_sd_with_fixed_mean (const unsigned long data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_ulong_absdev (const unsigned long data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_ulong_skew (const unsigned long data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_ulong_kurtosis (const unsigned long data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_ulong_lag1_autocorrelation (const unsigned long data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_ulong_covariance (const unsigned long data1[], const size_t stride1,const unsigned long data2[], const size_t stride2, const size_t n); GSL_EXPORT double gsl_stats_ulong_variance_m (const unsigned long data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_ulong_sd_m (const unsigned long data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_ulong_absdev_m (const unsigned long data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_ulong_skew_m_sd (const unsigned long data[], const size_t stride, const size_t n, const double mean, const double sd); GSL_EXPORT double gsl_stats_ulong_kurtosis_m_sd (const unsigned long data[], const size_t stride, const size_t n, const double mean, const double sd); GSL_EXPORT double gsl_stats_ulong_lag1_autocorrelation_m (const unsigned long data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_ulong_covariance_m (const unsigned long data1[], const size_t stride1,const unsigned long data2[], const size_t stride2, const size_t n, const double mean1, const double mean2); GSL_EXPORT double gsl_stats_ulong_pvariance (const unsigned long data1[], const size_t stride1, const size_t n1, const unsigned long data2[], const size_t stride2, const size_t n2); GSL_EXPORT double gsl_stats_ulong_ttest (const unsigned long data1[], const size_t stride1, const size_t n1, const unsigned long data2[], const size_t stride2, const size_t n2); GSL_EXPORT unsigned long gsl_stats_ulong_max (const unsigned long data[], const size_t stride, const size_t n); GSL_EXPORT unsigned long gsl_stats_ulong_min (const unsigned long data[], const size_t stride, const size_t n); GSL_EXPORT void gsl_stats_ulong_minmax (unsigned long * min, unsigned long * max, const unsigned long data[], const size_t stride, const size_t n); GSL_EXPORT size_t gsl_stats_ulong_max_index (const unsigned long data[], const size_t stride, const size_t n); GSL_EXPORT size_t gsl_stats_ulong_min_index (const unsigned long data[], const size_t stride, const size_t n); GSL_EXPORT void gsl_stats_ulong_minmax_index (size_t * min_index, size_t * max_index, const unsigned long data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_ulong_median_from_sorted_data (const unsigned long sorted_data[], const size_t stride, const size_t n) ; GSL_EXPORT double gsl_stats_ulong_quantile_from_sorted_data (const unsigned long sorted_data[], const size_t stride, const size_t n, const double f) ; __END_DECLS #endif /* __GSL_STATISTICS_ULONG_H__ */
{ "alphanum_fraction": 0.7988505747, "avg_line_length": 63.2727272727, "ext": "h", "hexsha": "c08392883cce19dfd8e7bd72722c1cc6904392f0", "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": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_statistics_ulong.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "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": "dynaryu/vaws", "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_statistics_ulong.h", "max_line_length": 205, "max_stars_count": null, "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_statistics_ulong.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1164, "size": 4872 }
/* * 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 <string.h> #include <mpi.h> #include <gsl/gsl_rng.h> #include "dnest.h" #include "model1.h" int which_level_update; int num_params; DNestFptrSet *fptrset_thismodel; void model1() { int i, argc=0, narg=6; char **argv; argv = malloc(narg*sizeof(char *)); for(i=0; i<narg; i++) { argv[i] = malloc(200*sizeof(char)); } strcpy(argv[argc++], "dnest"); strcpy(argv[argc++], "-s"); strcpy(argv[argc++], "restart_dnest1.txt"); strcpy(argv[argc++], "-l"); //level-dependnet sampling strcpy(argv[argc++], "-g"); strcpy(argv[argc++], "1"); /* setup szie of modeltype, which is used for dnest */ num_params = 20; /* allocate memory */ fptrset_thismodel = dnest_malloc_fptrset(); /* setup functions used for dnest*/ fptrset_thismodel->from_prior = from_prior_thismodel; fptrset_thismodel->log_likelihoods_cal = log_likelihoods_cal_thismodel; fptrset_thismodel->log_likelihoods_cal_initial = log_likelihoods_cal_thismodel; fptrset_thismodel->log_likelihoods_cal_restart = log_likelihoods_cal_thismodel; fptrset_thismodel->perturb = perturb_thismodel; fptrset_thismodel->print_particle = print_particle_thismodel; fptrset_thismodel->restart_action = restart_action_model1; /* run dnest */ dnest(argc, argv, fptrset_thismodel, num_params, NULL, NULL, NULL, "./", "OPTIONS1", NULL, NULL); /* free memory */ dnest_free_fptrset(fptrset_thismodel); for(i=0; i<narg; i++) free(argv[i]); free(argv); } /*====================================================*/ /* users responsible for following struct definitions */ void from_prior_thismodel(void *model) { int i; double *params = (double *)model; for(i=0; i<num_params; i++) { params[i] = -0.5 + dnest_rand(); } } double log_likelihoods_cal_thismodel(const void *model) { double *params = (double *)model; double logL; const double u = 0.01; const double v = 0.1; const double C = log(1.0/sqrt(2*M_PI)); double logl1 = num_params*(C - log(u)); double logl2 = num_params*(C - log(v)); int i; for(i=0; i<num_params; i++) { logl1 += -0.5*pow(( params[i] - 0.031)/u, 2); logl2 += -0.5*pow( params[i]/v, 2); } logl1 += log(100.); double max = fmax(logl1, logl2); logL = log( exp(logl1-max) + exp(logl2-max) ) + max; return logL; } double perturb_thismodel(void *model) { double *params = (double *)model; double logH = 0.0, width, limit1, limit2; int which = dnest_rand_int(num_params), which_level; int size_levels; which_level_update = dnest_get_which_level_update(); size_levels = dnest_get_size_levels(); which_level = which_level_update > (size_levels - 20)?(size_levels-20):which_level_update; if(which_level > 0) { limit1 = limits[(which_level-1) * num_params *2 + which *2 ]; limit2 = limits[(which_level-1) * num_params *2 + which *2 + 1]; } else { limit1 = -0.5; limit2 = 0.5; } width = (limit2 - limit1); params[which] += width * dnest_randh(); dnest_wrap(&params[which], limit1, limit2); return logH; } void print_particle_thismodel(FILE *fp, const void *model) { int i; double *params = (double *)model; for(i=0; i<num_params; i++) { fprintf(fp, "%f ", params[i] ); } fprintf(fp, "\n"); } /*========================================================*/ void restart_action_model1(int iflag) { return; }
{ "alphanum_fraction": 0.64453125, "avg_line_length": 23.7350993377, "ext": "c", "hexsha": "81959ee38130733ac048f492966bd841474c05a6", "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/model1.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/model1.c", "max_line_length": 99, "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/model1.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": 1089, "size": 3584 }
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_sf_expint.h> #include "ccl.h" //maths helper function for NFW profile static double helper_fx(double x){ double f; f = log(1.+x)-x/(1.+x); return f; } //cosmo: ccl cosmology object containing cosmological parameters //c: halo concentration, needs to be consistent with halo size definition //halomass: halo mass //massdef_delta: mass definition, overdensity relative to mean matter density //a: scale factor //r: radii at which to calculate output //nr: number of radii for calculation //rho_r: stores densities at r //returns void void ccl_halo_profile_nfw(ccl_cosmology *cosmo, double c, double halomass, double massdef_delta_m, double a, double *r, int nr, double *rho_r, int *status) { //haloradius: halo radius for mass definition //rs: scale radius double haloradius, rs; haloradius = r_delta(cosmo, halomass, a, massdef_delta_m, status); rs = haloradius/c; //rhos: NFW density parameter double rhos; rhos = halomass/(4.*M_PI*(rs*rs*rs)*helper_fx(c)); int i; double x; for(i=0; i < nr; i++) { x = r[i]/rs; rho_r[i] = rhos/(x*(1.+x)*(1.+x)); } return; } //cosmo: ccl cosmology object containing cosmological parameters //c: halo concentration, needs to be consistent with halo size definition //halomass: halo mass //massdef_delta: mass definition, overdensity relative to mean matter density //a: scale factor //rp: radius at which to calculate output //nr: number of radii for calculation //sigma_r: stores surface mass density (integrated along line of sight) at given projected rp //returns void void ccl_projected_halo_profile_nfw(ccl_cosmology *cosmo, double c, double halomass, double massdef_delta_m, double a, double *rp, int nr, double *sigma_r, int *status) { //haloradius: halo radius for mass definition //rs: scale radius double haloradius, rs; haloradius = r_delta(cosmo, halomass, a, massdef_delta_m, status); rs = haloradius/c; //rhos: NFW density parameter double rhos; rhos = halomass/(4.*M_PI*(rs*rs*rs)*helper_fx(c)); double x; int i; for(i=0; i < nr; i++){ x = rp[i]/rs; if (x==1.){ sigma_r[i] = 2.*rs*rhos/3.; } else if (x<1.){ sigma_r[i] = 2.*rs*rhos*(1.-2.*atanh(sqrt(fabs((1.-x)/(1.+x))))/sqrt(fabs(1.-x*x)))/(x*x-1.); } else { sigma_r[i] = 2.*rs*rhos*(1.-2.*atan(sqrt(fabs((1.-x)/(1.+x))))/sqrt(fabs(1.-x*x)))/(x*x-1.); } } return; } //maths helper function assuming NFW approximation static double helper_solve_cvir(double c, void *rhs_pointer){ double rhs = *(double*)rhs_pointer; return (log(1.+c)-c/(1.+c))/(c*c*c) - rhs; } //solve for cvir from different mass definition iteratively, assuming NFW profile. static double solve_cvir(ccl_cosmology *cosmo, double rhs, double initial_guess, int *status){ int rootstatus; int iter = 0, max_iter = 100; const gsl_root_fsolver_type *T; gsl_root_fsolver *s; double cvir; double c_lo = 0.1, c_hi = initial_guess*100.; gsl_function F; F.function = &helper_solve_cvir; F.params = &rhs; T = gsl_root_fsolver_brent; s = gsl_root_fsolver_alloc (T); if (s != NULL) { gsl_root_fsolver_set (s, &F, c_lo, c_hi); do { iter++; gsl_root_fsolver_iterate (s); cvir = gsl_root_fsolver_root (s); c_lo = gsl_root_fsolver_x_lower (s); c_hi = gsl_root_fsolver_x_upper (s); rootstatus = gsl_root_test_interval (c_lo, c_hi, 0, 0.0001); } while (rootstatus == GSL_CONTINUE && iter < max_iter); gsl_root_fsolver_free(s); // Check for errors if (rootstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(rootstatus, "ccl_haloprofile.c: solve_cvir():"); *status = CCL_ERROR_PROFILE_ROOT; ccl_cosmology_set_status_message(cosmo, "ccl_haloprofile.c: solve_cvir(): Root finding failure\n"); return NAN; } else { return cvir; } } else { *status = CCL_ERROR_MEMORY; return NAN; } } // Structure to hold parameters of integrand_einasto typedef struct{ ccl_cosmology *cosmo; double alpha, rs; } Int_Einasto_Par; static double integrand_einasto(double r, void *params){ Int_Einasto_Par *p = (Int_Einasto_Par *)params; double alpha = p->alpha; double rs = p->rs; return 4.*M_PI*r*r*exp(-2.*(pow(r/rs,alpha)-1)/alpha); } //integrate einasto profile to get normalization of rhos static double integrate_einasto(ccl_cosmology *cosmo, double R, double alpha, double rs, int *status){ int qagstatus; double result = 0, eresult; Int_Einasto_Par ipar; gsl_function F; gsl_integration_workspace *w = NULL; w = gsl_integration_workspace_alloc(1000); if (w == NULL) { *status = CCL_ERROR_MEMORY; } if (*status == 0) { // Structure required for the gsl integration ipar.cosmo = cosmo; ipar.alpha = alpha; ipar.rs = rs; F.function = &integrand_einasto; F.params = &ipar; // Actually does the integration qagstatus = gsl_integration_qag( &F, 0, R, 0, 0.0001, 1000, 3, w, &result, &eresult); // Check for errors if (qagstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(qagstatus, "ccl_haloprofile.c: integrate_einasto():"); *status = CCL_ERROR_PROFILE_INT; ccl_cosmology_set_status_message(cosmo, "ccl_haloprofile.c: integrate_einasto(): Integration failure\n"); result = NAN; } } // Clean up gsl_integration_workspace_free(w); return result; } //cosmo: ccl cosmology object containing cosmological parameters //c: halo concentration, needs to be consistent with halo size definition //halomass: halo mass //massdef_delta: mass definition, overdensity relative to mean matter density //a: scale factor //r: radii at which to calculate output //nr: number of radii for calculation //rho_r: stores densities at r //returns void void ccl_halo_profile_einasto(ccl_cosmology *cosmo, double c, double halomass, double massdef_delta_m, double a, double *r, int nr, double *rho_r, int *status) { //haloradius: halo radius for mass definition //rs: scale radius double haloradius, rs; haloradius = r_delta(cosmo, halomass, a, massdef_delta_m, status); rs = haloradius/c; //nu: peak height, https://arxiv.org/pdf/1401.1216.pdf eqn1 //alpha: Einasto parameter, https://arxiv.org/pdf/1401.1216.pdf eqn5 double nu; double alpha; //calibrated relation with nu, with virial mass double Mvir; double Delta_v; Delta_v = Dv_BryanNorman(cosmo, a, status); //virial definition, if odelta is this, the definition is virial. if (massdef_delta_m<Delta_v+1 && massdef_delta_m>Delta_v-1){ //allow rounding of virial definition Mvir = halomass; } else{ double rhs; //NFW equation for cvir: f(Rvir/Rs)/f(c)=(Rvir^3*Delta_v)/(R^3*massdef) -> f(cvir)/cvir^3 = rhs rhs = (helper_fx(c)*(rs*rs*rs)*Delta_v)/((haloradius*haloradius*haloradius)*massdef_delta_m); Mvir = halomass*helper_fx(solve_cvir(cosmo, rhs, c, status))/helper_fx(c); } nu = 1.686/ccl_sigmaM(cosmo, log10(Mvir), a, status); //delta_c_Tinker alpha = 0.155 + 0.0095*nu*nu; //rhos: scale density double rhos; rhos = halomass/integrate_einasto(cosmo, haloradius, alpha, rs, status); //normalize int i; for(i=0; i < nr; i++) { rho_r[i] = rhos*exp(-2.*(pow(r[i]/rs,alpha)-1.)/alpha); } return; } // Structure to hold parameters of integrand_hernquist typedef struct{ ccl_cosmology *cosmo; double rs; } Int_Hernquist_Par; static double integrand_hernquist(double r, void *params){ Int_Hernquist_Par *p = (Int_Hernquist_Par *)params; double rs = p->rs; return 4.*M_PI*r*r/((r/rs)*(1.+r/rs)*(1.+r/rs)*(1.+r/rs)); } //integrate hernquist profile to get normalization of rhos static double integrate_hernquist(ccl_cosmology *cosmo, double R, double rs, int *status){ int qagstatus; double result = 0, eresult; Int_Hernquist_Par ipar; gsl_function F; gsl_integration_workspace *w = NULL; w = gsl_integration_workspace_alloc(1000); if (w == NULL) { *status = CCL_ERROR_MEMORY; } if (*status == 0) { // Structure required for the gsl integration ipar.cosmo = cosmo; ipar.rs = rs; F.function = &integrand_hernquist; F.params = &ipar; // Actually does the integration qagstatus = gsl_integration_qag( &F, 0, R, 0, 0.0001, 1000, 3, w, &result, &eresult); // Check for errors if (qagstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(qagstatus, "ccl_haloprofile.c: integrate_hernquist():"); *status = CCL_ERROR_PROFILE_INT; ccl_cosmology_set_status_message(cosmo, "ccl_haloprofile.c: integrate_hernquist(): Integration failure\n"); result = NAN; } } // Clean up gsl_integration_workspace_free(w); return result; } //cosmo: ccl cosmology object containing cosmological parameters //c: halo concentration, needs to be consistent with halo size definition //halomass: halo mass //massdef_delta: mass definition, overdensity relative to mean matter density //a: scale factor //r: radii at which to calculate output //nr: number of radii for calculation //rho_r: stores densities at r //returns void void ccl_halo_profile_hernquist(ccl_cosmology *cosmo, double c, double halomass, double massdef_delta_m, double a, double *r, int nr, double *rho_r, int *status) { //haloradius: halo radius for mass definition //rs: scale radius double haloradius, rs; haloradius = r_delta(cosmo, halomass, a, massdef_delta_m, status); rs = haloradius/c; //rhos: scale density double rhos; rhos = halomass/integrate_hernquist(cosmo, haloradius, rs, status); //normalize int i; double x; for(i=0; i < nr; i++) { x = r[i]/rs; rho_r[i] = rhos/(x*pow((1.+x),3)); } return; }
{ "alphanum_fraction": 0.6414701146, "avg_line_length": 29.654494382, "ext": "c", "hexsha": "83a59b2b4c39d696043fd33b8d247548d6d0b334", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-02-10T07:35:07.000Z", "max_forks_repo_forks_event_min_datetime": "2021-02-10T07:35:07.000Z", "max_forks_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "benediktdiemer/CCL", "max_forks_repo_path": "src/ccl_haloprofile.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "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": "benediktdiemer/CCL", "max_issues_repo_path": "src/ccl_haloprofile.c", "max_line_length": 115, "max_stars_count": null, "max_stars_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "benediktdiemer/CCL", "max_stars_repo_path": "src/ccl_haloprofile.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3047, "size": 10557 }
#ifndef CWANNIER_DOS_UTIL #define CWANNIER_DOS_UTIL #include <stdlib.h> #include <stdio.h> #include "bstrlib/bstrlib.h" #include <gsl/gsl_matrix.h> gsl_matrix* parse_R_from_bs(char *b1, char *b2, char *b3); int set_R_row(gsl_matrix *R, char *b, int row); double* linspace(double a, double b, int num); #endif //CWANNIER_DOS_UTIL
{ "alphanum_fraction": 0.75, "avg_line_length": 23.7142857143, "ext": "h", "hexsha": "58a4e3c3d94a6d69f326453fb6e61a138eb42522", "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": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tflovorn/cwannier", "max_forks_repo_path": "dos_util.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8", "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": "tflovorn/cwannier", "max_issues_repo_path": "dos_util.h", "max_line_length": 58, "max_stars_count": null, "max_stars_repo_head_hexsha": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tflovorn/cwannier", "max_stars_repo_path": "dos_util.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 106, "size": 332 }
#pragma once #ifndef UPCA_ARCH_H #error "Don't include this file directly. Use #include <upca/upca.h>." #endif #include <iostream> #include <memory> #include <sstream> #include <string> #include <gsl/gsl> #include <fcntl.h> #include <stdio.h> #include <sys/stat.h> #include <sys/types.h> #ifdef JEVENTS_FOUND #include <inttypes.h> #include <unistd.h> #ifdef __cplusplus extern "C" { #endif #include <jevents.h> #include <rdpmc.h> #ifdef __cplusplus } #endif #include <linux/perf_event.h> #include <sys/ioctl.h> #endif namespace upca { std::ostream &operator<<(std::ostream &os, const struct perf_event_attr &c); namespace arch { namespace x86_64 { class x86_64_base_pmu { public: uint64_t timestamp_begin() { unsigned high, low; __asm__ volatile("CPUID\n\t" "RDTSC\n\t" "mov %%edx, %0\n\t" "mov %%eax, %1\n\t" : "=r"(high), "=r"(low)::"%rax", "%rbx", "%rcx", "%rdx"); return static_cast<uint64_t>(high) << 32 | low; } uint64_t timestamp_end() { unsigned high, low; __asm__ volatile("RDTSCP\n\t" "mov %%edx,%0\n\t" "mov %%eax,%1\n\t" "CPUID\n\t" : "=r"(high), "=r"(low)::"%rax", "%rbx", "%rcx", "%rdx"); return static_cast<uint64_t>(high) << 32 | low; } }; #ifdef JEVENTS_FOUND #ifndef __APPLE__ /* * SYSCALL_HANDLED(601, pmc_init) int counter, int type, int mode * SYSCALL_HANDLED(602, pmc_start) * SYSCALL_HANDLED(603, pmc_stop) * SYSCALL_HANDLED(604, pmc_reset) * * Yes, the interface is that fucked up. counter is either int or unsigned long, * depending on the syscall … */ static inline long mck_pmc_init(int counter, int type, unsigned mode) { return syscall(601, counter, type, mode); } static inline long mck_pmc_start(unsigned long counter) { return syscall(602, counter); } static inline long mck_pmc_stop(unsigned long counter) { return syscall(603, counter); } static inline long mck_pmc_reset(int counter) { return syscall(604, counter); } static inline int mck_is_mckernel() { return syscall(732) == 0; } #else static inline int mck_is_mckernel() { return 0; } #endif class resolver { public: resolver(); struct perf_event_attr resolve(const std::string &name) const; }; class fd { int fd_; public: explicit fd(int fd) : fd_(fd) {} fd(std::nullptr_t = nullptr) : fd_(-1) {} ~fd() { if (fd_ != -1) { close(fd_); } } fd(fd &&l) { fd_ = l.fd_; l.fd_ = -1; } explicit operator bool() { return fd_ != -1; } explicit operator int() { return fd_; } friend bool operator==(const fd &l, const fd &r) { return l.fd_ == r.fd_; } friend bool operator!=(const fd &l, const fd &r) { return !(l == r); } }; static inline std::unique_ptr<fd> make_perf_fd(struct perf_event_attr &attr) { const int fd = perf_event_open(&attr, 0, -1, -1, 0); if (fd < 0) { std::ostringstream os; os << "perf_event_open() failed: " << errno << strerror(errno) << std::endl; throw std::runtime_error(os.str()); } return std::make_unique<class fd>(fd); } static uint64_t rdpmc(const uint32_t counter) { uint32_t low, high; __asm__ volatile("rdpmc" : "=a"(low), "=d"(high) : "c"(counter)); return static_cast<uint64_t>(high) << 32 | low; } enum msrs { IA32_PMC_BASE = 0x0c1, IA32_PERFEVTSEL_BASE = 0x186, IA32_FIXED_CTR_CTRL = 0x38d, IA32_PERF_GLOBAL_STATUS = 0x38e, IA32_PERF_GLOBAL_CTRL = 0x38f, IA32_PERF_GLOBAL_OVF_CTRL = 0x390, IA32_PERF_CAPABILITIES = 0x345, IA32_DEBUGCTL = 0x1d9, }; static inline void cpuid(const int code, uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d) { asm volatile("cpuid" : "=a"(*a), "=b"(*b), "=c"(*c), "=d"(*d) : "a"(code)); } #define MASK(v, high, low) ((v >> low) & ((1 << (high - low + 1)) - 1)) template <typename POLICY> static void pmu_info(const POLICY &msr) { uint32_t eax, ebx, ecx, edx; cpuid(0x1, &eax, &ebx, &ecx, &edx); std::cout << std::hex; std::cout << "EAX: " << eax << std::endl; std::cout << "EBX: " << ebx << std::endl; std::cout << "ECX: " << ecx << std::endl; std::cout << "EDX: " << edx << std::endl; if (ecx & (1 << 15)) { const uint64_t caps = msr.rdmsr(IA32_PERF_CAPABILITIES); const int vmm_freeze = MASK(caps, 12, 12); std::cout << "Caps: " << caps << std::endl; std::cout << "VMM Freeze: " << std::boolalpha << static_cast<bool>(vmm_freeze) << std::noboolalpha << std::endl; if (vmm_freeze) { const uint64_t debugctl = msr.rdmsr(IA32_DEBUGCTL); msr.wrmsr(IA32_DEBUGCTL, debugctl & ~(1 << 14)); } } cpuid(0xa, &eax, &ebx, &ecx, &edx); const unsigned version = MASK(eax, 7, 0); const unsigned counters = MASK(eax, 15, 8); const unsigned width = MASK(eax, 23, 16); const unsigned ffpc = MASK(edx, 4, 0); const unsigned ff_width = MASK(edx, 12, 5); std::cout << "EAX: " << eax << std::endl; std::cout << "EBX: " << ebx << std::endl; std::cout << "ECX: " << ecx << std::endl; std::cout << "EDX: " << edx << std::endl; std::cout << std::dec; std::cout << "PMC version " << version << std::endl; std::cout << "PMC counters: " << counters << std::endl; std::cout << "PMC width: " << width << std::endl; std::cout << "FFPCs: " << ffpc << ", width: " << ff_width << std::endl; } struct x86_pmc_base { virtual ~x86_pmc_base(); virtual gsl::span<uint64_t>::index_type start(gsl::span<uint64_t>) = 0; virtual gsl::span<uint64_t>::index_type stop(gsl::span<uint64_t>) = 0; }; struct mck_mck_policy { static long init(const int active, const uint64_t config) { return mck_pmc_init(active, gsl::narrow<int>(config), 0x4); } /* writes MSR_IA32_PMC0 + i to 0 */ static void reset(const int i) { mck_pmc_reset(i); } /* sets and clears bits in MSR_PERF_GLOBAL_CTRL */ static void start(const unsigned long mask) { const auto err = mck_pmc_start(mask); if (err) { std::cerr << "Error starting PMCs" << std::endl; } } static void stop(const unsigned long mask) { const auto err = mck_pmc_stop(mask); if (err) { std::cerr << "Error stopping PMCs" << std::endl; } } static uint64_t read(const unsigned i) { return rdpmc(i); } }; class msr_mck { public: msr_mck() {} uint64_t rdmsr(const uint32_t reg) const { return static_cast<unsigned long>(syscall(850, reg)); } auto wrmsr(const uint32_t reg, const uint64_t val) const { /* always returns 0 */ return syscall(851, reg, val); } }; class msr_linux { std::unique_ptr<fd> fd_; static unsigned cpu() { int cpu = sched_getcpu(); if (cpu < 0) { using namespace std::string_literals; throw std::runtime_error("Error getting CPU number: "s + strerror(errno) + " (" + std::to_string(errno) + ")\n"); } /* TODO: check thread affinity mask * - has a single CPU * - this single CPU is this CPU */ return static_cast<unsigned>(cpu); } public: msr_linux() : fd_(std::make_unique<fd>(open( ("/dev/cpu/" + std::to_string(cpu()) + "/msr").c_str(), O_RDWR))) {} uint64_t rdmsr(const uint32_t reg) const { uint64_t v; const ssize_t ret = pread(static_cast<int>(*fd_), &v, sizeof(v), reg); if (ret != sizeof(v)) { std::cerr << "Reading MSR " << std::hex << reg << std::dec << " failed." << std::endl; } return v; } auto wrmsr(const uint32_t reg, const uint64_t val) const { const ssize_t ret = pwrite(static_cast<int>(*fd_), &val, sizeof(val), reg); if (ret != sizeof(val)) { std::cerr << "Writing MSR " << std::hex << reg << std::dec << " failed." << std::endl; } return ret; } }; template <typename MSR> class rawmsr_policy : MSR { uint64_t global_ctrl_; public: rawmsr_policy() : global_ctrl_(this->rdmsr(IA32_PERF_GLOBAL_CTRL)) { // pmu_info(static_cast<MSR&>(*this)); } ~rawmsr_policy() { this->wrmsr(IA32_PERF_GLOBAL_CTRL, global_ctrl_); } int init(const int i, const uint64_t config) { const uint64_t v = (1 << 22) | (1 << 16) | config; this->wrmsr(IA32_PERFEVTSEL_BASE + static_cast<uint32_t>(i), v); return 0; } void reset(const int i) { this->wrmsr(IA32_PMC_BASE + static_cast<uint32_t>(i), 0); } void start(const unsigned long mask) { this->wrmsr(IA32_PERF_GLOBAL_OVF_CTRL, 0); this->wrmsr(IA32_PERF_GLOBAL_CTRL, mask); } void stop(const unsigned long /* mask */) { this->wrmsr(IA32_PERF_GLOBAL_CTRL, 0); const uint64_t ovf = this->rdmsr(IA32_PERF_GLOBAL_STATUS); if (ovf) { std::cout << "Overflow: " << std::hex << ovf << std::dec << std::endl; this->wrmsr(IA32_PERF_GLOBAL_OVF_CTRL, 0); } } /* Should be equivalent to rdpmc instruction */ uint64_t read(const unsigned i) { return this->rdmsr(IA32_PMC_BASE + i); } }; template <typename ACCESS> class msr_pmc final : ACCESS, public x86_pmc_base { unsigned long active_mask_ = 0; int active = 0; public: using resolver_type = resolver; template <typename T> msr_pmc(const T &pmcs) { for (const auto &pmc : pmcs) { const auto err = ACCESS::init(active, pmc.data().config); if (err) { std::cerr << "Error configuring PMU " << pmc.name() << " with " << std::hex << pmc.data().config << std::dec << std::endl; continue; } ++active; } active_mask_ = static_cast<unsigned long>((1 << active) - 1); } gsl::span<uint64_t>::index_type start(gsl::span<uint64_t>) override { for (int i = 0; i < active; ++i) { ACCESS::reset(i); } ACCESS::start(active_mask_); return active; } gsl::span<uint64_t>::index_type stop(gsl::span<uint64_t> buf) override { ACCESS::stop(active_mask_); for (int i = 0; i < active; ++i) { buf[i] = ACCESS::read(static_cast<uint32_t>(i)); } return active; } }; using mck_rawmsr = msr_pmc<rawmsr_policy<msr_mck>>; using mck_mckmsr = msr_pmc<mck_mck_policy>; using linux_rawmsr = msr_pmc<rawmsr_policy<msr_linux>>; class linux_jevents final : public x86_pmc_base { struct rdpmc_t { struct rdpmc_ctx ctx; int close = 0; rdpmc_t(struct perf_event_attr attr) { const int err = rdpmc_open_attr(&attr, &ctx, nullptr); if (err) { throw std::runtime_error(std::to_string(errno) + ' ' + strerror(errno)); } close = 1; } ~rdpmc_t() { if (close) { rdpmc_close(&ctx); } } rdpmc_t(const rdpmc_t &) = delete; rdpmc_t(rdpmc_t &&rhs) { this->ctx = rhs.ctx; this->close = rhs.close; rhs.close = 0; } uint64_t read() { return rdpmc_read(&ctx); } }; std::vector<rdpmc_t> rdpmc_ctxs; public: using resolver_type = resolver; template <typename T> linux_jevents(const T &pmcs) { for (const auto &pmc : pmcs) { rdpmc_ctxs.emplace_back(pmc.data()); } } gsl::span<uint64_t>::index_type start(gsl::span<uint64_t> buf) override { int idx = 0; for (auto &&pmc : rdpmc_ctxs) { buf[idx] = pmc.read(); ++idx; } return idx; } gsl::span<uint64_t>::index_type stop(gsl::span<uint64_t> buf) override { int idx = 0; for (auto &&pmc : rdpmc_ctxs) { buf[idx] = pmc.read() - buf[idx]; ++idx; } return idx; } }; class linux_perf final : public x86_pmc_base { std::vector<std::unique_ptr<fd>> perf_fds; public: using resolver_type = resolver; template <typename T> linux_perf(const T &pmcs) { for (const auto &pmc : pmcs) { struct perf_event_attr pe; memset(&pe, 0, sizeof(pe)); const auto &attr = pmc.data(); pe.config = attr.config; pe.config1 = attr.config1; pe.config2 = attr.config2; pe.type = attr.type; pe.size = attr.size; // attr.disabled = 1; pe.exclude_kernel = 1; pe.exclude_hv = 1; try { perf_fds.push_back(make_perf_fd(pe)); } catch (const std::exception &e) { std::cerr << pmc.name() << ": " << e.what() << std::endl; } } } gsl::span<uint64_t>::index_type start(gsl::span<uint64_t>) override { for (const auto &perf_fd : perf_fds) { if (ioctl(static_cast<int>(*perf_fd), PERF_EVENT_IOC_RESET, 0)) { std::cerr << "Error in ioctl\n"; } } return static_cast<gsl::span<uint64_t>::index_type>(perf_fds.size()); } gsl::span<uint64_t>::index_type stop(gsl::span<uint64_t> buf) override { uint64_t v; int idx = 0; for (const auto &perf_fd : perf_fds) { const auto ret = read(static_cast<int>(*perf_fd), &v, sizeof(v)); if (ret < 0) { std::cerr << "perf: Error reading performance counter: " << errno << ": " << strerror(errno) << std::endl; } else if (ret != sizeof(v)) { std::cerr << "perf: Error reading " << sizeof(v) << " bytes." << std::endl; } buf[idx] = v; ++idx; } return idx; } }; template <typename MCK, typename LINUX> class x86_linux_mckernel : public x86_64_base_pmu { std::unique_ptr<x86_pmc_base> backend_; public: using resolver_type = resolver; template <typename T> x86_linux_mckernel(const T &pmcs) : backend_(mck_is_mckernel() ? static_cast<std::unique_ptr<x86_pmc_base>>( std::make_unique<MCK>(pmcs)) : static_cast<std::unique_ptr<x86_pmc_base>>( std::make_unique<LINUX>(pmcs))) {} auto start(gsl::span<uint64_t> o) { return backend_->start(o); } auto stop(gsl::span<uint64_t> o) { return backend_->stop(o); } }; #else struct Reason { static constexpr const char reason[] = "PMC support not compiled in; libjevents missing"; }; class x86_64_pmu : public x86_64_base_pmu { public: using resolver_type = upca::arch::detail::null_resolver<Reason>; template <typename T> x86_64_pmu(const T &) {} gsl::span<uint64_t>::index_type start(gsl::span<uint64_t>) { return 0; } gsl::span<uint64_t>::index_type stop(gsl::span<uint64_t>) { return 0; } }; #endif /* JEVENTS_FOUND */ } // namespace x86_64 } // namespace arch } // namespace upca
{ "alphanum_fraction": 0.6044441329, "avg_line_length": 27.2251908397, "ext": "h", "hexsha": "b2327a1121c075998f385161d92a7db90058ca7c", "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": "e4062fd98d83f4cc57ee04f554540c09c1ca8ccd", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "hannesweisbach/ucpa", "max_forks_repo_path": "include/upca/arch/x86_64.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e4062fd98d83f4cc57ee04f554540c09c1ca8ccd", "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": "hannesweisbach/ucpa", "max_issues_repo_path": "include/upca/arch/x86_64.h", "max_line_length": 88, "max_stars_count": 1, "max_stars_repo_head_hexsha": "e4062fd98d83f4cc57ee04f554540c09c1ca8ccd", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "hannesweisbach/ucpa", "max_stars_repo_path": "include/upca/arch/x86_64.h", "max_stars_repo_stars_event_max_datetime": "2018-08-31T13:51:26.000Z", "max_stars_repo_stars_event_min_datetime": "2018-08-31T13:51:26.000Z", "num_tokens": 4351, "size": 14266 }
/****************************************************************************** CosmoLike Configuration Space Covariances for Projected Galaxy 2-Point Statistics https://github.com/CosmoLike/CosmoCov by CosmoLike developers ******************************************************************************/ #include <math.h> #include <stdlib.h> #include <stdio.h> #include <assert.h> #include <fftw3.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_sf_legendre.h> #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_sf_trig.h> #include <gsl/gsl_sf_erf.h> #define NR_END 1 #define FREE_ARG char* #define EXIT_MISSING_FILE(ein, purpose, filename) if (!ein) {fprintf(stderr, "Could not find %s file %s\n",purpose,filename);exit(1);} static double darg __attribute__((unused)),maxarg1 __attribute__((unused)), maxarg2 __attribute__((unused)); #define FMAX(a,b) (maxarg1=(a), maxarg2=(b), (maxarg1) > (maxarg2) ? (maxarg1) : (maxarg2)) #define FMIN(a,b) (maxarg1=(a), maxarg2=(b), (maxarg1) < (maxarg2) ? (maxarg1) : (maxarg2)) //Note: SQR*SQR....gives undefined warning static double sqrarg; #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 : sqrarg*sqrarg) static double cubearg; #define CUBE(a) ((cubearg=(a)) == 0.0 ? 0.0 : cubearg*cubearg*cubearg) static double pow4arg; #define POW4(a) ((pow4arg=(a)) == 0.0 ? 0.0 : pow4arg*pow4arg*pow4arg*pow4arg) void SVD_inversion(gsl_matrix *cov, gsl_matrix *inverseSVD,int Nmatrix); double interpol2d(double **f, int nx, double ax, double bx, double dx, double x, int ny, double ay, double by, double dy, double y, double lower, double upper); double interpol2d_fitslope(double **f, int nx, double ax, double bx, double dx, double x, int ny, double ay, double by, double dy, double y, double lower); double interpol(double *f, int n, double a, double b, double dx, double x, double lower, double upper); double interpol_fitslope(double *f, int n, double a, double b, double dx, double x, double lower); void free_double_vector(double *v, long nl, long nh); long *long_vector(long nl, long nh); int *int_vector(long nl, long nh); double *create_double_vector(long nl, long nh); void free_double_matrix(double **m, long nrl, long nrh, long ncl, long nch); double **create_double_matrix(long nrl, long nrh, long ncl, long nch); int line_count(char *filename); void error(char *s); void cdgamma(fftw_complex x, fftw_complex *res); double int_gsl_integrate_insane_precision(double (*func)(double, void*),void *arg,double a, double b, double *error, int niter); double int_gsl_integrate_high_precision(double (*func)(double, void*),void *arg,double a, double b, double *error, int niter); double int_gsl_integrate_medium_precision(double (*func)(double, void*),void *arg,double a, double b, double *error, int niter); double int_gsl_integrate_low_precision(double (*func)(double, void*),void *arg,double a, double b, double *error, int niter); double int_gsl_integrate_cov_precision(double (*func)(double, void*),void *arg,double a, double b, double *error, int niter); typedef struct { double pi; double pi_sqr; double twopi; double ln2; double arcmin; double lightspeed; }con; con constants = { 3.14159265358979323846, //pi 9.86960440108935861883, //pisqr 6.28318530717958647693, //twopi 0.69314718, 2.90888208665721580e-4, //arcmin 299792.458 //speed of light km/s }; typedef struct { double low; double medium; double high; double insane; }pre; pre precision= { 1e-2, //low 1e-3, //medium 1e-5, //high 1e-7 //insane }; typedef struct { double a_min; double k_min_mpc; double k_max_mpc; double k_max_mpc_class; double k_min_cH0; double k_max_cH0; double P_2_s_min; double P_2_s_max; double xi_via_hankel_theta_min; double xi_via_hankel_theta_max; double xi_3d_rmin; double xi_3d_rmax; double M_min; double M_max; }lim; lim limits = { // 0.19, //a_min (in order to compute z=4 WFIRST) 1./(1.+10.), //a_min (z=10, needed for CMB lensing) 6.667e-6, //k_min_mpc 1.e3, //k_max_mpc 50., //k_max_mpc_class 2.e-2, //k_min_cH0 3.e+6, //k_max_cH0 0.1,//P_2_s_min 1.0e5,//P_2_s_max 3.0e-7,//xi_via_hankel_theta_min 0.12, //xi_via_hankel_theta_max 1.e-5,//xi_3d_rmin 1.e+0,//xi_3d_rmax 1.e+6, //M_min 1.e+17,//M_max }; typedef struct { int N_a ; int N_k_lin; int N_k_nlin; int N_ell; int N_theta; int N_thetaH; int N_S2; int N_DS; int N_norm; int N_r_3d; int N_k_3d; int N_a_halo; }Ntab; Ntab Ntable = { 100, //N_a 500, //N_k_lin 500, //N_k_nlin 200, //N_ell 200, //N_theta 2048, //N_theta for Hankel 1000, //N_S2 1000, //N_DS 50, //N_norm 50, //N_r_3d 25, //N_k_3d 20, //N_a_halo }; struct cos{ int ORDER ; double vt_max; double vt_min; double vt_bin_max; double vt_bin_min; int ni ; int nj ; }; void SVD_inversion(gsl_matrix *cov, gsl_matrix *inverseSVD,int Nmatrix) { int i,j; gsl_matrix *V=gsl_matrix_calloc(Nmatrix,Nmatrix); gsl_matrix *U=gsl_matrix_calloc(Nmatrix,Nmatrix); gsl_vector *S=gsl_vector_calloc(Nmatrix); gsl_vector *work=gsl_vector_calloc(Nmatrix); gsl_matrix_memcpy(U,cov); gsl_linalg_SV_decomp(U,V,S,work); for (i=0;i<Nmatrix;i++){ gsl_vector *b=gsl_vector_calloc(Nmatrix); gsl_vector *x=gsl_vector_calloc(Nmatrix); gsl_vector_set(b,i,1.0); gsl_linalg_SV_solve(U,V,S,b,x); for (j=0;j<Nmatrix;j++){ gsl_matrix_set(inverseSVD,i,j,gsl_vector_get(x,j)); } gsl_vector_free(b); gsl_vector_free(x); } gsl_matrix_free(V); gsl_matrix_free(U); gsl_vector_free(S); gsl_vector_free(work); } void invert_matrix_colesky(gsl_matrix *A) { gsl_linalg_cholesky_decomp (A); // Adummy will be overwritten */ gsl_linalg_cholesky_invert (A); } double int_gsl_integrate_insane_precision(double (*func)(double, void*),void *arg,double a, double b, double *error, int niter) { double res, err; gsl_integration_cquad_workspace *w = gsl_integration_cquad_workspace_alloc(niter); gsl_function F; F.function = func; F.params = arg; gsl_integration_cquad(&F,a,b,0,precision.insane,w,&res,&err,0); if(NULL!=error) *error=err; gsl_integration_cquad_workspace_free(w); return res; } double int_gsl_integrate_high_precision(double (*func)(double, void*),void *arg,double a, double b, double *error, int niter) { double res, err; gsl_integration_cquad_workspace *w = gsl_integration_cquad_workspace_alloc(niter); gsl_function F; F.function = func; F.params = arg; gsl_integration_cquad(&F,a,b,0,precision.high,w,&res,&err,0); if(NULL!=error) *error=err; gsl_integration_cquad_workspace_free(w); return res; } double int_gsl_integrate_medium_precision(double (*func)(double, void*),void *arg,double a, double b, double *error, int niter) { double res, err; gsl_integration_cquad_workspace *w = gsl_integration_cquad_workspace_alloc(niter); gsl_function F; F.function = func; F.params = arg; gsl_integration_cquad(&F,a,b,0,precision.medium,w,&res,&err,0); if(NULL!=error) *error=err; gsl_integration_cquad_workspace_free(w); return res; } double int_gsl_integrate_low_precision(double (*func)(double, void*),void *arg,double a, double b, double *error, int niter) { double res, err; gsl_integration_cquad_workspace *wcrude = gsl_integration_cquad_workspace_alloc(niter); gsl_function F; F.function = func; F.params = arg; gsl_integration_cquad(&F,a,b,0,precision.low,wcrude,&res,&err,0); if(NULL!=error) *error=err; gsl_integration_cquad_workspace_free(wcrude); return res; } double int_gsl_integrate_cov_precision(double (*func)(double, void*),void *arg,double a, double b, double *error, int niter) { double res, err; gsl_integration_cquad_workspace *wcrude = gsl_integration_cquad_workspace_alloc(niter); gsl_function F; F.function = func; F.params = arg; gsl_integration_cquad(&F,a,b,1e-16,precision.high,wcrude,&res,&err,0); if(NULL!=error) *error=err; gsl_integration_cquad_workspace_free(wcrude); return res; } int line_count(char *filename) { FILE *n; n = fopen(filename,"r"); if (!n){printf("line_count: %s not found!\nEXIT!\n",filename);exit(1);} int ch =0, prev =0,number_of_lines = 0; do { prev = ch; ch = fgetc(n); if(ch == '\n') number_of_lines++; } while (ch != EOF); fclose(n); // last line might not end with \n, but if previous character does, last line is empty if(ch != '\n' && prev !='\n' && number_of_lines != 0) number_of_lines++; return number_of_lines; } double **create_double_matrix(long nrl, long nrh, long ncl, long nch) /* allocate a double matrix with subscript range m[nrl..nrh][ncl..nch] */ { long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; double **m; /* allocate pointers to rows */ m=(double **) calloc(nrow+NR_END,sizeof(double*)); if (!m) error("allocation failure 1 in create_double_matrix()"); m += NR_END; m -= nrl; /* allocate rows and set pointers to them */ m[nrl]=(double *) calloc(nrow*ncol+NR_END,sizeof(double)); if (!m[nrl]) error("allocation failure 2 in create_double_matrix()"); m[nrl] += NR_END; m[nrl] -= ncl; for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; /* return pointer to array of pointers to rows */ return m; } void free_double_matrix(double **m, long nrl, long nrh, long ncl, long nch) /* free a double matrix allocated by create_double_matrix() */ { free((FREE_ARG) (m[nrl]+ncl-NR_END)); free((FREE_ARG) (m+nrl-NR_END)); } double *create_double_vector(long nl, long nh) /* allocate a double vector with subscript range v[nl..nh] */ { double *v; v=(double *) calloc(nh-nl+1+NR_END,sizeof(double)); if (!v) error("allocation failure in double vector()"); return v-nl+NR_END; } int *int_vector(long nl, long nh) /* allocate a int vector with subscript range v[nl..nh] */ { int *v; v=(int *)calloc(nh-nl+1+NR_END, sizeof(int)); if (!v) error("allocation failure in int vector()"); return v-nl+NR_END; } long *long_vector(long nl, long nh) /* allocate a int vector with subscript range v[nl..nh] */ { long *v; v=(long *)calloc(nh-nl+1+NR_END,sizeof(long)); if (!v) error("allocation failure in int vector()"); return v-nl+NR_END; } void free_double_vector(double *v, long nl, long nh) /* free a double vector allocated with vector() */ { free((FREE_ARG) (v+nl-NR_END)); } void error(char *s) { printf("error:%s\n ",s); exit(1); } /* ============================================================ * * Interpolates f at the value x, where f is a double[n] array, * * representing a function between a and b, stepwidth dx. * * 'lower' and 'upper' are powers of a logarithmic power law * * extrapolation. If no extrapolation desired, set these to 0 * * ============================================================ */ double interpol(double *f, int n, double a, double b, double dx, double x, double lower, double upper) { double r; int i; if (x < a) { if (lower==0.) { //error("value too small in interpol"); return 0.0; } return f[0] + lower*(x - a); } r = (x - a)/dx; i = (int)(floor(r)); if (i+1 >= n) { if (upper==0.0) { if (i+1==n) { return f[i]; /* constant extrapolation */ } else { //error("value too big in interpol"); return 0.0; } } else { return f[n-1] + upper*(x-b); /* linear extrapolation */ } } else { return (r - i)*(f[i+1] - f[i]) + f[i]; /* interpolation */ } } double interpol_fitslope(double *f, int n, double a, double b, double dx, double x, double lower) { double r; int i,fitrange; if (x < a) { if (lower==0.) { //error("value too small in interpol"); return 0.0; } return f[0] + lower*(x - a); } r = (x - a)/dx; i = (int)(floor(r)); if (i+1 >= n) { if (n > 50){fitrange =5;} else{fitrange = (int)floor(n/10);} double upper = (f[n-1] - f[n-1-fitrange])/(dx*fitrange); return f[n-1] + upper*(x-b); /* linear extrapolation */ } else { return (r - i)*(f[i+1] - f[i]) + f[i]; /* interpolation */ } } /* ============================================================ * * like interpol, but f beeing a 2d-function * * 'lower' and 'upper' are the powers of a power law extra- * * polation in the second argument * * ============================================================ */ double interpol2d(double **f, int nx, double ax, double bx, double dx, double x, int ny, double ay, double by, double dy, double y, double lower, double upper) { double t, dt, s, ds; int i, j; if (x < ax) { return 0.; // error("value too small in interpol2d"); } if (x > bx) { return 0.;// // printf("%le %le\n",x,bx); // error("value too big in interpol2d"); } t = (x - ax)/dx; i = (int)(floor(t)); dt = t - i; if (y < ay) { return ((1.-dt)*f[i][0] + dt*f[i+1][0]) + (y-ay)*lower; } else if (y > by) { return ((1.-dt)*f[i][ny-1] + dt*f[i+1][ny-1]) + (y-by)*upper; } s = (y - ay)/dy; j = (int)(floor(s)); ds = s - j; if ((i+1==nx)&&(j+1==ny)) { //printf("%d %d\n",i+1,j+1); return (1.-dt)*(1.-ds)*f[i][j]; } if (i+1==nx){ //printf("%d %d\n",i+1,j+1); return (1.-dt)*(1.-ds)*f[i][j]+ (1.-dt)*ds*f[i][j+1]; } if (j+1==ny){ //printf("%d %d\n",i+1,j+1); return (1.-dt)*(1.-ds)*f[i][j]+ dt*(1.-ds)*f[i+1][j]; } return (1.-dt)*(1.-ds)*f[i][j] +(1.-dt)*ds*f[i][j+1] + dt*(1.-ds)*f[i+1][j] + dt*ds*f[i+1][j+1]; } double interpol2d_fitslope(double **f, int nx, double ax, double bx, double dx, double x, int ny, double ay, double by, double dy, double y, double lower) { double t, dt, s, ds, upper; int i, j, fitrange; if (x < ax) { return 0.; // error("value too small in interpol2d"); } if (x > bx) { return 0.; // printf("%le %le\n",x,bx); // error("value too big in interpol2d"); } t = (x - ax)/dx; i = (int)(floor(t)); dt = t - i; if (y < ay) { return ((1.-dt)*f[i][0] + dt*f[i+1][0]) + (y-ay)*lower; } else if (y > by) { if (ny > 25){fitrange =5;} else{fitrange = (int)floor(ny/5);} upper = ((1.-dt)*(f[i][ny-1] - f[i][ny-1-fitrange])+dt*(f[i+1][ny-1] - f[i+1][ny-1-fitrange]))/(dy*fitrange); return ((1.-dt)*f[i][ny-1] + dt*f[i+1][ny-1]) + (y-by)*upper; } s = (y - ay)/dy; j = (int)(floor(s)); ds = s - j; if ((i+1==nx)&&(j+1==ny)) { //printf("%d %d\n",i+1,j+1); return (1.-dt)*(1.-ds)*f[i][j]; } if (i+1==nx){ //printf("%d %d\n",i+1,j+1); return (1.-dt)*(1.-ds)*f[i][j]+ (1.-dt)*ds*f[i][j+1]; } if (j+1==ny){ //printf("%d %d\n",i+1,j+1); return (1.-dt)*(1.-ds)*f[i][j]+ dt*(1.-ds)*f[i+1][j]; } return (1.-dt)*(1.-ds)*f[i][j] +(1.-dt)*ds*f[i][j+1] + dt*(1.-ds)*f[i+1][j] + dt*ds*f[i+1][j+1]; } void cdgamma(fftw_complex x, fftw_complex *res) { double xr, xi, wr, wi, ur, ui, vr, vi, yr, yi, t; xr = (double) x[0]; xi = (double) x[1]; if (xr<0) { wr = 1 - xr; wi = -xi; } else { wr = xr; wi = xi; } ur = wr + 6.00009857740312429; vr = ur * (wr + 4.99999857982434025) - wi * wi; vi = wi * (wr + 4.99999857982434025) + ur * wi; yr = ur * 13.2280130755055088 + vr * 66.2756400966213521 + 0.293729529320536228; yi = wi * 13.2280130755055088 + vi * 66.2756400966213521; ur = vr * (wr + 4.00000003016801681) - vi * wi; ui = vi * (wr + 4.00000003016801681) + vr * wi; vr = ur * (wr + 2.99999999944915534) - ui * wi; vi = ui * (wr + 2.99999999944915534) + ur * wi; yr += ur * 91.1395751189899762 + vr * 47.3821439163096063; yi += ui * 91.1395751189899762 + vi * 47.3821439163096063; ur = vr * (wr + 2.00000000000603851) - vi * wi; ui = vi * (wr + 2.00000000000603851) + vr * wi; vr = ur * (wr + 0.999999999999975753) - ui * wi; vi = ui * (wr + 0.999999999999975753) + ur * wi; yr += ur * 10.5400280458730808 + vr; yi += ui * 10.5400280458730808 + vi; ur = vr * wr - vi * wi; ui = vi * wr + vr * wi; t = ur * ur + ui * ui; vr = yr * ur + yi * ui + t * 0.0327673720261526849; vi = yi * ur - yr * ui; yr = wr + 7.31790632447016203; ur = log(yr * yr + wi * wi) * 0.5 - 1; ui = atan2(wi, yr); yr = exp(ur * (wr - 0.5) - ui * wi - 3.48064577727581257) / t; yi = ui * (wr - 0.5) + ur * wi; ur = yr * cos(yi); ui = yr * sin(yi); yr = ur * vr - ui * vi; yi = ui * vr + ur * vi; if (xr<0) { wr = xr * 3.14159265358979324; wi = exp(xi * 3.14159265358979324); vi = 1 / wi; ur = (vi + wi) * sin(wr); ui = (vi - wi) * cos(wr); vr = ur * yr + ui * yi; vi = ui * yr - ur * yi; ur = 6.2831853071795862 / (vr * vr + vi * vi); yr = ur * vr; yi = ur * vi; } (*res)[0]=yr; (*res)[1]=yi; }
{ "alphanum_fraction": 0.6154537287, "avg_line_length": 27.6865671642, "ext": "c", "hexsha": "3d8a651fad6b31bca30719aff394bda709625a75", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-01-27T11:30:53.000Z", "max_forks_repo_forks_event_min_datetime": "2020-04-21T20:17:05.000Z", "max_forks_repo_head_hexsha": "a3ed2664573f0d47a192302b3326a2f6743c5ce5", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "joezuntz/CosmoCov", "max_forks_repo_path": "cosmolike_core/theory/basics.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "a3ed2664573f0d47a192302b3326a2f6743c5ce5", "max_issues_repo_issues_event_max_datetime": "2021-06-29T16:27:09.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-12T19:43:54.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "joezuntz/CosmoCov", "max_issues_repo_path": "cosmolike_core/theory/basics.c", "max_line_length": 162, "max_stars_count": 9, "max_stars_repo_head_hexsha": "a3ed2664573f0d47a192302b3326a2f6743c5ce5", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "joezuntz/CosmoCov", "max_stars_repo_path": "cosmolike_core/theory/basics.c", "max_stars_repo_stars_event_max_datetime": "2022-01-31T10:39:07.000Z", "max_stars_repo_stars_event_min_datetime": "2020-04-14T00:46:09.000Z", "num_tokens": 5714, "size": 16695 }
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * Set of C routines to use FFTW1.3 library * 2D- FFT's for any size * * * JLP * Version 12/12/2006 (from my BORLAND version) *--------------------------------------------------------*/ #include <stdio.h> #include <math.h> #include "jlp_fftw.h" #include "jlp_num_rename.h" /* JLP2001: To be compatible with "matlab" * I should not normalize by sqrt(nx*ny): */ /* #define NORMALIZE_SQRT */ /* Content of jlp_fftw.h: #include <fftw.h> int FFTW_1D_Y_FLT(float *re, float *im, INT4 *nx, INT4 *ny, INT4 *idim, INT4 *direct); int fftw_1D_Y_float(float *re, float *im, int nx, int ny, int direct); int FFTW_1D_Y_DBLE(double *re, double *im, INT4 *nx, INT4 *ny, INT4 *idim, INT4 *direct); int fftw_1D_Y_double(double *re, double *im, int nx, int ny, int direct); int FFTW_2D_DBLE(double *re, double *im, int *nx, int *ny, int *direct); int fftw_2D_double(double *re, double *im, int nx, int ny, int direct); int FFTW_2D_FLT(float *re, float *im, INT4 *nx, INT4 *ny, INT4 *idim, INT4 *kod); int fftw_2D_float(float *re, float *im, int nx, int ny, int direct); int fftw_setup(int nx, int ny); int FFTW_SETUP(int *nx, int *ny); int fftw_fast(FFTW_COMPLEX *image, int nx, int ny, int direct); int fftw_shutdown(); */ /* Static variables: */ static fftwnd_plan plan_fwd, plan_bkwd; /* #define MAIN_TEST */ #ifdef MAIN_TEST main() { register int i; int nx = 9, ny = 8; double re[128], im[128]; FFTW_COMPLEX* image; char s[80]; for(i = 0; i < nx * ny; i++) { re[i] = i; im[i] = -i; } fftw_2D_double(re, im, nx, ny, 1); fftw_2D_double(re, im, nx, ny, -1); for(i = 0; i < nx * ny; i++) { printf(" i=%d re=%f im=%f \n", i, re[i], im[i]); } printf(" Now going to fast fft..."); gets(s); nx = 388; ny = 128; image = (FFTW_COMPLEX *) malloc(nx * ny * sizeof(FFTW_COMPLEX)); for(i = 0; i < nx * ny; i++) { c_re(image[i]) = i; c_im(image[i]) = -i; } printf("OK, I go on, with nx=%d ny=%d",nx,ny); fftw_setup(nx, ny); fftw_fast(image, nx, ny, 1); fftw_fast(image, nx, ny, -1); fftw_shutdown(); for(i = 0; i < 200; i++) { printf(" i=%d re=%f im=%f \n", i, c_re(image[i]), c_im(image[i])); } gets(s); free(image); } #endif /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * Interface with Fortran routines (with arrays of first dimension = idim) * kod=1, or 2 direct * kod=-1, or -2 inverse * kod=-2, or 2: power spectrum, and phase *--------------------------------------------------------------*/ int FFTW_2D_FLT(float *re, float *im, INT4 *nx, INT4 *ny, INT4 *idim, INT4 *kod) { int nx1, ny1, direct, status; if(*idim != *nx) {printf("FFTW_2D/Fatal error idim=%d while nx=%d \n", *idim, *nx); exit(-1); } if(*kod != 1 && *kod != -1) {printf("FFTW_2D/Fatal error kod=%d (option not yet implemented)\n", *kod); exit(-1); } nx1 = *nx; ny1 = *ny; direct = *kod; status = fftw_2D_float(re, im, nx1, ny1, direct); return(status); } /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * Interface with Fortran routines * kod=1, or 2 direct * kod=-1, or -2 inverse * kod=-2, or 2: power spectrum, and phase * --------------------------------------------------------------*/ int FFTW_1D_Y_DBLE(double *re, double *im, INT4 *nx, INT4 *ny, INT4 *idim, INT4 *kod) { int nx1, ny1, direct, status; if(*idim != *nx) {printf("FFTW_1D_Y/Fatal error idim=%d while nx=%d \n", *idim, *nx); exit(-1); } if(*kod != 1 && *kod != -1) {printf("FFTW_1D_Y/Fatal error kod=%d (option not yet implemented)\n", *kod); exit(-1); } nx1 = *nx; ny1 = *ny; direct = *kod; printf("FFTW_1D_Y/ nx1=%d ny1=%d direct=%d\n",nx1,ny1,direct); status = fftw_1D_Y_double(re, im, nx1, ny1, direct); return(status); } /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * Interface with Fortran routines * kod=1, or 2 direct * kod=-1, or -2 inverse * kod=-2, or 2: power spectrum, and phase * --------------------------------------------------------------*/ int FFTW_1D_Y_FLT(float *re, float *im, INT4 *nx, INT4 *ny, INT4 *idim, INT4 *kod) { int nx1, ny1, direct, status; #ifndef TOTO_ double sum; register int i; #endif if(*idim != *nx) {printf("FFTW_1D_Y_FLT/Fatal error idim=%d while nx=%d \n", *idim, *nx); exit(-1); } if(*kod != 1 && *kod != -1) {printf("FFTW_1D_Y_FLT/Fatal error kod=%d (option not yet implemented)\n", *kod); exit(-1); } nx1 = *nx; ny1 = *ny; direct = *kod; #ifdef DEBUG printf("FFTW_1D_Y_FLT/ nx1=%d ny1=%d direct=%d (fftw)\n",nx1,ny1,direct); #endif #ifndef TOTO_ sum =0; for(i=0; i < ny1; i++) sum += re[nx1/2 + i * nx1]; printf(" Sum of central line = %e and sum/sqrt(ny)=%e \n", sum,sum/sqrt((double)ny1)); #endif status = fftw_1D_Y_float(re, im, nx1, ny1, direct); /* JLP99: to check that FFT is correct: */ /* Not recentred yet !! */ #ifndef TOTO_ for(i=0; i <= 2; i++) printf("re,im [ixc,%d]: %e %e \n",i, re[nx1/2 + i*nx1],im[nx1/2 + i*nx1]); #endif return(status); } /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * 2D FFT routine for double precision arrays * direct = 1 : direct or forward * direct = -1 : reverse or backward * (FORTRAN version) * --------------------------------------------------------------*/ int FFTW_2D_DBLE(double *re, double *im, int *nx, int *ny, int *direct) { int status; status = fftw_2D_double(re, im, *nx, *ny, *direct); return(status); } /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * 2D FFT routine for double precision arrays * direct = 1 : direct or forward * direct = -1 : reverse or backward * * --------------------------------------------------------------*/ int fftw_2D_double(double *re, double *im, int nx, int ny, int direct) { register int i; double norm; int isize; fftwnd_plan plan; fftw_direction dir; FFTW_COMPLEX* in_out; isize = nx * ny; in_out = (FFTW_COMPLEX *) malloc(isize * sizeof(FFTW_COMPLEX)); /* Transfer to complex array structure: */ for(i = 0; i < nx * ny; i++) { c_re(in_out[i]) = re[i]; c_im(in_out[i]) = im[i]; } /* direct = 1 : forward direct = -1 : backward */ dir = (direct == 1) ? FFTW_FORWARD : FFTW_BACKWARD; /* Warning: inversion nx-ny here: */ plan = fftw2d_create_plan(ny, nx, dir, FFTW_ESTIMATE | FFTW_IN_PLACE); if(plan == NULL) {printf("FFTW_2D_DBLE: fatal error creating plan\n"); exit(-1);} /* Compute the FFT: */ fftwnd(plan, 1, in_out, 1, 0, 0, 0, 0); /* Transfer back to original arrays (and normalize by sqrt(nx * ny): */ #ifdef NORMALIZE_SQRT norm = nx * ny; norm = sqrt(norm); for(i = 0; i < nx * ny; i++) { re[i] = c_re(in_out[i]) /norm; im[i] = c_im(in_out[i]) /norm; } #else if(direct == 1) { for(i = 0; i < nx * ny; i++) { re[i] = c_re(in_out[i]); im[i] = c_im(in_out[i]); } } else { norm = nx * ny; for(i = 0; i < nx * ny; i++) { re[i] = c_re(in_out[i]) /norm; im[i] = c_im(in_out[i]) /norm; } } #endif free(in_out); /* Delete plan: */ fftwnd_destroy_plan(plan); return(0); } /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * 2D FFT routine for single precision arrays (for which idim=nx) * (well suited to C arrays since nx=idim...) * direct = 1 : direct or forward * direct = -1 : reverse or backward * --------------------------------------------------------------*/ int fftw_2D_float(float *re, float *im, int nx, int ny, int direct) { register int i; double norm; int isize; fftwnd_plan plan; fftw_direction dir; FFTW_COMPLEX* in_out; isize = nx * ny; in_out = (FFTW_COMPLEX *) malloc(isize * sizeof(FFTW_COMPLEX)); /* Transfer to complex array structure: */ for(i = 0; i < nx * ny; i++) { c_re(in_out[i]) = re[i]; c_im(in_out[i]) = im[i]; } /* direct = 1 : forward direct = -1 : backward */ dir = (direct == 1) ? FFTW_FORWARD : FFTW_BACKWARD; /* Warning: inversion nx-ny here: */ plan = fftw2d_create_plan(ny, nx, dir, FFTW_ESTIMATE | FFTW_IN_PLACE); if(plan == NULL) {printf("fftw_2D_float: fatal error creating plan\n"); exit(-1);} /* Compute the FFT: */ fftwnd(plan, 1, in_out, 1, 0, 0, 0, 0); /* Transfer back to original arrays (and normalize by sqrt(nx * ny): */ #ifdef NORMALIZE_SQRT norm = nx * ny; norm = sqrt(norm); for(i = 0; i < nx * ny; i++) { re[i] = c_re(in_out[i]) /norm; im[i] = c_im(in_out[i]) /norm; } #else if(direct == 1) { for(i = 0; i < nx * ny; i++) { re[i] = c_re(in_out[i]); im[i] = c_im(in_out[i]); } } else { norm = nx * ny; for(i = 0; i < nx * ny; i++) { re[i] = c_re(in_out[i]) /norm; im[i] = c_im(in_out[i]) /norm; } } #endif free(in_out); /* Delete plan: */ fftwnd_destroy_plan(plan); return(0); } /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * 1D FFT routine for single precision arrays * along the columns (for spectroscopic mode) * direct = 1 : direct or forward * direct = -1 : reverse or backward * * --------------------------------------------------------------*/ int fftw_1D_Y_float(float *re, float *im, int nx, int ny, int direct) { register int i, j; double norm; fftw_plan plan; fftw_direction dir; FFTW_COMPLEX* in_out; in_out = (FFTW_COMPLEX *) malloc(ny * sizeof(FFTW_COMPLEX)); if(in_out == NULL) {printf("fftw_1D_Y_float: fatal error allocating memory\n"); exit(-1);} /* direct = 1 : forward direct = -1 : backward */ dir = (direct == 1) ? FFTW_FORWARD : FFTW_BACKWARD; plan = fftw_create_plan(ny, dir, FFTW_ESTIMATE | FFTW_IN_PLACE); if(plan == NULL) {printf("fftw_1D_Y_float: fatal error creating plan\n"); exit(-1);} for(i = 0; i < nx; i++) { /* Transfer to complex array structure: */ for(j = 0; j < ny; j++) { c_re(in_out[j]) = re[i + j * nx]; c_im(in_out[j]) = im[i + j * nx]; } /* Compute the FFT: */ fftw(plan, 1, in_out, 1, 0, 0, 0, 0); /* Transfer back to original arrays (and normalize by sqrt(ny): */ #ifdef NORMALIZE_SQRT norm = sqrt((double)ny); for(j = 0; j < ny; j++) { re[i + j * nx] = c_re(in_out[j]) /norm; im[i + j * nx] = c_im(in_out[j]) /norm; } #else if(direct == 1) { for(j = 0; j < ny; j++) { re[i + j * nx] = c_re(in_out[j]); im[i + j * nx] = c_im(in_out[j]); } } else { norm = (double)ny; for(j = 0; j < ny; j++) { re[i + j * nx] = c_re(in_out[j]) /norm; im[i + j * nx] = c_im(in_out[j]) /norm; } } #endif /* End of loop on i (from 0 to nx-1) */ } free(in_out); /* Delete plan: */ fftw_destroy_plan(plan); return(0); } /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * 1D FFT routine for double precision arrays * along the columns (for spectroscopic mode) * direct = 1 : direct or forward * direct = -1 : reverse or backward * * --------------------------------------------------------------*/ int fftw_1D_Y_double(double *re, double *im, int nx, int ny, int direct) { register int i, j; double norm; fftw_plan plan; fftw_direction dir; FFTW_COMPLEX* in_out; in_out = (FFTW_COMPLEX *) malloc(ny * sizeof(FFTW_COMPLEX)); /* direct = 1 : forward direct = -1 : backward */ dir = (direct == 1) ? FFTW_FORWARD : FFTW_BACKWARD; plan = fftw_create_plan(ny, dir, FFTW_ESTIMATE | FFTW_IN_PLACE); if(plan == NULL) {printf("fftw_1D_Y: fatal error creating plan\n"); exit(-1);} for(i = 0; i < nx; i++) { /* Transfer to complex array structure: */ for(j = 0; j < ny; j++) { c_re(in_out[j]) = re[i + j * nx]; c_im(in_out[j]) = im[i + j * nx]; } /* Compute the FFT: */ fftw(plan, 1, in_out, 1, 0, 0, 0, 0); /* Transfer back to original arrays (and normalize by sqrt(ny): */ #ifdef NORMALIZE_SQRT norm = sqrt((double)ny); for(j = 0; j < ny; j++) { re[i + j * nx] = c_re(in_out[j]) /norm; im[i + j * nx] = c_im(in_out[j]) /norm; } #else if(direct == 1) { for(j = 0; j < ny; j++) { re[i + j * nx] = c_re(in_out[j]); im[i + j * nx] = c_im(in_out[j]); } } else { norm = (double)ny; for(j = 0; j < ny; j++) { re[i + j * nx] = c_re(in_out[j]) /norm; im[i + j * nx] = c_im(in_out[j]) /norm; } } #endif /* End of loop on i (from 0 to nx-1) */ } free(in_out); /* Delete plan: */ fftw_destroy_plan(plan); return(0); } /**************************************************************** * Fortran interface to fftw_setup ****************************************************************/ int FFTW_FSETUP(int *nx, int *ny) { fftw_setup(*nx, *ny); return(0); } /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // fftw_setup, to initialize FFTW routines // Create forward and backward plans // // --------------------------------------------------------------*/ int fftw_setup(int nx, int ny) { char fwd_name[60], bkwd_name[60]; FILE *fp_wisd; int ToOutput; /********************** With "forward" ***************************/ #ifdef BORLAND sprintf(fwd_name,"c:\\tc\\fftw13\\jlp\\fwd_%d.wis",nx); #else sprintf(fwd_name,"/d/fftw/fwd_%d%d.wis",nx,ny); #endif /* Check if wisdom file already exits: */ printf("fftw_setup/Read wisdom file: %s\n",fwd_name); if((fp_wisd = fopen(fwd_name,"r")) == NULL) { printf("fftw_setup/Failure to open wisdom file: %s\n",fwd_name); ToOutput = 1; } else { ToOutput = 0; if(fftw_import_wisdom_from_file(fp_wisd) == FFTW_FAILURE) ToOutput = 1; fclose(fp_wisd); } /* Create "plan" for fftw (speed is wanted for subsequent FFT's) */ /* Warning: inversion nx-ny here: */ plan_fwd = fftw2d_create_plan(ny, nx, FFTW_FORWARD, FFTW_MEASURE | FFTW_IN_PLACE | FFTW_USE_WISDOM); /* Output wisdom file if needed: */ if(ToOutput) { printf("fftw_setup/Write wisdom file: %s\n",fwd_name); if((fp_wisd = fopen(fwd_name,"w")) != NULL) fftw_export_wisdom_to_file(fp_wisd); fclose(fp_wisd); } /********************** With "backward" ***************************/ #ifdef BORLAND sprintf(bkwd_name,"c:\\tc\\fftw13\\jlp\\bk_%d%d.wis",nx,ny); #else sprintf(bkwd_name,"/d/fftw/bk_%d%d.wis",nx,ny); #endif /* Check if wisdom file already exits: */ printf("fftw_setup/Read wisdom file: %s\n",bkwd_name); if((fp_wisd = fopen(bkwd_name,"r")) == NULL) { printf("fftw_setup/Failure to open wisdom file: %s\n",bkwd_name); ToOutput = 1; } else { ToOutput = 0; if(fftw_import_wisdom_from_file(fp_wisd) == FFTW_FAILURE) ToOutput = 1; fclose(fp_wisd); } /* Create "plan" for fftw (speed is wanted for subsequent FFT's) */ /* Warning: inversion nx-ny here: */ plan_bkwd = fftw2d_create_plan(ny, nx, FFTW_BACKWARD, FFTW_MEASURE | FFTW_IN_PLACE | FFTW_USE_WISDOM); /* Output wisdom file if needed: */ if(ToOutput) { printf("fftw_setup/Write wisdom file: %s\n",bkwd_name); if((fp_wisd = fopen(bkwd_name,"w")) != NULL) fftw_export_wisdom_to_file(fp_wisd); fclose(fp_wisd); } return(0); } /************************************************************* * **************************************************************/ int FFTW_SHUTDOWN() { /* Delete plans: */ fftwnd_destroy_plan(plan_fwd); fftwnd_destroy_plan(plan_bkwd); return(0); } /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * 2D FFT routine for double precision fftw_complex arrays * direction = 1 : forward * direction = -1 : backward * Should be called after fftw_setup and before fftw_shutdown * --------------------------------------------------------------*/ int fftw_fast(FFTW_COMPLEX *image, int nx, int ny, int dir) { register int i; double norm; /* Compute the FFT: */ if(dir == 1) fftwnd(plan_fwd, 1, image, 1, 0, 0, 0, 0); else fftwnd(plan_bkwd, 1, image, 1, 0, 0, 0, 0); /* Normalize by sqrt(nx * ny): */ #ifdef NORMALIZE_SQRT norm = nx * ny; norm = sqrt(norm); for(i = 0; i < nx * ny; i++) { c_re(image[i]) /= norm; c_im(image[i]) /= norm; } #else if(dir == -1) { norm = (double)(nx * ny); for(i = 0; i < nx * ny; i++) { c_re(image[i]) /= norm; c_im(image[i]) /= norm; } } #endif return(0); }
{ "alphanum_fraction": 0.5200622829, "avg_line_length": 26.1724137931, "ext": "c", "hexsha": "7fc57d430fd78b544776447f62828d4db5c609ec", "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/fft_num_old/fftw_set.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/fft_num_old/fftw_set.c", "max_line_length": 83, "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/fft_num_old/fftw_set.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5158, "size": 16698 }
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <assert.h> #include <gsl/gsl_math.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_sort.h> #include "cosmocalc.h" gsl_spline *cosmocalc_aexpn2comvdist_spline = NULL; gsl_interp_accel *cosmocalc_aexpn2comvdist_acc = NULL; gsl_spline *cosmocalc_comvdist2aexpn_spline = NULL; gsl_interp_accel *cosmocalc_comvdist2aexpn_acc = NULL; double DH_sqrtok; /* function for integration using gsl integration */ static double comvdist_integ_funct(double a, void *p) { return 1.0/a/a/hubble_noscale(a); } double comvdist_exact(double a) { #define WORKSPACE_NUM 100000 #define ABSERR 0.0 #define RELERR 1e-8 gsl_integration_workspace *workspace; gsl_function F; double result,abserr; workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM); F.function = &comvdist_integ_funct; gsl_integration_qag(&F,a,1.0,ABSERR,RELERR,(size_t) WORKSPACE_NUM,GSL_INTEG_GAUSS51,workspace,&result,&abserr); gsl_integration_workspace_free(workspace); #undef ABSERR #undef RELERR #undef WORKSPACE_NUM return result*DH; } /* init function - some help from Gadget-2 applied here */ void init_cosmocalc_comvdist_table(void) { #define WORKSPACE_NUM 100000 #define ABSERR 0.0 #define RELERR 1e-8 static int initFlag = 1; static int currCosmoNum; gsl_integration_workspace *workspace; gsl_function F; long i; double result,abserr,afact; double comvdist_table[COSMOCALC_COMVDIST_TABLE_LENGTH]; double aexpn_table[COSMOCALC_COMVDIST_TABLE_LENGTH]; size_t sindex[COSMOCALC_COMVDIST_TABLE_LENGTH]; double tmpDouble[COSMOCALC_COMVDIST_TABLE_LENGTH]; if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum) { initFlag = 0; currCosmoNum = cosmoData.cosmoNum; if(cosmoData.OmegaK != 0.0) DH_sqrtok = DH/sqrt(fabs(cosmoData.OmegaK)); else DH_sqrtok = 1.0; workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM); for(i=0;i<COSMOCALC_COMVDIST_TABLE_LENGTH-1;++i) { afact = (AEXPN_MAX - AEXPN_MIN_DIST)/(COSMOCALC_COMVDIST_TABLE_LENGTH-1.0)*((double) i) + AEXPN_MIN_DIST; F.function = &comvdist_integ_funct; F.params = &(cosmoData.OmegaM); gsl_integration_qag(&F,afact,1.0,ABSERR,RELERR,(size_t) WORKSPACE_NUM,GSL_INTEG_GAUSS51,workspace,&result,&abserr); aexpn_table[i] = afact; comvdist_table[i] = result*DH; } aexpn_table[i] = 1.0; comvdist_table[i] = 0.0; gsl_integration_workspace_free(workspace); #undef ABSERR #undef RELERR #undef WORKSPACE_NUM //init the spline and accelerators if(cosmocalc_aexpn2comvdist_spline != NULL) gsl_spline_free(cosmocalc_aexpn2comvdist_spline); cosmocalc_aexpn2comvdist_spline = gsl_spline_alloc(GSL_SPLINE_TYPE,(size_t) (COSMOCALC_COMVDIST_TABLE_LENGTH)); gsl_spline_init(cosmocalc_aexpn2comvdist_spline,aexpn_table,comvdist_table,(size_t) (COSMOCALC_COMVDIST_TABLE_LENGTH)); if(cosmocalc_aexpn2comvdist_acc != NULL) gsl_interp_accel_reset(cosmocalc_aexpn2comvdist_acc); else cosmocalc_aexpn2comvdist_acc = gsl_interp_accel_alloc(); //sort the distances properly gsl_sort_index(sindex,comvdist_table,(size_t) 1,(size_t) (COSMOCALC_COMVDIST_TABLE_LENGTH)); for(i=0;i<COSMOCALC_COMVDIST_TABLE_LENGTH;++i) tmpDouble[i] = comvdist_table[sindex[i]]; for(i=0;i<COSMOCALC_COMVDIST_TABLE_LENGTH;++i) comvdist_table[i] = tmpDouble[i]; for(i=0;i<COSMOCALC_COMVDIST_TABLE_LENGTH;++i) tmpDouble[i] = aexpn_table[sindex[i]]; for(i=0;i<COSMOCALC_COMVDIST_TABLE_LENGTH;++i) aexpn_table[i] = tmpDouble[i]; if(cosmocalc_comvdist2aexpn_spline != NULL) gsl_spline_free(cosmocalc_comvdist2aexpn_spline); cosmocalc_comvdist2aexpn_spline = gsl_spline_alloc(GSL_SPLINE_TYPE,(size_t) (COSMOCALC_COMVDIST_TABLE_LENGTH)); gsl_spline_init(cosmocalc_comvdist2aexpn_spline,comvdist_table,aexpn_table,(size_t) (COSMOCALC_COMVDIST_TABLE_LENGTH)); if(cosmocalc_comvdist2aexpn_acc != NULL) gsl_interp_accel_reset(cosmocalc_comvdist2aexpn_acc); else cosmocalc_comvdist2aexpn_acc = gsl_interp_accel_alloc(); } } double acomvdist(double dist) { static int initFlag = 1; static int currCosmoNum; if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum) { initFlag = 0; currCosmoNum = cosmoData.cosmoNum; init_cosmocalc_comvdist_table(); } return gsl_spline_eval(cosmocalc_comvdist2aexpn_spline,dist,cosmocalc_comvdist2aexpn_acc); } double comvdist(double a) { static int initFlag = 1; static int currCosmoNum; if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum) { initFlag = 0; currCosmoNum = cosmoData.cosmoNum; init_cosmocalc_comvdist_table(); } return gsl_spline_eval(cosmocalc_aexpn2comvdist_spline,a,cosmocalc_aexpn2comvdist_acc); } //NOTE: you must call comvdist *FIRST* to init DH_sqrtok! double angdist(double a) { double cd; cd = comvdist(a); if(cosmoData.OmegaK > 0.0) return DH_sqrtok*sinh(cd/DH_sqrtok)*a; else if(cosmoData.OmegaK < 0) return DH_sqrtok*sin(cd/DH_sqrtok)*a; else return cd*a; } double lumdist(double a) { double cd; cd = comvdist(a); if(cosmoData.OmegaK > 0.0) return DH_sqrtok*sinh(cd/DH_sqrtok)/a; else if(cosmoData.OmegaK < 0) return DH_sqrtok*sin(cd/DH_sqrtok)/a; else return cd/a; } double angdistdiff(double amin, double amax) { double cdmin,cdmax; assert(amin <= amax); cdmin = comvdist(amin); cdmax = comvdist(amax); if(cosmoData.OmegaK > 0.0) return DH_sqrtok*sinh((cdmin-cdmax)/DH_sqrtok)*amin; else if(cosmoData.OmegaK < 0) return DH_sqrtok*sin((cdmin-cdmax)/DH_sqrtok)*amin; else return (cdmin-cdmax)*amin; }
{ "alphanum_fraction": 0.7404211253, "avg_line_length": 28.97, "ext": "c", "hexsha": "d53a6e990c0d09002a6a3e310725fbf375905c72", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2017-08-11T17:31:51.000Z", "max_forks_repo_forks_event_min_datetime": "2017-07-14T12:17:31.000Z", "max_forks_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "beckermr/cosmocalc", "max_forks_repo_path": "src/distances.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_issues_repo_issues_event_max_datetime": "2016-04-05T19:36:21.000Z", "max_issues_repo_issues_event_min_datetime": "2016-04-05T19:10:45.000Z", "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "beckermr/cosmocalc", "max_issues_repo_path": "src/distances.c", "max_line_length": 125, "max_stars_count": null, "max_stars_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "beckermr/cosmocalc", "max_stars_repo_path": "src/distances.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1921, "size": 5794 }
#include <math.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_complex.h> #define max(A, B) ((A) > (B) ? (A) : (B)) #define min(A, B) ((A) < (B) ? (A) : (B)) double R0(double flock_size, double housing_period, double prob_dam_to_lamb, int maxage, double *params) { int n_age_classes = (maxage+1)*12; int c, a, i, y, t; int infectious_period, years_infectious, period_infectious_to_lambs; int latent_period = lrint(params[5]); double beta_field = params[0]; double beta_housed = params[1]; double p_mort, p_cull, sum, lambs_per_dam; double removal_rate[n_age_classes], infection_rate; double cohort_size_age_0; double cohort_size[maxage+1][n_age_classes]; double infecteds[maxage+1][n_age_classes]; double R0[n_age_classes][n_age_classes]; // age-specific mortality and cull probabilities from Andrew's data double prob_mortality[] = { 0.01, 0.012, 0.027, 0.041, 0.019, 0.021, 0.034, }; double prob_culled[] = { 0, 0.046, 0.065, 0.093, 0.134, 0.196, 0.295, }; // create vector of removal rates of a cohort from ages 0 to n_age_classes for (a = 0; a < n_age_classes; a++) { p_mort = prob_mortality[a/12]; p_cull = prob_culled[a/12]; removal_rate[a] = -(log(1.-p_mort)+log(1.-p_cull))/12.; } // these two ways are equivalent // create vector of infection rates within a year starting in April infection_rate = ((12-housing_period)*beta_field+housing_period*beta_housed)/12.; // for (a = 0; a < 12; a++) // if (a < 12-housing_period) // infection_rate[a] = beta_field; // else // infection_rate[a] = beta_housed; // find intial cohort size in a non-infected flock // take initial cohort size as 1 // find size of cohort as it ages cohort_size[0][0] = 1; for (a = 1; a < n_age_classes; a++) cohort_size[0][a] = cohort_size[0][a-1]*exp(-removal_rate[a]); // sum size of all existent cohorts in April sum = 0; for (y = 0; y <= maxage; y++) sum += cohort_size[0][12*y]; cohort_size_age_0 = flock_size/sum; // for cohorts of y years old at first exposure // assuming that the infectious ewe is starts to be infectious in April - but // this is not necessary, just convenient for (y = 0; y <= maxage; y++) { // cohort size at age 0 cohort_size[y][0] = cohort_size_age_0; // just removal for first y years before exposure for (a = 1; a < 12*y; a++) cohort_size[y][a] = cohort_size[y][a-1]*exp(-removal_rate[a]); // then removal and infection for rest of lifespan for (; a < n_age_classes; a++) cohort_size[y][a] = cohort_size[y][a-1]*exp(-removal_rate[a]-infection_rate); // calculate number of infecteds infecteds[y][0] = 0; for (a = 1; a < n_age_classes; a++) infecteds[y][a] = infection_rate/(removal_rate[a]+infection_rate)*(cohort_size[y][a-1]-cohort_size[y][a]); } // set matrix elements to zero for (a = 0; a < n_age_classes; a++) for (i = 0; i < n_age_classes; i++) R0[a][i] = 0; // for a ewe infected at age a, sum the number of ewes it infects of age i for (a = 0; a < n_age_classes; a++) { infectious_period = max(0, n_age_classes-a-latent_period); for (t = 0; t < infectious_period; t++) { // for all cohorts from past to future for (y = maxage; y >= -maxage; y--) { // get cohort // +ve y are cohorts in the past // -ve y are future cohorts (identical to cohort 0) c = max(0, y); // age of cohort y at time t i = 12*y+t; if (0 <= i && i < n_age_classes) R0[a][i] += infecteds[c][i]; } } } // contribution of vertical transmission to an infectious ewe's lambs lambs_per_dam = cohort_size_age_0/(flock_size-cohort_size_age_0); for (a = 0; a < n_age_classes; a++) { // a ewe infected at age a is infectious for max_age-a-1-latent_period months infectious_period = max(0, n_age_classes-a-latent_period); if (a < 24) // only 2 year olds and older give birth // so ewes infectious before 24 months cannot infect their lambs // until they are 2 years old period_infectious_to_lambs = max(0, n_age_classes-24-latent_period); else period_infectious_to_lambs = infectious_period; years_infectious = period_infectious_to_lambs/12; R0[a][0] += lambs_per_dam*prob_dam_to_lamb*years_infectious; } gsl_matrix *A = gsl_matrix_alloc(n_age_classes, n_age_classes); gsl_vector_complex *v = gsl_vector_complex_alloc(n_age_classes); gsl_eigen_nonsymm_workspace *w = gsl_eigen_nonsymm_alloc(n_age_classes); for (a = 0; a < n_age_classes; a++) for (i = 0; i < n_age_classes; i++) gsl_matrix_set(A, a, i, R0[a][i]); gsl_eigen_nonsymm(A, v, w); double max_eigenvalue = 0, e; for (a = 0; a < n_age_classes; a++) { e = GSL_REAL(gsl_vector_complex_get(v, a)); if (e > max_eigenvalue) max_eigenvalue = e; } gsl_eigen_nonsymm_free(w); gsl_vector_complex_free(v); gsl_matrix_free(A); return max_eigenvalue; }
{ "alphanum_fraction": 0.5926724138, "avg_line_length": 35.9225806452, "ext": "c", "hexsha": "c84bcfae05a9361835b6d635f629eb705f559f92", "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": "00771289509727b5b25e3776a0964555f227442d", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "nicksavill/maedi-visna-epidemiology", "max_forks_repo_path": "Peterson/R0.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "00771289509727b5b25e3776a0964555f227442d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "nicksavill/maedi-visna-epidemiology", "max_issues_repo_path": "Peterson/R0.c", "max_line_length": 118, "max_stars_count": null, "max_stars_repo_head_hexsha": "00771289509727b5b25e3776a0964555f227442d", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "nicksavill/maedi-visna-epidemiology", "max_stars_repo_path": "Peterson/R0.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1635, "size": 5568 }
#ifndef _FastFiz_h #define _FastFiz_h #ifdef SWIG %include exception.i %include "std_string.i" %{ #include "FastFiz.h" %} #endif /* SWIG */ #include <gsl/gsl_rng.h> #include <iosfwd> #include <list> #include <sstream> #include <string> #include <vector> // TODO: add a setprecision for double print out /** * The namespace in which all of the physics and rules components for FastFiz * reside. */ namespace Pool { class BadShotException; struct ShotParams; struct Point; struct Vector; class Ball; class TableState; class Table; class Event; class Shot; class Utils; #ifndef SWIG /** * The exception thrown when a Shot cannot be completed. * It can be thrown when TableState::executeShot() or * TableState::getFirstBallHit() is called. * The Type cannot be changed after construction. */ class BadShotException : public std::exception { public: enum Type { OK, /**< The Shot was okay. */ MISSED_BALL, /**< The Shot missed the CUE ball. */ INVALID_CUE_PARAMS, /**< The ShotParams for the Shot in the current TableState were out of range or not physically possible. */ POOLFIZ_ERROR, /**< FastFiz encountered some sort of error. */ UNKNOWN_ERROR /**< An unknown error. */ }; /** * Constructs a BadShotException initialized with the given Type. * There is no default constructor. */ BadShotException(Type type) : _type(type) {} /** * Returns the Type of the BadShotException. */ Type getType() const { return _type; } /** * Returns the Type of the BadShotException as a string. */ std::string getTypeString() const; /** * Returns a const char* pointing to a c string about what type of Exception * this is. */ virtual const char *what() const throw() { return "Bad Shot Exception"; } private: const Type _type; }; #endif /* SWIG */ /** * A struct of the parameters for a CUE_STRIKE. It is passed to * TableState::executeShot() and can be retrieved from CueStrikeEvent. * @see operator<<(ostream &out, const ShotParams &rhs) Writes human-readable * output for ShotParams objects to the output stream. */ struct ShotParams { double a; /**< The x-coordinate of the cue stick (right/left english) on the CUE ball in mm. */ double b; /**< The y-coordinate of the cue stick (top/bottom english) on the CUE ball in mm. */ double theta; /**< The elevation of the cue stick in degrees. */ double phi; /**< The azumith angle (heading) of the cue stick in degrees. */ double v; /**< The velocity of the cue stick before impact in m/s (max is 4.5 m/s). */ /** * Constructs a ShotParams object with all the fields initialized to 0.0. */ ShotParams() : a(0.0), b(0.0), theta(0.0), phi(0.0), v(0.0) {} /** * Constructs a ShotParams object with all the fields initialized to the given * values. * @param _a The x-coordinate of the cue stick (right/left english) on the * CUE ball in mm. * @param _b The y-coordinate of the cue stick (top/bottom english) on the * CUE ball in mm. * @param _theta The elevation of the cue stick in degrees. * @param _phi The azumith angle (heading) of the cue stick in degrees. * @param _v The velocity of the cue stick before impact in m/s (max is * 4.5 m/s). */ ShotParams(double _a, double _b, double _theta, double _phi, double _v) : a(_a), b(_b), theta(_theta), phi(_phi), v(_v) {} /** * Copy constructor. */ ShotParams(const ShotParams &rhs) : a(rhs.a), b(rhs.b), theta(rhs.theta), phi(rhs.phi), v(rhs.v) {} }; #ifndef SWIG /** * Writes human-readable output for the ShotParams object to the output stream. */ std::ostream &operator<<(std::ostream &out, const ShotParams &rhs); #endif /* SWIG */ /** * A two-dimensional Point class. It has methods for a few simple point * operations. * @see operator<<(ostream &out, const Point &rhs) Writes human-readable output * for Point objects to the output stream. */ struct Point { double x; /**< The x-coordinate of the Point in meters. */ double y; /**< The y-coordinate of the Point in meters. */ /** * Constructs a Point object with x and y initialized to 0.0. */ Point() : x(0.0), y(0.0) {} /** * Constructs a Point object with x and y initialized to the given values. */ Point(double xx, double yy) : x(xx), y(yy) {} /** * Copy constructor. */ Point(const Point &rhs) : x(rhs.x), y(rhs.y) {} #ifndef SWIG /** * Calculates the rotation of a Point object about the origin. The angle of * rotation is counterclockwise. * @param cos_phi The cos of the angle to be rotated by. * @param sin_phi The sin of the anlge to be rotated by. * @return A new Point object that is a copy of this Point object rotated * about the origin by the angle * represented by the cos and sin values. */ Point rotate(double cos_phi, double sin_phi) const; /** * Creates a Vector object representation of this Point object. * @return A new Vector object that is a copy of this Point object with the z * field initialized to 0.0. */ Vector to_v() const; /** * Calculates the sum of two Points. * @param p2 The other Point object to be added. * @return A new Point object that has the respective x and y components of * the other Point object * added to this Point object's components. */ Point operator+(const Point &p2) const; /** * Returns a new Point object that has the respective x and y components of * the other Point object * subtracted from this Point object's components. */ Point operator-(const Point &p2) const; /** * Writes a machine-readable string representation of this Point object (a * sequence of space-separated * doubles followed by a trailing space) to the stream provided. * It can later be interpreted by fromStream() of fromString(). */ void toStream(std::ostream &out) const; /** * Reads a machine-readable string representation of a Point (a sequence of * space-separated doubles) * written by toStream() or toString() from the stream provided and assigns * the values to this Point object. */ void fromStream(std::istream &in); #endif /* ! SWIG */ /** * Returns a string object that is a machine-readable string representation of * this Point object * (a sequence of space-separated doubles followed by a trailing space). * It can later be interpreted by fromString() or fromStream(). */ std::string toString() const; /** * Takes a machine-readable string representation of a Point (a sequence of * space-separated doubles) * created by toString() or toStream() and assigns the values to this Point * object. */ void fromString(const std::string &s); }; #ifndef SWIG /** * Writes human-readable output for the Point object to the output stream. */ std::ostream &operator<<(std::ostream &out, const Point &rhs); #endif /* !SWIG */ /** * A three-dimensional Vector class. It has methods for various vector * operations. * @see operator<<(ostream &out, const Vector &rhs) Writes human-readable output * for Vector objects to the output stream. */ struct Vector { double x; /**< The x-coordinate of the Vector in meters. */ double y; /**< The y-coordinate of the Vector in meters. */ double z; /**< The z-coordinate of the Vector in meters. */ /** * Constructs a Vector object with x, y and z initialized to 0.0. */ Vector() : x(0.0), y(0.0), z(0.0) {} /** * Constructs a Point object with x, y and z initialized to the given values. */ Vector(double xx, double yy, double zz) : x(xx), y(yy), z(zz) {} /** * Copy constructor. */ Vector(const Vector &rhs) : x(rhs.x), y(rhs.y), z(rhs.z) {} #ifndef SWIG /** * Returns a new Vector object that has the respective x, y, and z components * of this Vector object * multiplied with the coefficient provided. */ Vector operator*(double d) const; /** * Multiplies the x,y,z coordinates of the vector by the coefficient provided. */ Vector &operator*=(double d); /** * Returns a new Vector object that has the respective x, y, and z components * of the other Vector object * subtracted from this Vector object's components. */ Vector operator-(const Vector &fizV) const; /** * Returns a new Vector object that has the respective x, y, and z components * of the other Vector object * added to this Vector object's components. */ Vector operator+(const Vector &fizV) const; /** * Returns a new Vector object that is a copy of this Vector object rotated * about the origin. * The parameter is in radians. The angle is counterclockwise. */ Vector rotateRad(double rad) const; // takes radians /** * Returns a new Vector object that is a copy of this Vector object rotated * about the origin. * The parameter is in degrees. The angle is counterclockwise. */ Vector rotateDeg(double phi) const; // takes degrees /** * Returns a new Vector object that is a copy of this Vector object rotated * about the origin. * The parameters are the cos and sin of the angle to be rotated by. The * angle is counterclockwise. */ Vector rotate(double cos_phi, double sin_phi) const; /** * Returns dot-product of two vectors. */ double dot(const Vector &v2) const; /** * Returns cross-product of two vectors. */ Vector cross(const Vector &v2) const; /** * Returns the length (magnitude) of a vector. */ double mag() const; /** * Returns the vector divided by its magnitude. */ Vector norm() const; /** * Returns a point with same x,y as the vector. */ Point to_p() const; void toStream(std::ostream &out) const; void fromStream(std::istream &in); #endif /* ! SWIG */ std::string toString() const; void fromString(const std::string &s); }; #ifndef SWIG std::ostream &operator<<(std::ostream &out, const Vector &rhs); // doesn't need to be friend #endif /* ! SWIG */ #ifndef SWIG /** General utility functions */ class Utils { public: static constexpr double EPSILON = 1.0E-11; /**< double comparison threshold */ static constexpr double VELOCITY_EPSILON = 1E-10; /**< threshold velocity for balls to be considered stationary. */ // Angle ranges can START_ZERO [0,2pi) or START_NEG_HALF_CIRCLE [-pi,pi) // This can apply to degrees or radians enum ANGLE_RANGE { START_ZERO, START_NEG_HALF_CIRCLE }; enum ANGLE_UNIT { DEGREES, RADIANS }; /** direction in the plane from p1 to p2 */ static double angle(Point p1, Point p2, ANGLE_RANGE range, ANGLE_UNIT unit); /** converts radians to degrees */ static double toDegrees(double angleRad); /** converts an angle in radians to be on the specified range, either [0,2*pi) * or [-pi,pi) */ static double normalizeRadianAngleRange(double angle, ANGLE_RANGE range); /** A random number generator instance */ static gsl_rng *rng(); /** Equality test for doubles. */ static bool fequal(double a, double b); /** Less than test for doubles. */ static bool fless(double a, double b); /** Greater than test for doubles. */ static bool fgreater(double a, double b); /** Greater than or equal test for doubles. */ static bool fgreaterequal(double a, double b); /** Less than or equal test for doubles. */ static bool flessequal(double a, double b); /** Check if velocity absolute value should be considered zero. */ static bool vzero(double a); private: static gsl_rng *_rng; }; #endif /* ! SWIG */ /** This class represents the state and position of a single pool ball. * It is mostly used internally for execution of the physics, and as part of a * TableState object. */ class Ball { public: #ifndef SWIG static constexpr double MU_BALL_BALL = 0.01; /**< coefficient of ball-ball friction */ static constexpr double MU_CUETIP_BALL = 0.7; /**< coefficient of cue tip-ball friction */ static constexpr double BALL_COEFF_REST_POS = 2.0; /**< coefficient of restitution for balls */ static constexpr double BALL_COEFF_REST_NEG = 0.0; /**< coefficient of restitution for balls */ static constexpr double BALL_MASS = 163.01; /**< 5.57 oz. ball mass [g] */ static constexpr double BALL_RADIUS = 0.028575; /**< 2.25" ball radius [m] */ #endif /* SWIG */ /** The present physical state of the ball. */ enum State { NOTINPLAY, /**< not on the table */ STATIONARY, /**< in play but not moving */ SPINNING, /**< not moving translationally, but spinning in place about the vertical axis */ SLIDING, /**< sliding across the surface of the table, not necessarily in a straight trajectory */ ROLLING, /**< rolling across the surface of the table, necessarily in a straight trajectory */ POCKETED_SW, /**< pocketed in the SW pocket */ POCKETED_W, /**< pocketed in the W pocket */ POCKETED_NW, /**< pocketed in the NW pocket */ POCKETED_NE, /**< pocketed in the NE pocket */ POCKETED_E, /**< pocketed in the E pocket */ POCKETED_SE, /**< pocketed in the SE pocket */ SLIDING_SPINNING, /**< Transition between SLIDING and SPINNING */ ROLLING_SPINNING, /**< Transition between ROLLING and SPINNING */ UNKNOWN_STATE /**< in an unknown state */ }; /** The type (number) of the ball. */ enum Type { CUE, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, ELEVEN, TWELVE, THIRTEEN, FOURTEEN, FIFTEEN, UNKNOWN_ID }; /** Create a new ball */ Ball() : radius(BALL_RADIUS), r(), state(UNKNOWN_STATE), type(UNKNOWN_ID), v(), w() {} /** Create a new ball with specified number */ Ball(Type _type) : radius(BALL_RADIUS), r(), state(UNKNOWN_STATE), type(_type), v(), w() {} #ifndef SWIG /** Create a new ball with specified number and state */ Ball(Type _type, State _state) : radius(BALL_RADIUS), r(), state(_state), type(_type), v(), w() {} /** Create a new ball with specified number, state, and position */ Ball(Type _type, State _state, Point _r) : radius(BALL_RADIUS), r(_r), state(_state), type(_type), v(), w() {} /** Create a new ball with specified number, state, and position */ Ball(Type _type, State _state, double x, double y) : radius(BALL_RADIUS), r(x, y), state(_state), type(_type), v(), w() {} #endif /* ! SWIG */ /** Copy constructor */ Ball(const Ball &rhs) : radius(rhs.radius), r(rhs.r), state(rhs.state), type(rhs.type), v(rhs.v), w(rhs.w) {} #ifndef SWIG /** Assignment operator */ const Ball &operator=(const Ball &rhs); #endif /* ! SWIG */ /** Returns the radius of the ball in meters. */ double getRadius() const { return radius; } /** Returns the ID (number) of the ball */ Type getID() const { return type; } /** Returns the name of the ball (CUE, ONE, etc.) as a string */ std::string getIDString() const; /** Returns the physical state of the ball */ State getState() const { return state; } /** Returns the physical state of the ball as a string */ std::string getStateString() const; /** Returns the x,y position of the ball */ const Point &getPos() const { return r; } /** Returns the x,y,z velocity of the ball */ const Vector &getVelocity() const { return v; } /** Returns the x,y,z spin of the ball */ const Vector &getSpin() const { return w; } /** Set the number of the ball */ void setID(Type t) { type = t; } /** Set the position of the ball */ void setPos(Point pos) { r = pos; } /** Set the velocity of the ball */ void setVelocity(Vector vel) { v = vel; } /** Set the spin of the ball */ void setSpin(Vector spin) { w = spin; } /** Set the physical state of the ball */ void setState(State s) { state = s; } /** Returns true iff the ball is on the table. */ bool isInPlay() const { return (state == STATIONARY || state == SPINNING || state == SLIDING || state == ROLLING); } /** Returns true iff the ball is in a pocket. */ bool isPocketed() const { return (state == POCKETED_SW || state == POCKETED_W || state == POCKETED_NW || state == POCKETED_NE || state == POCKETED_E || state == POCKETED_SE); } #ifndef SWIG /** Returns true if the ball occupies the same space as the other ball */ bool overlaps(const Ball &other, double epsilon = Utils::EPSILON) const; void moveAway(Ball &other, double epsilon); /** Returns the distance between the centers of this ball and the other ball. * Note that a positive distance does not indicate no overlap. * No overlap is ensured if the distance is greater than the sum of the * radiuses of the balls. */ double dist(const Ball &other) const; /** Add small gaussian noise to ball's position based on dither parameter * passed. * This method is used for racking and spotting noise, and has nothing to do * with shot execution noise. */ void addNoise(double dither); #endif /* ! SWIG */ /** Update balls physical state based on position, velocity, and spin. * Used internally for physics calculations. */ void updateState(bool VERBOSE = false); #ifndef SWIG /** Print a machine-readable representation of the ball's type, radius and * position. * Only writes location information, not velocity and spin. */ void toStream(std::ostream &out) const; /** Read a machine-readable representation of the ball's type, radius and * position. * Should be used on data written by toStream()/toString(). */ void fromStream(std::istream &in); #endif /* ! SWIG */ /** Returns a string including a machine-readable representation of the ball's * type, radius and position. * Only outputs location information, not velocity and spin. */ std::string toString() const; /** Read a machine-readable representation of the ball's type, radius and * position from string. * Should be used on data created by toString()/toStream(). */ void fromString(const std::string &s); #ifndef SWIG private: double radius; Point r; State state; Type type; Vector v; Vector w; #endif /* ! SWIG */ }; #ifndef SWIG std::ostream &operator<<(std::ostream &out, const Ball &rhs); // doesn't need to be a friend #endif /* !SWIG */ /** Class representing physical properties of a pool table. This does not * include the position of the balls. * In general, this object doesn't need to be instansiated more than once. * This class also provides some static utility functions and constants related * to the pool table. */ class Table { public: /* Physics constants */ static constexpr double g = 9.81; /**< Gravitational constant.*/ static constexpr double MU_SLIDING = 0.2; /**< coefficient of sliding friction */ static constexpr double MU_ROLLING = 0.015; /**< coefficient of rolling friction */ static constexpr double MU_SPINNING = 0.044; /**< coefficient of spinning friction */ /* Default table parameters */ static constexpr double TABLE_LENGTH = 2.236; /**< table length [m] */ static constexpr double TABLE_WIDTH = 1.116; /**< table width [m] */ static constexpr double CORNER_POCKET_WIDTH = 0.11; /**< corner pocket width [m] */ static constexpr double SIDE_POCKET_WIDTH = 0.12; /**< side pocket width [m] */ static constexpr double RAIL_HEIGHT = 0.040005; /**< rail height [m] */ static constexpr double CUE_LENGTH = 1.45; /**< cue length [m] */ static constexpr double RAIL_VEL_DAMPING_X = 0.6; /**< damping factor for velocity component parallel to rail */ static constexpr double RAIL_VEL_DAMPING_Y = 0.9; /**< damping factor for velocity component perpendicular to rail */ static constexpr double RAIL_SPIN_DAMPING = 0.1; /**< damping factor for angular velocity component */ static constexpr double RAIL_VEL_ANGLE_ADJ = 0.0; /**< angle adjustment factor for velocity vector */ static constexpr double RAIL_ZSPIN_ANGLE_ADJ = 0.0; /**< angle adjustment factor for vertical component of angular velocity vector */ // used in CueStrikeEvent::doHandle static constexpr double CUE_MASS = 600.0; static constexpr double I = 0.4 * 160.0 * 0.028575 * 0.028575 * 0.995473; /**< moment of inertia; to match poolfiz */ /** A rail or a pocket. */ enum BoundaryId { SW_POCKET, SW_RAIL, W_POCKET, NW_RAIL, NW_POCKET, N_RAIL, NE_POCKET, NE_RAIL, E_POCKET, SE_RAIL, SE_POCKET, S_RAIL, UNKNOWN_BOUNDARY }; enum Pocket { SW, W, NW, NE, E, SE, UNKNOWN_POCKET }; /** Constructs a table with the default parameters */ Table() : _muS(MU_SLIDING), _muR(MU_ROLLING), _muSp(MU_SPINNING), _railHeight(RAIL_HEIGHT), _cueLength(CUE_LENGTH), _railVelDampingX(RAIL_VEL_DAMPING_X), _railVelDampingY(RAIL_VEL_DAMPING_Y), _railSpinDamping(RAIL_SPIN_DAMPING), _railZSpinAngleAdj(RAIL_ZSPIN_ANGLE_ADJ), _railVelAngleAdj(RAIL_VEL_ANGLE_ADJ) { calculateTableDimensions(TABLE_LENGTH, TABLE_WIDTH, CORNER_POCKET_WIDTH, SIDE_POCKET_WIDTH); } /** Constructs a table with the given parameters and automatically sets the *pockets. * @param length the length of the table in metres * @param width the width of the table in metres * @param cornerPocketWidth the width of corner pockets (horn to horn) in *metres * @param sidePocketWidth the width of the side pockets (horn to horn) in *metres * @param muS the coefficient of sliding friction (dimensionless) * @param muR the coefficient of rolling friction (dimensionless) * @param muSp the coefficient of spinning friction (dimensionless) * @param railHeight the height of the top of the rail above the table in *metres * @param cueLength the length of the cue in metres * @param railVelDampingX velocity damping factor of the banks (X) * @param railVelDampingY velocity damping factor of the banks (Y) * @param railSpinDamping spin damping factor of the banks * @param railZSpinAngleAdj z-spin angle of deflection factor of the banks * @param railVelAngleAdj velocity deflection factor of the banks */ Table(double length, double width, double cornerPocketWidth, double sidePocketWidth, double muS = MU_SLIDING, double muR = MU_ROLLING, double muSp = MU_SPINNING, double railHeight = RAIL_HEIGHT, double cueLength = CUE_LENGTH, double railVelDampingX = RAIL_VEL_DAMPING_X, double railVelDampingY = RAIL_VEL_DAMPING_Y, double railSpinDamping = RAIL_SPIN_DAMPING, double railZSpinAngleAdj = RAIL_ZSPIN_ANGLE_ADJ, double railVelAngleAdj = RAIL_VEL_ANGLE_ADJ); /** Copy constructor. */ Table(const Table &rhs); #ifndef SWIG /** Assignment operator */ const Table &operator=(const Table &rhs); #endif /* SWIG */ /* Convenience methods for the table parameters */ /** Returns the length of the table (in metres). */ double getLength() const { return _length; } /** Returns the width of the table (in metres). */ double getWidth() const { return _width; } /** Returns the y-coordinate of the headstring of the table (in metres) */ double getHeadString() const { return _headString; } /** Returns the x-y coordinate of the footspot of the table (in metres) */ const Point &getFootSpot() const { return _footSpot; } /** Sets the length of the cue stick. * @param length the length of the cue in metres. */ void setCueLength(double length) { _cueLength = length; } /** Returns the length of the cue stick. */ double getCueLength() const { return _cueLength; } /** Sets the height of the rails around the table. * @param height the height of the rails in metres. */ void setRailHeight(double height) { _railHeight = height; } /** Returns the height of the rails around the table. */ double getRailHeight() const { return _railHeight; } /** Sets the coefficient of sliding friction. * @param mu the coefficient of sliding friction (between 0 and 1). */ void setMuSliding(double mu) { _muS = mu; } /** Returns the coefficient of sliding friction. */ double getMuSliding() const { return _muS; } /** Sets the coefficient of rolling friction. * @param mu the coefficient of rolling friction (between 0 and 1). */ void setMuRolling(double mu) { _muR = mu; } /** Returns the coefficient of rolling friction. */ double getMuRolling() const { return _muR; } /** Sets the coefficient of spinning friction. * @param mu the coefficient of spinning friction (between 0 and 1). */ void setMuSpinning(double mu) { _muSp = mu; } /** Returns the coefficient of spinning friction. */ double getMuSpinning() const { return _muSp; } /** Returns the aiming point of the given pocket (in metres). */ const Point &getPocketCenter(Pocket pocket) const; /** Returns the right corner coordinates of the given pocket (in metres), *looking * at the pocket from the center of the table. */ const Point &getPocketRight(Pocket pocket) const; /** Returns the left corner coordinates of the given pocket (in metres), *looking * at the pocket from the center of the table. */ const Point &getPocketLeft(Pocket pocket) const; /** Contains a single default table object whose reference is returned when * called */ static const Table &defaultTable() { static const Table t = Table(); return t; } /** Returns the pocketed ball state corresponding to the given pocket (by * Pocket) */ static Ball::State stateFromPocket(Pocket pocket); /** Returns the same pocket in Pocket form rather than BoundaryId form */ static Pocket pocketFromBndId(BoundaryId bnd); /** Returns the same pocket in BoundaryId form rather than Pocket form */ static BoundaryId bndIdFromPocket(Pocket pocket); /** returns a string of the boundary name */ static std::string boundaryName(BoundaryId boundary); /** returns a string of the pocket name */ static std::string pocketName(Pocket pocket); #ifndef SWIG private: double _muS; double _muR; double _muSp; double _railHeight; double _cueLength; double _railVelDampingX; double _railVelDampingY; double _railSpinDamping; double _railZSpinAngleAdj; double _railVelAngleAdj; double _length; double _width; double _headString; Point _footSpot; Point _SWpocketLeft; Point _SWpocketRight; Point _SWpocketCenter; Point _WpocketLeft; Point _WpocketRight; Point _WpocketCenter; Point _NWpocketLeft; Point _NWpocketRight; Point _NWpocketCenter; Point _NEpocketLeft; Point _NEpocketRight; Point _NEpocketCenter; Point _EpocketLeft; Point _EpocketRight; Point _EpocketCenter; Point _SEpocketLeft; Point _SEpocketRight; Point _SEpocketCenter; void calculateTableDimensions(double length, double width, double cornerPocketWidth, double sidePocketWidth); #endif /* ! SWIG */ }; /** Base class of the Event heirarchy. Indicates a notable event in the * execution of a shot. * * Subclasses of this class indicate specific events. */ class Event { #ifndef SWIG friend std::ostream &operator<<(std::ostream &out, const Event &rhs); #endif /* ! SWIG */ public: /** Indicates the type of event.*/ enum Type { NO_EVENT, /**< Nothing happened (only used internally) */ STATE_CHANGE, /**< A ball transitioned to a different motion state */ BALL_COLLISION, /**< two balls collided */ RAIL_COLLISION, /**< a ball collided with a rail */ POCKETED, /**< a ball was pocketed */ CUE_STRIKE, /**< the cue ball was struck by the cue stick successfully */ MISCUE, /**< the cue ball was struck by the cue stick unsuccessfully */ UNKNOWN_EVENT /**< an unknown event */ }; /** Create a new base event. * \param time Simulation time event took place. * \param b id of the ball affected by the event. */ Event(double time, Ball::Type b) : _time(time), _ball1(b), _ball1Data(NULL) {} /** Returns the event's simulation time index */ double getTime() const { return _time; } /** Returns the id of first (possibly only) ball involved in the event. */ Ball::Type getBall1() const { return _ball1; } /** Returns the physical information (location, velocity,spin) of the first * (possibly only) ball involved in the event. * May cause a null pointer exception if the information is not available (if * event was not yet handled). */ Ball &getBall1Data() { return *_ball1Data; } /** Sorts Events by time */ bool operator<(const Event &other) const; /** Event comparison function, calls operator< */ static bool eventCmp(const Event *event1, const Event *event2); /** Returns a human-readble string representation of the event. */ std::string toString() const; /** Returns the type of the event */ virtual Type getType() const { return UNKNOWN_EVENT; } /** Returns the type of the event as a string */ virtual std::string getTypeString() const { return "Unknown Event"; } /** Returns the id of the second ball involved in the event, if applicable */ virtual Ball::Type getBall2() const { return Ball::UNKNOWN_ID; } /** Returns the physical information (location, velocity,spin) of the second * ball involved in the event. * If no second ball is involved, will return the first ball information. * May cause a null pointer exception if the information is not available (if * event was not yet handled). */ virtual Ball &getBall2Data() { return *_ball1Data; } /** Returns true if this event and the other event affect a shared ball. */ virtual bool relatedTo(const Event &other) const; /** Returns true if this event affects specified ball. */ virtual bool involvesBall(Ball::Type b) const; /** Destructor. */ virtual ~Event() { delete _ball1Data; } /** Used within physics code to apply event to a table state, modifying ball * states, positions, and properties * Also updates ball information within event. */ void handle(TableState &ts, bool VERBOSE = false) { doHandle(ts, VERBOSE); copyBalls(ts); } protected: double _time; Ball::Type _ball1; Ball *_ball1Data; virtual void doHandle(TableState &ts, bool VERBOSE) const = 0; virtual void copyBalls(TableState &ts); #ifndef SWIG virtual std::ostream &dump(std::ostream &out) const; private: // copy and assignment Event(const Event &rhs); //: _time(rhs._time), _ball1(rhs._ball1) {} const Event &operator=(const Event &rhs); //{if (this != &rhs) //{_time=rhs._time; //_ball1=rhs._ball1;}; return //*this;} #endif /* ! SWIG */ }; /** An event invloving a physical transition of state, e.g between SLIDING and * ROLLING. * In general these events are important for graphical simulation of the shot, * and for trajectory analysis. */ class StateChangeEvent : public Event { public: StateChangeEvent(double time, Ball::Type b) : Event(time, b) {} virtual Type getType() const { return STATE_CHANGE; } virtual std::string getTypeString() const { return "State Change"; } protected: virtual void doHandle(TableState &ts, bool VERBOSE) const; #ifndef SWIG private: // copy and assignment StateChangeEvent(const StateChangeEvent &rhs); // : Event(rhs) {} StateChangeEvent & operator=(const StateChangeEvent & rhs); //{if (this != &rhs) Event::operator=(rhs); return *this;} #endif /* ! SWIG */ }; /** An event involving two balls colliding. * This is the only event where Ball2 is defined. */ class BallCollisionEvent : public Event { public: BallCollisionEvent(double time, Ball::Type b1, Ball::Type b2) : Event(time, b1), _ball2(b2), _ball2Data(NULL) {} virtual Type getType() const { return BALL_COLLISION; } virtual std::string getTypeString() const { return "Ball Collision"; } virtual bool relatedTo(const Event &other) const; virtual bool involvesBall(Ball::Type b) const; virtual ~BallCollisionEvent() { delete _ball2Data; } virtual Ball::Type getBall2() const { return _ball2; } virtual Ball &getBall2Data() { return *_ball2Data; } protected: Ball::Type _ball2; Ball *_ball2Data; virtual void copyBalls(TableState &ts); virtual void doHandle(TableState &ts, bool VERBOSE) const; #ifndef SWIG virtual std::ostream &dump(std::ostream &out) const; private: // copy and assignment BallCollisionEvent( const BallCollisionEvent &rhs); //: Event(rhs), _ball2(rhs._ball2) {} BallCollisionEvent &operator=(const BallCollisionEvent &rhs); #endif /* ! SWIG */ }; /** An event involving a ball colliding with a rail. */ class RailCollisionEvent : public Event { public: RailCollisionEvent(double time, Ball::Type b, Table::BoundaryId rail) : Event(time, b), _rail(rail) {} virtual Type getType() const { return RAIL_COLLISION; } virtual std::string getTypeString() const { return "Rail Collision"; } /** Returns the ID of the rail collided with. */ Table::BoundaryId getRail() const { return _rail; } protected: Table::BoundaryId _rail; virtual void doHandle(TableState &ts, bool VERBOSE) const; #ifndef SWIG virtual std::ostream &dump(std::ostream &out) const; private: // copy and assignment RailCollisionEvent( const RailCollisionEvent &rhs); //: Event(rhs), _rail(rhs._rail) {} RailCollisionEvent &operator=(const RailCollisionEvent &rhs); #endif /* ! SWIG */ }; /** An event involving a ball entering a pocket. */ class PocketedEvent : public Event { public: PocketedEvent(double time, Ball::Type b, Table::Pocket pocket) : Event(time, b), _pocket(pocket) {} virtual Type getType() const { return POCKETED; } virtual std::string getTypeString() const { return "Ball Pocketed"; } /** Returns the ID of the pocket. */ Table::Pocket getPocket() const { return _pocket; } protected: Table::Pocket _pocket; virtual void doHandle(TableState &ts, bool VERBOSE) const; #ifndef SWIG virtual std::ostream &dump(std::ostream &out) const; private: // copy and assignment PocketedEvent( const PocketedEvent &rhs); //: Event(rhs), _pocket(rhs._pocket) {} PocketedEvent &operator=(const PocketedEvent &rhs); #endif /* ! SWIG */ }; /** The initial event in any shot -- cue ball struck by the cue stick. */ class CueStrikeEvent : public Event { public: // Default constructor /** Constructor with shot parameters, assumes zero time */ CueStrikeEvent(const ShotParams &params) : Event(0.0, Ball::CUE), _params(params) {} /** Constructor with shot parameters, and time */ CueStrikeEvent(double time, const ShotParams &params) : Event(time, Ball::CUE), _params(params) {} /** Constructor with shot parameters, ball, and time */ CueStrikeEvent(double time, Ball::Type &b, const ShotParams &params) : Event(time, b), _params(params) {} virtual Type getType() const { return CUE_STRIKE; } virtual std::string getTypeString() const { return "Cue Strike"; } /** Return shot parameters */ const ShotParams &getParams() const { return _params; } protected: #ifndef SWIG ShotParams _params; #endif /* SWIG */ virtual void doHandle(TableState &ts, bool VERBOSE) const; #ifndef SWIG virtual std::ostream &dump(std::ostream &out) const; private: // copy and assignment CueStrikeEvent( const CueStrikeEvent &rhs); //: Event(rhs), _params(rhs._params) {} CueStrikeEvent &operator=(const CueStrikeEvent &rhs); #endif /* ! SWIG */ }; StateChangeEvent& eventToStateChangeEvent(Event &event); BallCollisionEvent& eventToBallCollisionEvent(Event &event); RailCollisionEvent& eventToRailCollisionEvent(Event &event); PocketedEvent& eventToPocketedEvent(Event &event); CueStrikeEvent& eventToCueStrikeEvent(Event &event); /** Detailed result of a simulation of a shot. * Public objects of this class can only be created by TableState::executeShot() * Constructing a Shot object starts the physics simulation. * The private methods in this class implement the main part of the physics * simulation. */ class Shot { public: friend class TableState; /** Gets the list of events generated during the shot. * The vector is sorted by time, and all relevant ball information is * available in the events. */ const std::vector<Event *> &getEventList() const { return shotEvents; } /** Returns the amount of time (in seconds) balls will take to settle after * executing the shot. */ double getDuration() const; /** Destroy a shot object. * Deleting the Shot object is caller's responsibility. */ ~Shot(); private: // Uncopiable Shot(const Shot &rhs); Shot &operator=(const Shot &rhs); #ifndef SWIG std::vector<Event *> shotEvents; // Can throw BadShotException from simulateShot Shot(TableState &state, const ShotParams &sp, bool fullSim /* false = get first ball hit only */, bool verbose = false, bool errors = false) : shotEvents() { simulateShot(state, sp, fullSim, verbose, errors); } // Can throw BadShotException void simulateShot(TableState &state, const ShotParams &sp, bool fullSim, bool verbose, bool errors); static bool VERBOSE; static bool CHECK_ERRORS; static void updateTime(TableState &state, double oldTime, double newTime); static void updateBall(const Table &table, Ball &ball, double oldTime, double newTime); static double updateSpinning(double w_z, double t, double mu_sp, double R, bool isSliding); static void removeRelatedEvents(std::list<Event *> &events, Event *lastEvent); static void addRelatedFutureEvents(TableState &state, double curTime, std::list<Event *> &futureEvents, Ball::Type b1, Ball::Type b2); static Event *nextTransitionEvent(const Table &table, Ball &ball, double curTime); static Event *nextCollisionEvent(const Table &table, Ball &ball1, Ball &ball2, double curTime); static void addBoundaryEvents(const Table &table, Ball &ball, double curTime, std::list<Event *> &futureEvents); static double calcEventTime(int numRoots, double root1, double root2, double curTime); static int solveQuartic(double roots[], double a0, double a1, double a2, double a3, double a4); static constexpr double NEAR_FUTURE_EPSILON = 1E-8; static double leastPositiveRealRoot(double roots[], double epsilon = NEAR_FUTURE_EPSILON); /* static void handleEvent(TableState &state, Event *event); static void handleStateChange(Ball &ball); static void handleBallCollision(Ball &ball1, Ball &ball2); static void handleRailCollision(Ball &ball, Table::BoundaryId rail); static void handlePocketed(Ball &ball, Table::Pocket pocket); static void handleCueStrike(Ball &ball, const ShotParams &sp); */ // static void addFutureEvents(TableState &state, double curTime, std::list<Event*> // &futureEvents); // static constexpr double BALL_MASS = 160.0; //From Marlow, in line with BCA // rules // static constexpr double g = GSL_CONST_MKSA_GRAV_ACCEL; // static constexpr double R = 0.028575; //Ball radius //Now taken from // Ball::BALL_RADIUS // static constexpr int NUM_BALLS = 16; //Now taken from // TableState::getNumBalls() #endif /* ! SWIG */ }; #ifndef SWIG /** Print a human-readable representation of the shot to a stream */ std::ostream &operator<<(std::ostream &out, Shot &rhs); // doesn't need to be friend #endif /* ! SWIG */ /** The physical state of balls on a table. * Includes position and velocity information but no rules related information. */ class TableState { public: /* Thresholds */ static constexpr double MAX_VELOCITY = 10; /**< maximum velocity allowed [m/s] */ static constexpr double MIN_THETA = 0.0; /**< minimum theta allowed [degrees] */ static constexpr double MAX_THETA = 70.0; /**< maximum theta allowed [degrees] */ /** This integer is used within the bitmask integer returned by *Table::isPhysicallyPossible() * and Table::isValidBallPlacement() (as well as the fizG versions of those *classes). It * indicates that all shot parameters are valid; the actual integer *returned by these methods * is simply the OR'ed combinations of the all the possibilities from the *list under the heading * 'Variables' in the HTML documentation or listed below in the header *file; you can AND the result * returned by these methods with any of the possibilities from the list *below to test if that * particular possibility is true. */ static constexpr int OK_PRECONDITION = 0; /** This integer is used within the bitmask integer returned by *Table::isPhysicallyPossible() * and Table::isValidBallPlacement() (as well as the fizG versions of those *classes). It * indicates that shot parameter 'a' is invalid or not physically possible; * the actual integer returned by these methods * is simply the OR'ed combinations of the all the possibilities from the *list under the heading * 'Variables' in the HTML documentation or listed below in the header *file; you can AND the result * returned by these methods with any of the possibilities from the list *below to test if that * particular possibility is true. */ static constexpr int BAD_A_VAL = 1; /** This integer is used within the bitmask integer returned by *Table::isPhysicallyPossible() * and Table::isValidBallPlacement() (as well as the fizG versions of those *classes). It * indicates that shot parameter 'b' is invalid or not physically possible; * the actual integer returned by these methods * is simply the OR'ed combinations of the all the possibilities from the *list under the heading * 'Variables' in the HTML documentation or listed below in the header *file; you can AND the result * returned by these methods with any of the possibilities from the list *below to test if that * particular possibility is true. */ static constexpr int BAD_B_VAL = 2; /** This integer is used within the bitmask integer returned by *Table::isPhysicallyPossible() * and Table::isValidBallPlacement() (as well as the fizG versions of those *classes). It * indicates that shot parameter 'theta' is invalid or not physically *possible; * the actual integer returned by these methods * is simply the OR'ed combinations of the all the possibilities from the *list under the heading * 'Variables' in the HTML documentation or listed below in the header *file; you can AND the result * returned by these methods with any of the possibilities from the list *below to test if that * particular possibility is true. */ static constexpr int BAD_THETA_VAL = 4; /** This integer is used within the bitmask integer returned by *Table::isPhysicallyPossible() * and Table::isValidBallPlacement() (as well as the fizG versions of those *classes). It * indicates that shot parameter 'phi' is invalid or not physically *possible; * the actual integer returned by these methods * is simply the OR'ed combinations of the all the possibilities from the *list under the heading * 'Variables' in the HTML documentation or listed below in the header *file; you can AND the result * returned by these methods with any of the possibilities from the list *below to test if that * particular possibility is true. */ static constexpr int BAD_PHI_VAL = 8; /** This integer is used within the bitmask integer returned by *Table::isPhysicallyPossible() * and Table::isValidBallPlacement() (as well as the fizG versions of those *classes). It * indicates that shot parameter 'V' is invalid or not physically possible; * the actual integer returned by these methods * is simply the OR'ed combinations of the all the possibilities from the *list under the heading * 'Variables' in the HTML documentation or listed below in the header *file; you can AND the result * returned by these methods with any of the possibilities from the list *below to test if that * particular possibility is true. */ static constexpr int BAD_V_VAL = 16; /** This integer is used within the bitmask integer returned by *Table::isPhysicallyPossible() * and Table::isValidBallPlacement() (as well as the fizG versions of those *classes). It * indicates that the cue ball placement x-coordinate is out of range; * the actual integer returned by these methods * is simply the OR'ed combinations of the all the possibilities from the *list under the heading * 'Variables' in the HTML documentation or listed below in the header *file; you can AND the result * returned by these methods with any of the possibilities from the list *below to test if that * particular possibility is true. */ static constexpr int BAD_X_VAL = 32; /** This integer is used within the bitmask integer returned by *Table::isPhysicallyPossible() * and Table::isValidBallPlacement() (as well as the fizG versions of those *classes). It * indicates that the cue ball placement y-coordinate is out of range; * the actual integer returned by these methods * is simply the OR'ed combinations of the all the possibilities from the *list under the heading * 'Variables' in the HTML documentation or listed below in the header *file; you can AND the result * returned by these methods with any of the possibilities from the list *below to test if that * particular possibility is true. */ static constexpr int BAD_Y_VAL = 64; /** This integer is used within the bitmask integer returned by *Table::isPhysicallyPossible() * and Table::isValidBallPlacement() (as well as the fizG versions of those *classes). It * indicates that the cue will collide with a ball before striking the cue *ball; * the actual integer returned by these methods * is simply the OR'ed combinations of the all the possibilities from the *list under the heading * 'Variables' in the HTML documentation or listed below in the header *file; you can AND the result * returned by these methods with any of the possibilities from the list *below to test if that * particular possibility is true. */ static constexpr int CUE_STICK_COLLISION = 128; /** This integer is used within the bitmask integer returned by *Table::isPhysicallyPossible() * and Table::isValidBallPlacement() (as well as the fizG versions of those *classes). It * indicates that the ball placement x-y coordinates result in an overlap *with another ball on table; * the actual integer returned by these methods * is simply the OR'ed combinations of the all the possibilities from the *list under the heading * 'Variables' in the HTML documentation or listed below in the header *file; you can AND the result * returned by these methods with any of the possibilities from the list *below to test if that * particular possibility is true. */ static constexpr int BALL_OVERLAP = 256; /** Create an empty table state for given table (or default table if not * specified) */ TableState(const Table &table = Table::defaultTable()) : _table(table), balls() {} /** Copy constructor */ TableState(const TableState &rhs) : _table(rhs._table), balls(rhs.balls) {} #ifndef SWIG /** Assignment operator */ TableState &operator=(const TableState &rhs); #endif /* ! SWIG */ /** Return the number of different balls used in representing this state */ int getNumBalls() const { return balls.size(); } #ifndef SWIG /** Iterator for start of ball vector */ std::vector<Ball>::iterator getBegin() { return balls.begin(); } /** Iterator for end of ball vector */ std::vector<Ball>::iterator getEnd() { return balls.end(); } /** Const Iterator for start of ball vector */ std::vector<Ball>::const_iterator getBegin() const { return balls.begin(); } /** Const Iterator for end of ball vector */ std::vector<Ball>::const_iterator getEnd() const { return balls.end(); } #endif /* ! SWIG */ void fixOverlap(const bool VERBOSE); /** Modify specified ball id with specified ball information, adding if needed */ void setBall(Ball &b); /** Set a ball's state and position, adding if needed */ void setBall(Ball::Type btype, Ball::State state, Point r); /** Set a ball's state and position, adding if needed */ void setBall(Ball::Type btype, Ball::State state, double x, double y); /** Spot a pocketed ball at or near the foot spot, with dithering if needed */ void spotBall(Ball::Type btype, double dither = DITHER); /** Get ball information based on id. If ball does not exist it will be added * with unknown information. * Returned ball may be modified and will affect the table state. */ Ball &getBall(Ball::Type btype); #ifndef SWIG /** Get ball information based on id. If ball does not exist it will be added * with unknown information. */ const Ball &getBall(Ball::Type btype) const; #endif /* SWIG */ /** Return the underlying table object */ const Table &getTable() const { return _table; }; /* Validity checkers */ /** Returns BAD_X_VAL or BAD_Y_VAL if any ball that is in play is off the *table or * BALL_OVERLAP if any ball is overlapping with another ball. * Used to check cue ball placement validity in the case of Ball In Hand, *for example. * @param VERBOSE Print debugging information */ int isValidBallPlacement(bool VERBOSE = false) const; /** Checks physical validity of the given shot parameters and table state. *Used before calling * executeShot() to double-check that an error condition will not result *due to invalid * parameters. * @param shotParams Shot parameters * @param VERBOSE Print debugging information */ int isPhysicallyPossible(const ShotParams &shotParams, bool VERBOSE = false) const; /** Add racking noise to table state. * This has nothing to do with shot execution noise. */ void addNoise(double dither); /** Randomly position all balls on the table. */ void randomize(); #ifdef SWIG %exception { try { $function } catch (Pool::BadShotException &ex) { std::string msg = "Bad Shot: " + ex.getTypeString(); SWIG_exception(SWIG_ValueError, msg.c_str()); } } %newobject executeShot; #endif /* SWIG */ /** Execute given shot on the table state. * The TableState object will be modified to reflect the final state of the * shot. * If you need to retain the initial state, copy the object before calling. * Noise is not added to the shot prior to execution. * @param sp The shot parameters to execute. * @param verbose Print a lot of debugging information to cerr. * @param errors Detect internal errors (slower execution) * @exception BadShotException will be thrown in case of bad parameters or * errors in execution. */ Shot *executeShot(const ShotParams &sp, bool verbose = false, bool errors = false) { return new Shot(*this, sp, true, verbose, errors); } #ifdef SWIG %exception; #endif /* SWIG */ // Returns the first ball that will be hit by the cue ball by the given shot. // If the cue ball doesn't hit another ball, returns CUE. // Can throw BadShotException from creating Shot /** Return the first ball hit by the cue ball while executing shot. * This function will simulate the shot up until the first ball is hit by * the cue ball and then return the ball type, or UNKNOWN_ID if no ball is * hit. */ Ball::Type getFirstBallHit(const ShotParams &sp); #ifndef SWIG /** Writes a machine-readable representation of the table state to a stream. */ void toStream(std::ostream &out) const; /** Reads a machine-readable representation of the table state from a stream. * Should be used on output of toStream() or toString(). */ void fromStream(std::istream &in); #endif /* ! SWIG */ /** Returns a machine-readable representation of the table state as a string*/ std::string toString() const; /** Reads a machine-readable representation of the table state from a string. * Should be used on output of toStream() or toString(). */ void fromString(const std::string &s); #ifndef SWIG private: const Table &_table; std::vector<Ball> balls; static constexpr double DITHER = 0.00005; static constexpr double EPSILON_B = 0.001; /**< small value added to the b shot parameter for threshold calculations [mm] */ static constexpr double EPSILON_THETA = 0.001; /**< small value added to the theta shot parameter for threshold calculations [degrees] */ static constexpr int MAX_BALLS_ON_TABLE = 100; /**< Maximum balls allowed on the table at any time. */ static int numLineSphereIntersections(Vector &p1, Vector &p2, Vector &p3, double rad, double &root1, double &root2); int findOverlap(Ball::Type ball) const; #endif /* ! SWIG */ }; #ifndef SWIG std::ostream &operator<<(std::ostream &out, TableState &rhs); // doesn't need to be friend #endif /* ! SWIG */ /** Return a string identifying the version and build information of the library */ std::string getFastFizVersion(); #ifndef SWIG /** Return a string identifying the version and build information of the * library. * @deprecated Use getFastFizVersion(). */ inline std::string getPoolfizVersion() { return getFastFizVersion(); } #endif /* ! SWIG */ #ifndef SWIG /** Rack table state for Eight-ball. Debugging function. * @deprecated Use the GameState framework to generate a racked state. */ void rack(TableState &ts); /** Dump event list to standard error. Debugging function. */ void printEvents(std::list<Event *> events); /** Print overlapping balls in table state. Debugging function. */ void printOverlap(TableState &ts); #else /* SWIG */ %newobject getTestState; #endif /* SWIG */ /** Return a racked state for testing purposes. Debugging function. */ TableState *getTestState(); #ifdef SWIG %newobject getTestShotParams(); #endif /* SWIG */ /** Return sample shot parameters that work with the test state. */ ShotParams *getTestShotParams(); } // namespace Pool #ifdef SWIG %include "std_vector.i" namespace std { %template(EventVector) std::vector<Pool::Event *>; } #endif /* SWIG */ #endif //_FastFiz_h
{ "alphanum_fraction": 0.6781180792, "avg_line_length": 36.2762900065, "ext": "h", "hexsha": "9ecc1ce1ca276afdf9b763d7ae12b2aa36dde2e7", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-07-17T11:41:41.000Z", "max_forks_repo_forks_event_min_datetime": "2021-07-17T11:41:41.000Z", "max_forks_repo_head_hexsha": "78336678a99608d1c41a5b4d0f03d33916b0b4df", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "FieldMrFive/fastfiz", "max_forks_repo_path": "fastfiz/include/FastFiz.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "78336678a99608d1c41a5b4d0f03d33916b0b4df", "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": "FieldMrFive/fastfiz", "max_issues_repo_path": "fastfiz/include/FastFiz.h", "max_line_length": 90, "max_stars_count": 2, "max_stars_repo_head_hexsha": "78336678a99608d1c41a5b4d0f03d33916b0b4df", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "FieldMrFive/fastfiz", "max_stars_repo_path": "fastfiz/include/FastFiz.h", "max_stars_repo_stars_event_max_datetime": "2021-10-13T07:22:11.000Z", "max_stars_repo_stars_event_min_datetime": "2021-07-20T01:55:36.000Z", "num_tokens": 13622, "size": 55539 }
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* ** ** ** This file forms part of the Underworld geophysics modelling application. ** ** ** ** For full license and copyright information, please refer to the LICENSE.md file ** ** located at the project root, or contact the authors. ** ** ** **~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/ /* Performs y = ( G^T G )^{-1} ( G^T K G ) ( G^T G )^{-1} x This preconditioner is defined as a PC rather than a MatShell as we can define and compute the inverse easily without the need of an additional KSP. Compare this to Q_S = G^T Q_K^-1 G, where Q_S^-1 can only be performed implicitly via an iterative method. */ #if 1 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <petsc.h> #include <petscmat.h> #include <petscvec.h> #include <petscksp.h> #include <petscpc.h> #include "common-driver-utils.h" #include <petscversion.h> #if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >=3) ) #if (PETSC_VERSION_MINOR >=6) #include "petsc/private/pcimpl.h" #include "petsc/private/kspimpl.h" #else #include "petsc-private/pcimpl.h" #include "petsc-private/kspimpl.h" #endif #else #include "private/pcimpl.h" #include "private/kspimpl.h" #endif #include "pc_GtKG.h" #include <StGermain/StGermain.h> #include <StgDomain/StgDomain.h> #define PCTYPE_GtKG "gtkg" /* private data */ typedef struct { Mat G, K; /* G \in [M x N], K \in [M x M] */ Mat M; /* the velocity mass matrix */ Vec inv_diag_M; PetscTruth form_GtG; /* don't allow anything else yet */ Mat GtG; KSP ksp; Vec s,t,X; /* s \in [M], t \in [N], X \in [M] */ PetscTruth monitor_activated; PetscTruth monitor_rhs_consistency; } _PC_GtKG; typedef _PC_GtKG* PC_GtKG; /* private prototypes */ PetscErrorCode BSSCR_PCApply_GtKG( PC pc, Vec x, Vec y ); PetscErrorCode BSSCR_PCApplyTranspose_GtKG( PC pc, Vec x, Vec y ); PetscErrorCode BSSCR_BSSCR_PCApply_GtKG_diagonal_scaling( PC pc, Vec x, Vec y ); PetscErrorCode BSSCR_BSSCR_PCApplyTranspose_GtKG_diagonal_scaling( PC pc, Vec x, Vec y ); PetscErrorCode BSSCR_PCSetUp_GtKG( PC pc ); PetscErrorCode BSSCR_pc_warn( PC pc, const char func_name[] ) { const PCType type; PCGetType( pc, &type ); if( strcmp(type,PCTYPE_GtKG)!=0 ) { printf("Warning(%s): PC type (%s) should be gtkg \n",func_name, type ); PetscFunctionReturn(0); } PetscFunctionReturn(0); } PetscErrorCode BSSCR_pc_error( PC pc, const char func_name[] ) { const PCType type; PCGetType( pc, &type ); if( strcmp(type,PCTYPE_GtKG)!=0 ) { printf("Error(%s): PC type (%s) should be gtkg \n",func_name, type ); PetscFinalize(); exit(0); } PetscFunctionReturn(0); } void BSSCR_get_number_nonzeros_AIJ( Mat A, PetscInt *nnz ) { MatInfo info; MatGetInfo( A, MAT_GLOBAL_SUM, &info ); *nnz = info.nz_used; } /* I should not modify setup called!! This is handled via petsc. */ PetscErrorCode BSSCR_PCSetUp_GtKG( PC pc ) { PC_GtKG ctx = (PC_GtKG)pc->data; PetscReal fill; Mat Ident; Vec diag; PetscInt M,N, m,n; MPI_Comm comm; PetscInt nnz_I, nnz_G; const MatType mtype; const char *prefix; PetscTruth wasSetup; if( ctx->K == PETSC_NULL ) { Stg_SETERRQ( PETSC_ERR_SUP, "gtkg: K not set" ); } if( ctx->G == PETSC_NULL ) { Stg_SETERRQ( PETSC_ERR_SUP, "gtkg: G not set" ); } PetscObjectGetComm( (PetscObject)ctx->K, &comm ); /* Check for existence of objects and trash any which exist */ if( ctx->form_GtG == PETSC_TRUE && ctx->GtG != PETSC_NULL ) { Stg_MatDestroy(&ctx->GtG ); ctx->GtG = PETSC_NULL; } if( ctx->s != PETSC_NULL ) { Stg_VecDestroy(&ctx->s ); ctx->s = PETSC_NULL; } if( ctx->X != PETSC_NULL ) { Stg_VecDestroy(&ctx->X ); ctx->X = PETSC_NULL; } if( ctx->t != PETSC_NULL ) { Stg_VecDestroy(&ctx->t ); ctx->t = PETSC_NULL; } if( ctx->inv_diag_M != PETSC_NULL ) { Stg_VecDestroy(&ctx->inv_diag_M ); ctx->inv_diag_M = PETSC_NULL; } /* Create vectors */ MatGetVecs( ctx->K, &ctx->s, &ctx->X ); MatGetVecs( ctx->G, &ctx->t, PETSC_NULL ); if( ctx->M != PETSC_NULL ) { MatGetVecs( ctx->K, &ctx->inv_diag_M, PETSC_NULL ); MatGetDiagonal( ctx->M, ctx->inv_diag_M ); VecReciprocal( ctx->inv_diag_M ); /* change the pc_apply routines */ pc->ops->apply = BSSCR_BSSCR_PCApply_GtKG_diagonal_scaling; pc->ops->applytranspose = BSSCR_BSSCR_PCApplyTranspose_GtKG_diagonal_scaling; } /* Assemble GtG */ MatGetSize( ctx->G, &M, &N ); MatGetLocalSize( ctx->G, &m, &n ); MatGetVecs( ctx->G, PETSC_NULL, &diag ); VecSet( diag, 1.0 ); MatCreate( comm, &Ident ); MatSetSizes( Ident, m,m , M, M ); #if (((PETSC_VERSION_MAJOR==3) && (PETSC_VERSION_MINOR>=3)) || (PETSC_VERSION_MAJOR>3) ) MatSetUp(Ident); #endif MatGetType( ctx->G, &mtype ); MatSetType( Ident, mtype ); if( ctx->M == PETSC_NULL ) { MatDiagonalSet( Ident, diag, INSERT_VALUES ); } else { MatDiagonalSet( Ident, ctx->inv_diag_M, INSERT_VALUES ); } BSSCR_get_number_nonzeros_AIJ( Ident, &nnz_I ); BSSCR_get_number_nonzeros_AIJ( ctx->G, &nnz_G ); //fill = 1.0; /* Not sure the best way to estimate the fill factor. GtG is a laplacian on the pressure space. This might tell us something useful... */ fill = (PetscReal)(nnz_G)/(PetscReal)( nnz_I ); MatPtAP( Ident, ctx->G, MAT_INITIAL_MATRIX, fill, &ctx->GtG ); Stg_MatDestroy(&Ident); Stg_VecDestroy(&diag ); Stg_KSPSetOperators( ctx->ksp, ctx->GtG, ctx->GtG, SAME_NONZERO_PATTERN ); if (!pc->setupcalled) { wasSetup = PETSC_FALSE; PCGetOptionsPrefix( pc,&prefix ); KSPSetOptionsPrefix( ctx->ksp, prefix ); KSPAppendOptionsPrefix( ctx->ksp, "pc_gtkg_" ); /* -pc_GtKG_ksp_type <type>, -ksp_GtKG_pc_type <type> */ } else { wasSetup = PETSC_TRUE; } // if (!wasSetup && pc->setfromoptionscalled) { if (!wasSetup) { KSPSetFromOptions(ctx->ksp); } PetscFunctionReturn(0); } PetscErrorCode BSSCR_PCDestroy_GtKG( PC pc ) { PC_GtKG ctx = (PC_GtKG)pc->data; if( ctx == PETSC_NULL ) { PetscFunctionReturn(0); } if( ctx->form_GtG == PETSC_TRUE && ctx->GtG != PETSC_NULL ) { Stg_MatDestroy(&ctx->GtG ); } if( ctx->ksp != PETSC_NULL ) { Stg_KSPDestroy(&ctx->ksp ); } if( ctx->s != PETSC_NULL ) { Stg_VecDestroy(&ctx->s ); } if( ctx->X != PETSC_NULL ) { Stg_VecDestroy(&ctx->X ); } if( ctx->t != PETSC_NULL ) { Stg_VecDestroy(&ctx->t ); } if( ctx->inv_diag_M != PETSC_NULL ) { Stg_VecDestroy(&ctx->inv_diag_M ); ctx->inv_diag_M = PETSC_NULL; } PetscFree( ctx ); PetscFunctionReturn(0); } PetscErrorCode BSSCR_PCView_GtKG( PC pc, PetscViewer viewer ) { PC_GtKG ctx = (PC_GtKG)pc->data; PetscViewerASCIIPushTab(viewer); //1 if( ctx->M == PETSC_NULL ) { PetscViewerASCIIPrintf( viewer, "gtkg: Standard \n" ); }else { PetscViewerASCIIPrintf( viewer, "gtkg: Least Squares Commutator \n" ); } PetscViewerASCIIPrintf( viewer, "gtkg-ksp \n" ); PetscViewerASCIIPrintf(viewer,"---------------------------------\n"); PetscViewerASCIIPushTab(viewer); KSPView( ctx->ksp, viewer ); PetscViewerASCIIPopTab(viewer); PetscViewerASCIIPrintf(viewer,"---------------------------------\n"); PetscViewerASCIIPopTab(viewer); //1 PetscFunctionReturn(0); } PetscErrorCode BSSCR_Lp_monitor( KSP ksp, PetscInt index ) { PetscInt max_it; PetscReal rnorm; KSPConvergedReason reason; KSPGetIterationNumber( ksp, &max_it ); KSPGetResidualNorm( ksp, &rnorm ); KSPGetConvergedReason( ksp, &reason ); if (ksp->reason > 0) { PetscPrintf(((PetscObject)ksp)->comm,"\t<Lp(%d)>: Linear solve converged. its.=%.4d ; |r|=%5.5e ; Reason=%s\n", index, max_it, rnorm, KSPConvergedReasons[reason] ); } else { PetscPrintf(((PetscObject)ksp)->comm,"\t<Lp(%d)>: Linear solve did not converge. its.=%.4d ; |r|=%5.5e ; Reason=%s\n", index, max_it, rnorm, KSPConvergedReasons[reason]); } PetscFunctionReturn(0); } PetscErrorCode BSSCR_PCBFBTSubKSPMonitor( KSP ksp, PetscInt index, PetscLogDouble time ) { PetscInt max_it; PetscReal rnorm; KSPConvergedReason reason; KSPGetIterationNumber( ksp, &max_it ); KSPGetResidualNorm( ksp, &rnorm ); KSPGetConvergedReason( ksp, &reason ); PetscPrintf(((PetscObject)ksp)->comm," PCBFBTSubKSP (%d): %D Residual norm; r0 %12.12e, r %12.12e: Reason %s: Time %5.5e \n", index, max_it, ksp->rnorm0, rnorm, KSPConvergedReasons[reason], time ); PetscFunctionReturn(0); } /* Checks rhs of Lp systems is in the null space of Lp, i.e. {rhs} \centerdot {null_space} = 0 Since Lp should contain the null space {1}, we just check the \sum_i rhs_i = 0 */ PetscErrorCode BSSCRBSSCR_Lp_monitor_check_rhs_consistency( KSP ksp, Vec rhs, PetscInt index ) { PetscScalar dot; #if 0 Vec one; VecDuplicate( rhs, &one ); VecSet( one, 1.0 ); VecDot( rhs, one, &dot ); if( PetscAbsReal(dot) > 1.0e-8 ) { PetscPrintf(ksp->comm," ($D) Lp z = r: ******* WARNING ******* RHS is not consistent. {b}.{1} = %5.5e \n", index, dot ); } Stg_VecDestroy(&one ); PetscFunctionReturn(0); #endif #if 0 VecSum( rhs, &dot ); if( PetscAbsReal(dot) > 1.0e-8 ) { PetscPrintf(((PetscObject)ksp)->comm," (%D) Lp z = r: ******* WARNING ******* RHS is not consistent. {b}.{1} = %5.5e \n", index, dot ); BSSCR_VecRemoveConstNullspace( rhs, PETSC_NULL ); } #endif PetscFunctionReturn(0); } /* Performs y <- S^{-1} x S^{-1} = ( G^T G )^{-1} G^T K G ( G^T G )^{-1} */ PetscErrorCode BSSCR_PCApply_GtKG( PC pc, Vec x, Vec y ) { PC_GtKG ctx = (PC_GtKG)pc->data; KSP ksp; Mat K, G; Vec s,t,X; PetscLogDouble t0,t1; ksp = ctx->ksp; K = ctx->K; G = ctx->G; s = ctx->s; t = ctx->t; X = ctx->X; if (ctx->monitor_rhs_consistency) { BSSCRBSSCR_Lp_monitor_check_rhs_consistency(ksp,x,1); } PetscGetTime(&t0); KSPSolve( ksp, x, t ); /* t <- GtG_inv x */ PetscGetTime(&t1); if (ctx->monitor_activated) { BSSCR_PCBFBTSubKSPMonitor(ksp,1,(t1-t0)); } MatMult( G, t, s ); /* s <- G t */ MatMult( K, s, X ); /* X <- K s */ MatMultTranspose( G, X, t ); /* t <- Gt X */ if (ctx->monitor_rhs_consistency) { BSSCRBSSCR_Lp_monitor_check_rhs_consistency(ksp,t,2); } PetscGetTime(&t0); KSPSolve( ksp, t, y ); /* y <- GtG_inv t */ PetscGetTime(&t1); if (ctx->monitor_activated) { BSSCR_PCBFBTSubKSPMonitor(ksp,2,(t1-t0)); } PetscFunctionReturn(0); } /* Need to check this one if correct */ /* S^{-1} = ( G^T G )^{-1} G^T K G ( G^T G )^{-1} = A C A S^{-T} = A^T (A C)^T = A^T C^T A^T, but A = G^T G which is symmetric = A C^T A = A G^T ( G^T K )^T A = A G^T K^T G A */ PetscErrorCode BSSCR_PCApplyTranspose_GtKG( PC pc, Vec x, Vec y ) { PC_GtKG ctx = (PC_GtKG)pc->data; KSP ksp; Mat K, G; Vec s,t,X; PetscLogDouble t0,t1; ksp = ctx->ksp; K = ctx->K; G = ctx->G; s = ctx->s; t = ctx->t; X = ctx->X; if (ctx->monitor_rhs_consistency) { BSSCRBSSCR_Lp_monitor_check_rhs_consistency(ksp,x,1); } PetscGetTime(&t0); KSPSolve( ksp, x, t ); /* t <- GtG_inv x */ PetscGetTime(&t1); if (ctx->monitor_activated) { BSSCR_PCBFBTSubKSPMonitor(ksp,1,(t1-t0)); } MatMult( G, t, s ); /* s <- G t */ MatMultTranspose( K, s, X ); /* X <- K^T s */ MatMultTranspose( G, X, t ); /* t <- Gt X */ if (ctx->monitor_rhs_consistency) { BSSCRBSSCR_Lp_monitor_check_rhs_consistency(ksp,t,2); } PetscGetTime(&t0); KSPSolve( ksp, t, y ); /* y <- GtG_inv t */ PetscGetTime(&t1); if (ctx->monitor_activated) { BSSCR_PCBFBTSubKSPMonitor(ksp,2,(t1-t0)); } PetscFunctionReturn(0); } /* Performs y <- S^{-1} x S^{-1} = ( G^T Di G )^{-1} G^T Di K Di G ( G^T Di G )^{-1} where Di = diag(M)^{-1} */ PetscErrorCode BSSCR_BSSCR_PCApply_GtKG_diagonal_scaling( PC pc, Vec x, Vec y ) { PC_GtKG ctx = (PC_GtKG)pc->data; KSP ksp; Mat K, G; Vec s,t,X,di; ksp = ctx->ksp; K = ctx->K; G = ctx->G; di = ctx->inv_diag_M; s = ctx->s; t = ctx->t; X = ctx->X; if (ctx->monitor_rhs_consistency) { BSSCRBSSCR_Lp_monitor_check_rhs_consistency(ksp,x,1); } KSPSolve( ksp, x, t ); /* t <- GtG_inv x */ if (ctx->monitor_activated) { BSSCR_Lp_monitor(ksp,2); } MatMult( G, t, s ); /* s <- G t */ VecPointwiseMult( s, s,di ); /* s <- s * di */ MatMult( K, s, X ); /* X <- K s */ VecPointwiseMult( X, X,di ); /* X <- X * di */ MatMultTranspose( G, X, t ); /* t <- Gt X */ if (ctx->monitor_rhs_consistency) { BSSCRBSSCR_Lp_monitor_check_rhs_consistency(ksp,t,2); } KSPSolve( ksp, t, y ); /* y <- GtG_inv t */ if (ctx->monitor_activated) { BSSCR_Lp_monitor(ksp,2); } PetscFunctionReturn(0); } PetscErrorCode BSSCR_BSSCR_PCApplyTranspose_GtKG_diagonal_scaling( PC pc, Vec x, Vec y ) { PC_GtKG ctx = (PC_GtKG)pc->data; KSP ksp; Mat K, G; Vec s,t,X,di; ksp = ctx->ksp; K = ctx->K; G = ctx->G; di = ctx->inv_diag_M; s = ctx->s; t = ctx->t; X = ctx->X; if (ctx->monitor_rhs_consistency) { BSSCRBSSCR_Lp_monitor_check_rhs_consistency(ksp,x,1); } KSPSolve( ksp, x, t ); /* t <- GtG_inv x */ if (ctx->monitor_activated) { BSSCR_Lp_monitor(ksp,1); } MatMult( G, t, s ); /* s <- G t */ VecPointwiseMult( s, s,di ); /* s <- s * di */ MatMultTranspose( K, s, X ); /* X <- K^T s */ VecPointwiseMult( X, X,di ); /* X <- X * di */ MatMultTranspose( G, X, t ); /* t <- Gt X */ if (ctx->monitor_rhs_consistency) { BSSCRBSSCR_Lp_monitor_check_rhs_consistency(ksp,t,2); } KSPSolve( ksp, t, y ); /* y <- GtG_inv t */ if (ctx->monitor_activated) { BSSCR_Lp_monitor(ksp,2); } PetscFunctionReturn(0); } /* Only the options related to GtKG should be set here. */ PetscErrorCode BSSCR_PCSetFromOptions_GtKG( PC pc ) { PC_GtKG ctx = (PC_GtKG)pc->data; PetscTruth ivalue, flg; PetscOptionsGetTruth( PETSC_NULL, "-pc_gtkg_monitor", &ivalue, &flg ); if( flg==PETSC_TRUE ) { ctx->monitor_activated = ivalue; } PetscOptionsGetTruth( PETSC_NULL, "-pc_gtkg_monitor_rhs_consistency", &ivalue, &flg ); if( flg==PETSC_TRUE ) { ctx->monitor_rhs_consistency = ivalue; } PetscFunctionReturn(0); } /* ---- Exposed functions ---- */ PetscErrorCode BSSCR_PCCreate_GtKG( PC pc ) { PC_GtKG pc_data; PetscErrorCode ierr; /* create memory for ctx */ ierr = Stg_PetscNew( _PC_GtKG,&pc_data);CHKERRQ(ierr); /* init ctx */ pc_data->K = PETSC_NULL; pc_data->G = PETSC_NULL; pc_data->M = PETSC_NULL; pc_data->GtG = PETSC_NULL; pc_data->form_GtG = PETSC_TRUE; pc_data->ksp = PETSC_NULL; pc_data->monitor_activated = PETSC_FALSE; pc_data->monitor_rhs_consistency = PETSC_FALSE; pc_data->s = PETSC_NULL; pc_data->t = PETSC_NULL; pc_data->X = PETSC_NULL; pc_data->inv_diag_M = PETSC_NULL; /* create internals */ KSPCreate( ((PetscObject)pc)->comm, &pc_data->ksp ); /* set ctx onto pc */ pc->data = (void*)pc_data; ierr = PetscLogObjectMemory(pc,sizeof(_PC_GtKG));CHKERRQ(ierr); /* define operations */ pc->ops->setup = BSSCR_PCSetUp_GtKG; pc->ops->view = BSSCR_PCView_GtKG; pc->ops->destroy = BSSCR_PCDestroy_GtKG; pc->ops->setfromoptions = BSSCR_PCSetFromOptions_GtKG; pc->ops->apply = BSSCR_PCApply_GtKG; pc->ops->applytranspose = BSSCR_PCApplyTranspose_GtKG; PetscFunctionReturn(0); } /* K & G must different to PETSC_NULL M can be PETSC_NULL */ PetscErrorCode BSSCR_PCGtKGSet_Operators( PC pc, Mat K, Mat G, Mat M ) { PC_GtKG ctx = (PC_GtKG)pc->data; BSSCR_pc_error( pc, "__func__" ); ctx->K = K; ctx->G = G; ctx->M = M; PetscFunctionReturn(0); } PetscErrorCode BSSCR_PCGtKGSet_OperatorForAlgebraicCommutator( PC pc, Mat M ) { PC_GtKG ctx = (PC_GtKG)pc->data; BSSCR_pc_error( pc, "__func__" ); ctx->M = M; PetscFunctionReturn(0); } PetscErrorCode BSSCR_PCGtKGAttachNullSpace( PC pc ) { PC_GtKG ctx = (PC_GtKG)pc->data; MatNullSpace nsp; BSSCR_pc_error( pc, "__func__" ); /* Attach a null space */ MatNullSpaceCreate( PETSC_COMM_WORLD, PETSC_TRUE, PETSC_NULL, PETSC_NULL, &nsp ); #if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR <6) ) KSPSetNullSpace( ctx->ksp, nsp ); #else Mat A; KSPGetOperators(ctx->ksp,&A,NULL);//Note: DOES NOT increase the reference counts of the matrix, so you should NOT destroy them. MatSetNullSpace( A, nsp); #endif /* NOTE: This does NOT destroy the memory for nsp, it just decrements the nsp->refct, so that the next time MatNullSpaceDestroy() is called, the memory will be released. The next time this is called will be by KSPDestroy(); */ MatNullSpaceDestroy( nsp ); PetscFunctionReturn(0); } PetscErrorCode BSSCR_PCGtKGGet_KSP( PC pc, KSP *ksp ) { PC_GtKG ctx = (PC_GtKG)pc->data; BSSCR_pc_error( pc, "__func__" ); if( ksp != PETSC_NULL ) { (*ksp) = ctx->ksp; } PetscFunctionReturn(0); } PetscErrorCode BSSCR_PCGtKGSet_KSP( PC pc, KSP ksp ) { PC_GtKG ctx = (PC_GtKG)pc->data; BSSCR_pc_error( pc, "__func__" ); if( ctx->ksp != PETSC_NULL ) { Stg_KSPDestroy(&ctx->ksp); } ctx->ksp = ksp; PetscFunctionReturn(0); } #endif
{ "alphanum_fraction": 0.6305747126, "avg_line_length": 25.1082251082, "ext": "c", "hexsha": "906ed26364c4b7a38bd4b3bb0bbff569314c79e8", "lang": "C", "max_forks_count": 68, "max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z", "max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z", "max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "longgangfan/underworld2", "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/pc_GtKG.c", "max_issues_count": 561, "max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z", "max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z", "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "longgangfan/underworld2", "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/pc_GtKG.c", "max_line_length": 137, "max_stars_count": 116, "max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "longgangfan/underworld2", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/pc_GtKG.c", "max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z", "max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z", "num_tokens": 6276, "size": 17400 }
#include <stdio.h> #include <string.h> #include <image_lib.h> #include <gsl/gsl_fit.h> #include "tz_image_lib.h" #include "tz_string.h" #include "tz_fimage_lib.h" #include "tz_error.h" #include "tz_darray.h" #include "private/alignstack.c" #include "private/alignconf.c" int main(int argc, const char *argv[]) { const char *result_dir = "/Users/zhaot/Work/V3D/neurolabi/data/align"; const char *image_dir = "/Users/zhaot/Data/nathan/2008-04-18"; char file_path[150]; char image_path[150]; char result_path[150]; char file1[100], file2[100]; char id[100]; fullpath(result_dir, "align_input.txt", file_path); FILE *fp = fopen(file_path, "r"); while ((Read_Word(fp, file1, 0) > 0) && (Read_Word(fp, file2, 0) > 0)) { align_id(file1, file2, id); strcat(id, ".txt"); fullpath(result_dir, id, result_path); if (!fexist(result_path)) { printf("%s, %s\n", file1, file2); fullpath(image_dir, file1, image_path); Stack *stack1 = Read_Stack(image_path); fullpath(image_dir, file2, image_path); Stack *stack2 = Read_Stack(image_path); // Stack_Threshold_Tp4(stack1, 0, 65535); //Stack_Threshold_Tp4(stack2, 0, 65535); int chopoff1 = estimate_chopoff(stack1); printf("%d\n", chopoff1); Stack *substack1 = Crop_Stack(stack1, 0, 0, chopoff1, stack1->width, stack1->height, stack1->depth - chopoff1, NULL); int chopoff2 = estimate_chopoff(stack2); printf("%d\n", chopoff2); Stack *substack2 = Crop_Stack(stack2, 0, 0, chopoff2, stack2->width, stack2->height, stack2->depth - chopoff2, NULL); float unnorm_maxcorr; int offset[3]; int intv[] = {3, 3, 3}; float score = Align_Stack_MR_F(substack1, substack2, intv, 1, offset, &unnorm_maxcorr); if (score <= 0.0) { printf("failed\n"); write_align_result(result_dir, file1, file2, NULL); } else { offset[2] += chopoff2; printf("(%d, %d, %d): %g\n", offset[0], offset[1], offset[2], score); write_align_result(result_dir, file1, file2, offset); } Kill_Stack(substack1); Kill_Stack(substack2); Kill_Stack(stack1); Kill_Stack(stack2); } } fclose(fp); return 0; }
{ "alphanum_fraction": 0.632535461, "avg_line_length": 27.512195122, "ext": "c", "hexsha": "c19c9f237b1916313a8e256fd110fe8d38d8d2b9", "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": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzhmark/vaa3d_tools", "max_forks_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/alignstack_batch.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_issues_repo_issues_event_max_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_issues_event_min_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzhmark/vaa3d_tools", "max_issues_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/alignstack_batch.c", "max_line_length": 76, "max_stars_count": 1, "max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzhmark/vaa3d_tools", "max_stars_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/alignstack_batch.c", "max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z", "num_tokens": 708, "size": 2256 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <limits.h> #include <float.h> #include "parmt_postProcess.h" #ifdef PARMT_USE_INTEL #include <mkl_cblas.h> #else #include <cblas.h> #endif #include "iscl/array/array.h" #include "iscl/memory/memory.h" static double *diff(const int n, const double *__restrict__ x, int *ierr); static int computePadding8i(const int n); int marginal_getOptimum(const int nloc, const int nm, const int nb, const int ng, const int nk, const int ns, const int nt, const double *__restrict__ phi, int *jloc, int *jm, int *jb, int *jg, int *jk, int *js, int *jt) { int ib, ig, ik, iloc, imax, im, imt, indx, is, it, nmt; enum isclError_enum ierr; nmt = nm*nb*ng*nk*ns*nt; imax = array_argmax64f(nmt*nloc, phi, &ierr); for (iloc=0; iloc<nloc; iloc++) { for (im=0; im<nm; im++) { for (ib=0; ib<nb; ib++) { for (ig=0; ig<ng; ig++) { for (ik=0; ik<nk; ik++) { for (is=0; is<ns; is++) { for (it=0; it<nt; it++) { imt = im*nb*ng*nk*ns*nt + ib*ng*nk*ns*nt + ig*nk*ns*nt + ik*ns*nt + is*nt + it; indx = iloc*nmt + imt; if (indx == imax) { *jloc = iloc; *jm = im; *jb = ib; *jg = ig; *jk = ik; *js = is; *jt = it; } } } } } } } } return 0; } /*! * @brief Computes the marginal PDF at lune points using Eqn 48 of * Tape and Tape 2015. * * @param[in] nloc number of locations in grid-search. * @param[in] nm number of moment magnitudes in grid search * @param[in] nb number of colatitudes * @param[in] betas colatitudes (radians) of lune points [nb] * @param[in] ng number of longitudes * @param[in] gammas longitudes (radians) of lune points [ng] * @param[in] nk number of strike angles * @param[in] kappas fault strike angles (radians) [nk] * @param[in] ns number of slip angles * @param[in] sigmas fault slip angles (radians) [ns] * @param[in] nh number of dip angles * @param[in] h related to dip angles (radians) [nh] * @param[in] phi objective function computed throughout grid-search * space to marginalize [nloc*nm*nb*ng*nk*ns*nh] * @param[out] luneMPDF marginalized lune [nb x ng]. the ib, ig'th * colatitude and longitude is given by ib*ng + ig. * * @result 0 indicates success * * @author Ben Baker * * @copyright ISTI distributed under Apache 2 * * @bug There is inadequate handling of moment tensor scaling and locs * is a misnomer. Technically this can only loop in 1D and I would * require the cell volumes for position to loop on locations. */ int marginal_computeLuneMPDF(const int nloc, const int nm, const int nb, const double *__restrict__ betas, const int ng, const double *__restrict__ gammas, const int nk, const double *__restrict__ kappas, const int ns, const double *__restrict__ sigmas, const int nh, const double *__restrict__ h, const double *__restrict__ phi, double *__restrict__ luneMPDF) { const char *fcnm = "marginal_computeLuneMPDF\0"; int ib, ierr, ig, igIb, ih, ik, iloc, im, imt, indx, is, nmt; double *cos3g, *dh, *dk, *ds, *twoSinB3; double sinb, sinb3, dkdsdh, dV; nmt = nm*nb*ng*nk*ns*nh; memset(luneMPDF, 0, (size_t) (ng*nb)*sizeof(double)); if (nk < 2 || ns < 2 || nh < 2) { if (nk < 2){printf("%s: Error nk must be > 1\n", fcnm);} if (ns < 2){printf("%s: Error ns must be > 1\n", fcnm);} if (nh < 2){printf("%s: Error nh must be > 1\n", fcnm);} } // Differentiate weights for Riemann quadrature dk = diff(nk, kappas, &ierr); ds = diff(ns, sigmas, &ierr); dh = diff(nh, h, &ierr); // theta goes from 0 to pi/2 as h goes from 1 to 0 hence it's // orientation is reversed from our ini file (recall that it asks // for theta and not h) and hence -dh is not conducive to quadrature. cblas_dscal(nh-1, -1.0, dh, 1); // Precompute the trigonemetric terms twoSinB3 = memory_calloc64f(nb); for (ib=0; ib<nb; ib++) { twoSinB3[ib] = 2.0*pow(sin(betas[ib]), 3); } cos3g = memory_calloc64f(ng); for (ig=0; ig<ng; ig++) { cos3g[ig] = cos(3.0*gammas[ig]); } // Marginalize the lune for (iloc=0; iloc<nloc; iloc++) { for (im=0; im<nm; im++) { for (ib=0; ib<nb; ib++) { for (ig=0; ig<ng; ig++) { for (ik=0; ik<nk-1; ik++) { for (is=0; is<ns-1; is++) { for (ih=0; ih<nh-1; ih++) { imt = im*nb*ng*nk*ns*nh + ib*ng*nk*ns*nh + ig*nk*ns*nh + ik*ns*nh + is*nh + ih; igIb = ib*ng + ig; indx = iloc*nmt + imt; //sinb = sin(betas[ib]); //sinb3 = (sinb*sinb)*sinb; //twoSinb3 = 2.0*sinb3; //cos3g = cos(3.0*gammas[ig]); dkdsdh = (dk[ik]*ds[is])*dh[ih]; dV = twoSinB3[ib]*cos3g[ig]*dkdsdh; luneMPDF[igIb] = luneMPDF[igIb] + phi[indx]*dV; } } } } } } } memory_free64f(&dh); memory_free64f(&dk); memory_free64f(&ds); memory_free64f(&twoSinB3); memory_free64f(&cos3g); return 0; } int marginal_computeLuneUVMPDF(const int nloc, const int nm, const int nu, const double *__restrict__ us, const int nv, const double *__restrict__ vs, const int nk, const double *__restrict__ kappas, const int ns, const double *__restrict__ sigmas, const int nh, const double *__restrict__ hs, const double *__restrict__ phi, double *__restrict__ luneMPDF) { const char *fcnm = "marginal_computeLuneMPDF\0"; int ierr, ih, ik, iloc, im, imt, indx, is, iu, iuIv, iv, nmt; double *dh, *dk, *ds, *du, *dv; double dudv, dkdsdh, dV; const double sqrt8 = sqrt(8.0); nmt = nm*nu*nv*nk*ns*nh; memset(luneMPDF, 0, (size_t) (nu*nv)*sizeof(double)); if (nk < 2 || ns < 2 || nh < 2) { if (nk < 2){printf("%s: Error nk must be > 1\n", fcnm);} if (ns < 2){printf("%s: Error ns must be > 1\n", fcnm);} if (nh < 2){printf("%s: Error nh must be > 1\n", fcnm);} } // Differentiate weights for Riemann quadrature dk = diff(nk, kappas, &ierr); ds = diff(ns, sigmas, &ierr); dh = diff(nh, hs, &ierr); /* du = diff(nu, us, &ierr); dv = diff(nv, vs, &ierr); for (int i=0; i<nu; i++) { printf("du: %f: \n", du[i]); } for (int i=0; i<nv; i++) { printf("dv: %f: \n", dv[i]); } */ // theta goes from 0 to pi/2 as h goes from 1 to 0 hence it's // orientation is reversed from our ini file (recall that it asks // for theta and not h) and hence -dh is not conducive to quadrature. cblas_dscal(nh-1, -1.0, dh, 1); // Marginalize the lune for (iloc=0; iloc<nloc; iloc++) { for (im=0; im<nm; im++) { for (iu=0; iu<nu; iu++) { for (iv=0; iv<nv; iv++) { for (ik=0; ik<nk-1; ik++) { for (is=0; is<ns-1; is++) { for (ih=0; ih<nh-1; ih++) { imt = im*nu*nv*nk*ns*nh + iu*nv*nk*ns*nh + iv*nk*ns*nh + ik*ns*nh + is*nh + ih; iuIv = iv*nu + iu; indx = iloc*nmt + imt; //sinb = sin(betas[ib]); //sinb3 = (sinb*sinb)*sinb; //twoSinb3 = 2.0*sinb3; //cos3g = cos(3.0*gammas[ig]); dudv = sqrt8; //du[iu]*dv[iv]; dkdsdh = (dk[ik]*ds[is])*dh[ih]; dV = dudv*dkdsdh; luneMPDF[iuIv] = luneMPDF[iuIv] + phi[indx]*dV; } } } } } } } /* memory_free64f(&du); memory_free64f(&dv); */ memory_free64f(&dk); memory_free64f(&ds); memory_free64f(&dh); return 0; } //============================================================================// int marginal_computeDepthMPDF(const int nloc, const int nm, const double *__restrict__ M0s, const int nb, const double *__restrict__ betas, const int ng, const double *__restrict__ gammas, const int nk, const double *__restrict__ kappas, const int ns, const double *__restrict__ sigmas, const int nt, const double *__restrict__ thetas, const double *__restrict__ phi, double *__restrict__ depMagMPDF, double *__restrict__ depMPDF) { const char *fcnm = "marginal_computeDepthMPDF\0"; double *cos3g, *db, *dg, *dk, *dm, *ds, *dt, *twoSinB4, *sint, arg, dbdg, dkdsdt, dV5, geom, sum; int ib, ierr, ig, ik, iloc, im, imt, indx, is, it, jloc; ierr = 0; memset(depMPDF, 0, (size_t) nloc*sizeof(double)); memset(depMagMPDF, 0, (size_t) (nloc*nm)*sizeof(double)); // Cell spacings for for Riemann quadrature dm = memory_calloc64f(nm); db = memory_calloc64f(nb); dg = memory_calloc64f(ng); dk = memory_calloc64f(nk); ds = memory_calloc64f(ns); dt = memory_calloc64f(nt); ierr += postprocess_computeBetaCellSpacing(nb, betas, db); ierr += postprocess_computeGammaCellSpacing(ng, gammas, dg); ierr += postprocess_computeKappaCellSpacing(nk, kappas, dk); ierr += postprocess_computeSigmaCellSpacing(ns, sigmas, ds); ierr += postprocess_computeThetaCellSpacing(nt, thetas, dt); ierr += postprocess_computeM0CellSpacing(nm, M0s, dm); printf("%s: for now i'm setting dm = 1 and dl = 1\n", fcnm); array_set64f_work(nm, 1.0, dm); if (ierr != 0) { printf("%s: Failed to compute cell spacing\n", fcnm); return -1; } if (array_min64f(nm, dm, &ierr) <= 0.0 || array_min64f(nb, db, &ierr) <= 0.0 || array_min64f(ng, dg, &ierr) <= 0.0 || array_min64f(nk, dk, &ierr) <= 0.0 || array_min64f(ns, ds, &ierr) <= 0.0 || array_min64f(nt, dt, &ierr) <= 0.0) { printf("%s: Negative jacobian\n", fcnm); return -1; } // Compute the geometric factors twoSinB4 = memory_calloc64f(nb); for (ib=0; ib<nb; ib++) { twoSinB4[ib] = 2.0*pow(sin(betas[ib]), 4); } sint = memory_calloc64f(nt); for (it=0; it<nt; it++) { sint[it] = sin(thetas[it]); } cos3g = memory_calloc64f(ng); for (ig=0; ig<ng; ig++) { cos3g[ig] = cos(3.0*gammas[ig]); } if (array_min64f(nb, twoSinB4, &ierr) <= 0.0 || array_min64f(nt, sint, &ierr) <= 0.0 || array_min64f(ng, cos3g, &ierr) <= 0.0) { printf("%s: Warning negative jacobian from geometric factors\n", fcnm); } for (iloc=0; iloc<nloc; iloc++) { for (im=0; im<nm; im++) { for (ib=0; ib<nb; ib++) { for (ig=0; ig<ng; ig++) { for (ik=0; ik<nk; ik++) { for (is=0; is<ns; is++) { for (it=0; it<nt; it++) { imt = iloc*nm*nb*ng*nk*ns*nt + im*nb*ng*nk*ns*nt + ib*ng*nk*ns*nt + ig*nk*ns*nt + ik*ns*nt + is*nt + it; dkdsdt = (dk[ik]*ds[is])*dt[it]; dbdg = db[ib]*dg[ig]; geom = (twoSinB4[ib]*cos3g[ig])*sint[it]; dV5 = geom*(dbdg*dkdsdt); //if (dV5 < 0.0){printf("error\n");} arg = phi[imt]*dV5; jloc = im*nloc + iloc; depMagMPDF[jloc] = depMagMPDF[jloc] + arg; } } } } } } } // Integrate out the depMagMPDF for (iloc=0; iloc<nloc; iloc++) { for (im=0; im<nm; im++) { jloc = im*nloc + iloc; depMPDF[iloc] = depMPDF[iloc] + depMagMPDF[jloc]*dm[im]; } } memory_free64f(&cos3g); memory_free64f(&sint); memory_free64f(&twoSinB4); memory_free64f(&db); memory_free64f(&dg); memory_free64f(&dk); memory_free64f(&ds); memory_free64f(&dt); memory_free64f(&dm); return ierr; } //============================================================================// double marginal_computeNormalization( const int nloc, const double *__restrict__ deps, const int nm, const double *__restrict__ M0s, const int nb, const double *__restrict__ betas, const int ng, const double *__restrict__ gammas, const int nk, const double *__restrict__ kappas, const int ns, const double *__restrict__ sigmas, const int nt, const double *__restrict__ thetas, const double *__restrict__ phi, int *ierr) { const char *fcnm = "marginal_computeNormalization\0"; double *cos3g, *db, *dg, *dk, *dl, *dm, *ds, *dt, *twoSinB4, *sint, dbdg, dkdsdt, dV2, dV5, dV7, geom, sum; int ib, ig, ik, iloc, im, imt, is, it, nmt; *ierr = 0; sum = 0.0; nmt = nm*nb*ng*nk*ns*nt; // Cell spacings for for Riemann quadrature dl = memory_calloc64f(nloc); dm = memory_calloc64f(nm); db = memory_calloc64f(nb); dg = memory_calloc64f(ng); dk = memory_calloc64f(nk); ds = memory_calloc64f(ns); dt = memory_calloc64f(nt); *ierr += postprocess_computeBetaCellSpacing(nb, betas, db); *ierr += postprocess_computeGammaCellSpacing(ng, gammas, dg); *ierr += postprocess_computeKappaCellSpacing(nk, kappas, dk); *ierr += postprocess_computeSigmaCellSpacing(ns, sigmas, ds); *ierr += postprocess_computeThetaCellSpacing(nt, thetas, dt); *ierr += postprocess_computeM0CellSpacing(nm, M0s, dm); *ierr += postprocess_computeM0CellSpacing(nloc, deps, dl); printf("%s: for now i'm setting dm = 1 and dl = 1\n", fcnm); array_set64f_work(nm, 1.0, dm); array_set64f_work(nloc, 1.0, dl); if (*ierr != 0) { printf("%s; Error computing normalization\n", fcnm); return sum; } if (array_min64f(nloc, dl, ierr) <= 0.0 || array_min64f(nm, dm, ierr) <= 0.0 || array_min64f(nb, db, ierr) <= 0.0 || array_min64f(ng, dg, ierr) <= 0.0 || array_min64f(nk, dk, ierr) <= 0.0 || array_min64f(ns, ds, ierr) <= 0.0 || array_min64f(nt, dt, ierr) <= 0.0) { printf("%s: Negative jacobian\n", fcnm); *ierr = 1; return sum; } // Compute the geometric factors twoSinB4 = memory_calloc64f(nb); for (ib=0; ib<nb; ib++) { twoSinB4[ib] = 2.0*pow(sin(betas[ib]), 4); } sint = memory_calloc64f(nt); for (it=0; it<nt; it++) { sint[it] = sin(thetas[it]); } cos3g = memory_calloc64f(ng); for (ig=0; ig<ng; ig++) { cos3g[ig] = cos(3.0*gammas[ig]); } sum = 0.0; for (iloc=0; iloc<nloc; iloc++) { for (im=0; im<nm; im++) { for (ib=0; ib<nb; ib++) { for (ig=0; ig<ng; ig++) { for (ik=0; ik<nk; ik++) { for (is=0; is<ns; is++) { for (it=0; it<nt; it++) { imt = iloc*nm*nb*ng*nk*ns*nt + im*nb*ng*nk*ns*nt + ib*ng*nk*ns*nt + ig*nk*ns*nt + ik*ns*nt + is*nt + it; dkdsdt = (dk[ik]*ds[is])*dt[it]; dbdg = db[ib]*dg[ig]; geom = (twoSinB4[ib]*cos3g[ig])*sint[it]; dV5 = geom*(dbdg*dkdsdt); dV2 = dl[iloc]*dm[im]; dV7 = dV5*dV2; sum = sum + phi[imt]*dV7; } } } } } } } memory_free64f(&cos3g); memory_free64f(&sint); memory_free64f(&twoSinB4); memory_free64f(&db); memory_free64f(&dg); memory_free64f(&dk); memory_free64f(&ds); memory_free64f(&dt); memory_free64f(&dl); memory_free64f(&dm); return sum; } //============================================================================// int marginal_computeMarginalBeachball( const int nloc, const int nm, const int nb, const double *__restrict__ betas, const int ng, const double *__restrict__ gammas, const int nk, const double *__restrict__ kappas, const int ns, const double *__restrict__ sigmas, const int nt, const double *__restrict__ thetas, const double *__restrict__ phi ) { const char *fcnm = "marginal_computeMarginalBeachball\0"; const double M0loc = 1.0/sqrt(2.0); double pAxis[3], nAxis[3], tAxis[3]; double *bb, *bbAvg, *bbWt, *cos3g, *db, *dg, *dk, *ds, *dt, *twoSinB4, *sint, *xw1, *yw1, dbdg, dkdsdt, dV5, geom, xscal; int ib, ig, ik, ierr, iloc, im, imt, indx, is, it, j, jmt, jndx, ldi, nmt, nmtBB; int8_t *bmap; size_t nwork; const int nxp = 51; const int nyp = nxp; const double xc = 1.5; const double yc = xc; const double rad = 1.0; nmt = nm*nb*ng*nk*ns*nt; nmtBB = nb*ng*nk*ns*nt; ldi = nxp*nyp + computePadding8i(nxp*nyp); printf("%d %d\n", ldi, nxp*nyp); nwork = (size_t)(nmtBB)*(size_t) (ldi); if (nwork > INT_MAX) { printf("%s: Insufficient space for bb\n", fcnm); return -1; } xw1 = memory_calloc64f(nxp*nyp); yw1 = memory_calloc64f(nxp*nyp); bmap = (int8_t *) calloc(nwork, sizeof(int8_t)); bbAvg = memory_calloc64f(nxp*nyp); bbWt = memory_calloc64f(nxp*nyp); bb = memory_calloc64f(nxp*nyp); printf("%s: Drawing...\n", fcnm); for (ib=0; ib<nb; ib++) { printf("%s: Drawing beta: %d\n", fcnm, ib+1); for (ig=0; ig<ng; ig++) { for (ik=0; ik<nk; ik++) { for (is=0; is<ns; is++) { for (it=0; it<nt; it++) { postprocess_tt2tnp(betas[ib], gammas[ig], kappas[ik], sigmas[is], thetas[it], pAxis, nAxis, tAxis); jmt = ib*ng*nk*ns*nt + ig*nk*ns*nt + ik*ns*nt + is*nt + it; jndx = jmt*ldi; postprocess_tnp2beachballPolarity(nxp, xc, yc, rad, pAxis, nAxis, tAxis, xw1, yw1, &bmap[jndx]); } } } } } // Differentiate weights for Riemann quadrature db = diff(nb, betas, &ierr); dg = diff(ng, gammas, &ierr); dk = diff(nk, kappas, &ierr); ds = diff(ns, sigmas, &ierr); dt = diff(nt, thetas, &ierr); // Compute the geometric factors twoSinB4 = memory_calloc64f(nb); for (ib=0; ib<nb; ib++) { twoSinB4[ib] = 2.0*pow(sin(betas[ib]), 4); } sint = memory_calloc64f(nt); for (it=0; it<nt; it++) { sint[it] = sin(thetas[it]); } cos3g = memory_calloc64f(ng); for (ig=0; ig<ng; ig++) { cos3g[ig] = cos(3.0*gammas[ig]); } printf("integrating\n"); // Stack the result for (iloc=0; iloc<nloc; iloc++) { for (im=0; im<nm; im++) { for (ib=0; ib<nb; ib++) { for (ig=0; ig<ng; ig++) { for (ik=0; ik<nk; ik++) { for (is=0; is<ns; is++) { for (it=0; it<nt; it++) { imt = im*nb*ng*nk*ns*nt + ib*ng*nk*ns*nt + ig*nk*ns*nt + ik*ns*nt + is*nt + it; indx = iloc*nmt + imt; dkdsdt = (dk[ik]*ds[is])*dt[it]; dbdg = db[ib]*dg[ig]; geom = (twoSinB4[ib]*cos3g[ig])*sint[it]; dV5 = geom*(dbdg*dkdsdt); //if (dV5 < 0.0){printf("error %f %f %f %f %f %f %f\n", dV5, dbdg, dkdsdt, geom, twoSinB4[ib], cos3g[ig], sint[it]);} xscal = (phi[indx] - 1);//*dV5; jmt = ib*ng*nk*ns*nt + ig*nk*ns*nt + ik*ns*nt + is*nt + it; jndx = jmt*ldi; for (j=0; j<nxp*nxp; j++) { bb[j] = bb[j] + xscal*(double) bmap[jndx+j]; // bbAvg[j] = bbAvg[j] + (double) bmap[jndx+j]; // bbWt[j] = bbWt[j] + (double) bmap[jndx+j]*dV5; } } } } } } } } printf("dumping result\n"); int ix, iy; FILE *fwork; fwork = fopen("depmag/beachball.txt", "w"); for (iy=0; iy<nyp; iy++) { for (ix=0; ix<nxp; ix++) { int k = iy*nxp + ix; fprintf(fwork, "%e %e %e %e %e %d\n", xw1[k], yw1[k], bb[k], bbAvg[k], bbWt[k], bmap[nmtBB/2*ldi+k]); } fprintf(fwork, "\n"); } fclose(fwork); memory_free64f(&bbAvg); memory_free64f(&bbWt); memory_free64f(&xw1); memory_free64f(&yw1); memory_free64f(&cos3g); memory_free64f(&sint); memory_free64f(&twoSinB4); memory_free64f(&db); memory_free64f(&dg); memory_free64f(&dk); memory_free64f(&ds); memory_free64f(&dt); free(bmap); return 0; } static double *diff(const int n, const double *__restrict__ x, int *ierr) { double *d; int i; d = array_set64f(n, 1.0, ierr); for (i=0; i<n; i++) { if (i < n - 1) { d[i] = x[i+1] - x[i]; } else { d[i] = x[i] - x[i-1]; } } return d; } /*! Related to beta */ /* static double g11(void) { return 1; } */ /*! Related to gamma */ /* static double g22(const double sinBeta) { return sinBeta*sinBeta; } */ /*! Related to kappa */ /* static double g33( ) { const double twoSqrt3 = 3.4641016151377544; coss2 = coss*coss; g33 = 0.5*((4.0 + (-2.0 + 3.0*(1.0 - cos2t))*coss2)*cos2g + twoSqrt3*sin2g*sins*sin2t)*sin2b; } */ /*! Related to sigma */ /* static void g44( ) { for (ib=0; ib<nb; ib++) { for (ig=0; ig<ng; ig++) { g33 = (2.0 - cos(2.0*gamma))*sinb2; for (ik=0; ik<nk; ik++) { for (is=0; is<ns; is++) { for (it=0; it<nt; it++) { } } } } } return; } */ /*! * @brief Computes the determinant of the upper 3 x 3 matrix */ /* static void computeDet123(const int nmt, const double *__restrict__ g11, const double *__restrict__ g22, const double *__restrict__ g33, double *__restrict__ det) { int i; for (i=0; i<nmt; i++) { det[i] = (g11[i]*g22[i])*g33; } return } static void computeDet124(const int nmt, const double *__restrict__ g11, const double *__restrict__ g22, const double *__restrict__ g44, double *__restrict__ det) { computeDet123(nmt, g11, g22, g44, det); return; } static void computeDet125(const int nmt, const double *__restrict__ g11, const double *__restrict__ g22, const double *__restrict__ g55, double *__restrict__ det) { computeDet123(nmt, g11, g22, g55, det); return; } */ int marginal_write1DToGnuplot(const char *fname, const int nx, const double *__restrict__ xlocs, const double *__restrict__ vals) { FILE *fout; int ix; fout = fopen(fname, "w"); for (ix=0; ix<nx; ix++) { fprintf(fout, "%.8e %.10e\n", xlocs[ix], vals[ix]); } fclose(fout); return 0; } int marginal_write2DToGnuplot(const char *fname, const int nx, const double *__restrict__ xlocs, const int ny, const double *__restrict__ ylocs, const double *__restrict__ vals) { FILE *fout; int ix, ixy, iy; fout = fopen(fname, "w"); for (iy=0; iy<ny; iy++) { for (ix=0; ix<nx; ix++) { ixy = iy*nx + ix; fprintf(fout, "%.8e %.8e %.10e\n", xlocs[ix], ylocs[iy], vals[ixy]); } fprintf(fout, "\n"); } fclose(fout); return 0; } //============================================================================// static int computePadding8i(const int n) { size_t mod, pad; int ipad; // Set space and make G matrix pad = 0; mod = ((size_t) n*sizeof(int8_t))%64; if (mod != 0) { pad = (64 - mod)/sizeof(int8_t); } ipad = (int) pad; return ipad; }
{ "alphanum_fraction": 0.4303494495, "avg_line_length": 34.2459016393, "ext": "c", "hexsha": "9a3284206019043513df507566f8ddd9722fb741", "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": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_forks_repo_licenses": [ "Intel" ], "max_forks_repo_name": "bakerb845/parmt", "max_forks_repo_path": "postprocess/marginal.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Intel" ], "max_issues_repo_name": "bakerb845/parmt", "max_issues_repo_path": "postprocess/marginal.c", "max_line_length": 117, "max_stars_count": null, "max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_stars_repo_licenses": [ "Intel" ], "max_stars_repo_name": "bakerb845/parmt", "max_stars_repo_path": "postprocess/marginal.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 8215, "size": 29246 }
/* linalg/test_common.c * * Copyright (C) 2017, 2018, 2019, 2020 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. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_rng.h> static int create_random_vector(gsl_vector * v, gsl_rng * r); static int create_random_matrix(gsl_matrix * m, gsl_rng * r); static int create_posdef_matrix(gsl_matrix * m, gsl_rng * r); static int create_hilbert_matrix2(gsl_matrix * m); static int create_random_vector(gsl_vector * v, gsl_rng * r) { const size_t N = v->size; size_t i; for (i = 0; i < N; ++i) { double vi = gsl_rng_uniform(r); gsl_vector_set(v, i, vi); } return GSL_SUCCESS; } static int create_random_complex_vector(gsl_vector_complex * v, gsl_rng * r) { const size_t N = v->size; size_t i; for (i = 0; i < N; ++i) { gsl_complex vi; GSL_REAL(vi) = gsl_rng_uniform(r); GSL_IMAG(vi) = gsl_rng_uniform(r); gsl_vector_complex_set(v, i, vi); } return GSL_SUCCESS; } static int create_random_matrix(gsl_matrix * m, gsl_rng * r) { const size_t M = m->size1; const size_t N = m->size2; size_t i, j; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { double mij = gsl_rng_uniform(r); gsl_matrix_set(m, i, j, mij); } } return GSL_SUCCESS; } static int create_random_complex_matrix(gsl_matrix_complex * m, gsl_rng * r) { const size_t M = m->size1; const size_t N = m->size2; size_t i, j; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { gsl_complex mij; GSL_REAL(mij) = gsl_rng_uniform(r); GSL_IMAG(mij) = gsl_rng_uniform(r); gsl_matrix_complex_set(m, i, j, mij); } } return GSL_SUCCESS; } static int create_symm_matrix(gsl_matrix * m, gsl_rng * r) { const size_t N = m->size1; size_t i, j; for (i = 0; i < N; ++i) { for (j = 0; j <= i; ++j) { double mij = gsl_rng_uniform(r); gsl_matrix_set(m, i, j, mij); } } /* copy lower triangle to upper */ gsl_matrix_transpose_tricpy(CblasLower, CblasUnit, m, m); return GSL_SUCCESS; } static int create_herm_matrix(gsl_matrix_complex * m, gsl_rng * r) { const size_t N = m->size1; size_t i, j; for (i = 0; i < N; ++i) { for (j = 0; j <= i; ++j) { double re = gsl_rng_uniform(r); double im = (i != j) ? gsl_rng_uniform(r) : 0.0; gsl_complex z = gsl_complex_rect(re, im); gsl_matrix_complex_set(m, i, j, z); if (i != j) gsl_matrix_complex_set(m, j, i, gsl_complex_conjugate(z)); } } return GSL_SUCCESS; } /* create symmetric banded matrix with p sub/super-diagonals */ static int create_symm_band_matrix(const size_t p, gsl_matrix * m, gsl_rng * r) { size_t i; gsl_matrix_set_zero(m); for (i = 0; i < p + 1; ++i) { gsl_vector_view subdiag = gsl_matrix_subdiagonal(m, i); create_random_vector(&subdiag.vector, r); if (i > 0) { gsl_vector_view superdiag = gsl_matrix_superdiagonal(m, i); gsl_vector_memcpy(&superdiag.vector, &subdiag.vector); } } return GSL_SUCCESS; } /* create (p,q) banded matrix */ static int create_band_matrix(const size_t p, const size_t q, gsl_matrix * m, gsl_rng * r) { size_t i; gsl_matrix_set_zero(m); for (i = 0; i <= p; ++i) { gsl_vector_view v = gsl_matrix_subdiagonal(m, i); create_random_vector(&v.vector, r); } for (i = 1; i <= q; ++i) { gsl_vector_view v = gsl_matrix_superdiagonal(m, i); create_random_vector(&v.vector, r); } return GSL_SUCCESS; } static int create_posdef_matrix(gsl_matrix * m, gsl_rng * r) { const size_t N = m->size1; const double alpha = 10.0 * N; size_t i; /* The idea is to make a symmetric diagonally dominant * matrix. Make a symmetric matrix and add alpha*I to * its diagonal */ create_symm_matrix(m, r); for (i = 0; i < N; ++i) { double mii = gsl_matrix_get(m, i, i); gsl_matrix_set(m, i, i, mii + alpha); } return GSL_SUCCESS; } static int create_posdef_complex_matrix(gsl_matrix_complex *m, gsl_rng *r) { const size_t N = m->size1; const double alpha = 10.0 * N; size_t i; create_herm_matrix(m, r); for (i = 0; i < N; ++i) { gsl_complex * mii = gsl_matrix_complex_ptr(m, i, i); GSL_REAL(*mii) += alpha; } return GSL_SUCCESS; } static int create_hilbert_matrix2(gsl_matrix * m) { const size_t N = m->size1; size_t i, j; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { gsl_matrix_set(m, i, j, 1.0/(i+j+1.0)); } } return GSL_SUCCESS; } static int create_posdef_band_matrix(const size_t p, gsl_matrix * m, gsl_rng * r) { const size_t N = m->size1; const double alpha = 10.0 * N; size_t i; /* The idea is to make a symmetric diagonally dominant * matrix. Make a symmetric matrix and add alpha*I to * its diagonal */ create_symm_band_matrix(p, m, r); for (i = 0; i < N; ++i) { double *mii = gsl_matrix_ptr(m, i, i); *mii += alpha; } return GSL_SUCCESS; } /* transform dense symmetric banded matrix to compact form, with bandwidth p */ static int symm2band_matrix(const size_t p, const gsl_matrix * m, gsl_matrix * bm) { const size_t N = m->size1; if (bm->size1 != N) { GSL_ERROR("banded matrix requires N rows", GSL_EBADLEN); } else if (bm->size2 != p + 1) { GSL_ERROR("banded matrix requires p + 1 columns", GSL_EBADLEN); } else { size_t i; gsl_matrix_set_zero(bm); for (i = 0; i < p + 1; ++i) { gsl_vector_const_view diag = gsl_matrix_const_subdiagonal(m, i); gsl_vector_view v = gsl_matrix_subcolumn(bm, i, 0, N - i); gsl_vector_memcpy(&v.vector, &diag.vector); } return GSL_SUCCESS; } } /* transform general dense (p,q) banded matrix to compact banded form */ static int gen2band_matrix(const size_t p, const size_t q, const gsl_matrix * A, gsl_matrix * AB) { const size_t N = A->size2; if (AB->size1 != N) { GSL_ERROR("banded matrix requires N rows", GSL_EBADLEN); } else if (AB->size2 != 2*p + q + 1) { GSL_ERROR("banded matrix requires 2*p + q + 1 columns", GSL_EBADLEN); } else { size_t i; gsl_matrix_set_zero(AB); /* copy diagonal and subdiagonals */ for (i = 0; i <= p; ++i) { gsl_vector_const_view v = gsl_matrix_const_subdiagonal(A, i); gsl_vector_view w = gsl_matrix_subcolumn(AB, p + q + i, 0, v.vector.size); gsl_vector_memcpy(&w.vector, &v.vector); } /* copy superdiagonals */ for (i = 1; i <= q; ++i) { gsl_vector_const_view v = gsl_matrix_const_superdiagonal(A, i); gsl_vector_view w = gsl_matrix_subcolumn(AB, p + q - i, i, v.vector.size); gsl_vector_memcpy(&w.vector, &v.vector); } return GSL_SUCCESS; } }
{ "alphanum_fraction": 0.6098552197, "avg_line_length": 22.6264367816, "ext": "c", "hexsha": "aece28edc02caa3cdaac17497425680fc6e161a9", "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/test_common.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/test_common.c", "max_line_length": 86, "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/test_common.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": 2360, "size": 7874 }
// ============================================================================= // == IMG.h // == -------------------------------------------------------------------------- // == An image class to be used with temporal superpixels. // == // == All work using this code should cite: // == J. Chang, D. Wei, and J. W. Fisher III. A Video Representation Using // == Temporal Superpixels. CVPR 2013. // == -------------------------------------------------------------------------- // == Written by Jason Chang and Donglai Wei 06-20-2013 // ============================================================================= #ifndef _IMG_H_INCLUDED_ #define _IMG_H_INCLUDED_ #include <iostream> #include <fstream> #include "utils.h" #include "SP.h" #include "NormalD.h" #include "topology.h" #include "array.h" #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #include "helperMEX.h" using namespace std; class IMG { private: int debug; int xdim; int ydim; int N; arr(double) data; arr(int) label; int K; //NIW new_pos; NormalD new_pos; NormalD new_app; arr(SP*) SP_arr; SP* SP_new; // a pointer to an exemplar "new" SP arr(bool) SP_old; // indicates the SPs that are from a prev frame arr(bool) SP_changed; // indicates which SPs changed in the previous iteration arr(linkedListNode<int>*) border_ptr; arr(linkedListNode<int>*) pixel_ptr; arr(double) T4Table; double log_alpha; // size parameter double log_beta; double area; double area_var; double log_area_var; unsigned long max_UID; double lambda; // flow parameters double lambda_sigma; arr(int) prev_label; arr(double) prev_app_mean; arr(double) prev_pos_mean; int prev_K; arr(double) prev_covariance; arr(double) prev_precision; linkedList< std::pair<int, int> > prev_neighbors; linkedList< double > prev_neighbors_scale; bool alive_dead_changed; double dummy_log_prob; arr(bool) boundary_mask; // flow stuff gsl_vector *vgsl; gsl_vector *ugsl; arr(double) Sxy; arr(double) Syy; arr(double) SxySyy; arr(double) obs_u; arr(double) obs_v; arr(double) temp_Syy; arr(double) temp_d; arr(bool) temp_still_alive; int num_alive; int num_dead; arr(int) all2alive; arr(int) alive2all; arr(int) all2dead; arr(int) dead2all; public: IMG(); virtual ~IMG(); void ReadIMG(); void mxReadIMG(const mxArray *mstruct); void mxWriteIMG(mxArray* plhs[], const mxArray* oldstruct); // -------------------------------------------------------------------------- // -- move_local // -- finds the optimal local joint move of labels and parameters. Chooses // -- a super pixel at random and loops through and updates its borders. // -------------------------------------------------------------------------- bool move_local_IMG(); bool move_switch_IMG(); // -------------------------------------------------------------------------- // -- move_merge // -- finds the optimal merge between all pairs of super pixels // -------------------------------------------------------------------------- void move_merge_IMG(); void move_split_IMG(); void move_IMG(); void Flow_QP2(); void find_SxySyy(arr(int) all2alive, arr(int) alive2all, arr(int) all2dead, arr(int) dead2all); private: // // -- 1. I/O void U_initialize(); void U_relabel_SP(bool final=false); double U_calc_energy(); double U_calc_model_order(int N, bool is_old); // -- 3. border bookkeeping bool U_check_border_pix(int index); bool U_check_border_pix(int index, int cur_label); void U_find_border_SP(int k,arr(bool) neighbors,linkedList<int> &neighborsLL); // -------------------------------------------------------------------------- // -- U_update_border_changed // -- Updates all border linked lists and pointers for the neighbors of a // -- changed pixel at index. // -- // -- parameters: // -- - index : the index of the recently changed pixel // -------------------------------------------------------------------------- void U_update_border_changed(int index); // -------------------------------------------------------------------------- // -- U_update_border_changed_pixel // -- Updates all border linked lists and pointers at index // -- // -- parameters: // -- - index : the index of the recently changed pixel // -------------------------------------------------------------------------- void U_update_border_changed_pixel(int index); // -------------------------------------------------------------------------- // -- U_update_neighbor_list // -- Updates super pixel neighbors used in merge // -- // -- parameters: // -- - neighbors : a boolean array indicating which labels are added // -- - neighborsLL : a linked list of the neighbor indices // -- - index : the index of the point to consider adding // -------------------------------------------------------------------------- void U_update_neighbor_list(arr(bool) neighbors, linkedList<int> &neighborsLL, int index); void U_fix_neighbors_self(int k); void U_fix_neighbors_neighbors(int k); void U_fix_neighbors_neighbors(int k, int kignore); void U_print_neighbors(int k); // -------------------------------------------------------------------------- // -- U_update_neighbors_rem // -- Updates all neighbor lists when a pixel is "removed". A subsequent // -- call to update_neighbors_add should be completed right after this one. // -- The neighboring label should be changed before calling this function. // -- // -- parameters: // -- - old_label : the label of the pixel before it was changed // -- - index : the index bordering the removed pixel // -------------------------------------------------------------------------- void U_update_neighbors_rem(int old_label, int index); // -------------------------------------------------------------------------- // -- U_update_neighbors_add // -- Updates all neighbor lists when a pixel is "added". A previous // -- call to update_neighbors_rem should be completed right before this one. // -- The neighboring label should be changed before calling this function. // -- // -- parameters: // -- - index : the index bordering the removed pixel // -------------------------------------------------------------------------- void U_update_neighbors_add(int index); // -------------------------------------------------------------------------- // -- U_update_neighbors_merge // -- Updates the neighbor lists for merging two super pixels. // -- All labels and SP_arr things should be updated *before* calling this. // -- // -- parameters: // -- - index : the index bordering the removed pixel // -------------------------------------------------------------------------- void U_update_neighbors_merge(int new_label, int old_label); // -------------------------------------------------------------------------- // -- U_update_neighbors_split // -- Updates the neighbor lists for merging two super pixels. // -- All labels and SP_arr things should be updated *before* calling this. // -- // -- parameters: // -- - index : the index bordering the removed pixel // -------------------------------------------------------------------------- void U_update_neighbors_split(int label1, int label2); // -- 4. Modularized Move // -- 4.0 Change of Energy // -------------------------------------------------------------------------- // -- link_cost // -- calculates the energy of linking SP_arr[ko] (old) to SP_arr[kn] (new) // -- // -- parameters: // -- - ko : the old k // -- - kn : the new k // -------------------------------------------------------------------------- double link_cost(int ko, int kn); double move_local_calc_delta_MM(int index, int new_k, double& max_prob, int& max_k); // -------------------------------------------------------------------------- // -- move_local_calc_neigbor // -- calculates the probability of assigning the pixel at index to the // -- cluster of nindex (neighbor index). Updates the max_prob and max_k if // -- the new_app value is greater than the old one // -- // -- parameters: // -- - index : the new point to add // -- - new_k : the neighbor to add this point to // -- - max_prob : the maximum probability of all neighbors // -- - max_k : the super pixel index of the maximum probability // -------------------------------------------------------------------------- double move_local_calc_delta(int index, int new_k, bool add, double& max_prob, int& max_k); double move_switch_calc_delta(SP* &oldSP, SP* &newSP); // -------------------------------------------------------------------------- // -- move_merge_calc_delta // -- calculates the probability of assigning the pixel at index to the // -- cluster of nindex (neighbor index). // -- // -- parameters: // -- - index : the new point to add // -- - nindex : the neighbor to add this point to // -------------------------------------------------------------------------- double move_merge_calc_delta(int k, int merge_k); // -------------------------------------------------------------------------- // -- move_split_calc_delta // -- calculates the change in energy for // -- (k1 U new_k1) && (k2 U new_k2) - (k1 U new_k1 U new_k) && (k2) // -- // -- parameters: // -- - SP1 : the SP that originates the splitting // -- - SP2 : the SP to split to // -- - new_SP1 : temporary SP that contains pixels that will go in k1 // -- - new_SP2 : temporary SP that contains pixels that will go in k2 // -- - SP1_old : indicates if SP1 is an old SP // -- - SP2_old : indicates if SP2 is an old SP // -------------------------------------------------------------------------- double move_split_calc_delta(SP* SP1, SP* SP2, SP* new_SP1, SP* new_SP2, bool SP1_old, bool SP2_old); // -- 4.1 move local // need to be done int move_local_SP_region(int k,linkedList<int> &check_labels); int move_local_SP(int k); // need to be done int move_local_pix(int index); //-- 4.2 move merge void move_merge_SP_propose(int k,arr(bool) neighbors,double &max_E,int &max_k); void move_merge_SP_propose_region(int k,arr(bool) neighbors, linkedList<int> &check_labels,double &max_E,int &max_k); void move_merge_SP(int k,arr(bool) neighbors); // -- 4.3 move split void move_split_SP(int k); bool U_Kmeans_plusplus(int k, int *bbox, int num_SP, int numiter, int index2=-1); void U_connect_newSP(int *bbox, int num_SP); double U_dist(int index1 , double* center); double U_dist(int index1 , int index2); void move_split_SP_propose(int index, int num_SP, int option, double &max_E,int &ksplit,int* new_ks); }; #endif
{ "alphanum_fraction": 0.5184352518, "avg_line_length": 36.9435215947, "ext": "h", "hexsha": "f41cb3dc0371d3fe107de9af2480ef23b877cbd0", "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": "bc43079a182fa736859dae24ffaa35aa06159830", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "KnockKnock13/segmentation-track", "max_forks_repo_path": "external/TSP/mex/IMG.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "bc43079a182fa736859dae24ffaa35aa06159830", "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": "KnockKnock13/segmentation-track", "max_issues_repo_path": "external/TSP/mex/IMG.h", "max_line_length": 120, "max_stars_count": 1, "max_stars_repo_head_hexsha": "bc43079a182fa736859dae24ffaa35aa06159830", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "KnockKnock13/segmentation-track", "max_stars_repo_path": "external/TSP/mex/IMG.h", "max_stars_repo_stars_event_max_datetime": "2020-01-07T04:49:16.000Z", "max_stars_repo_stars_event_min_datetime": "2020-01-07T04:49:16.000Z", "num_tokens": 2391, "size": 11120 }
/* GENETIC - A simple genetic algorithm. Copyright 2014, Javier Burguete Tolosa. 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. THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``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 Javier Burguete Tolosa 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. */ /** * \file genetic.c * \brief Source file to define genetic algorithm main function. * \author Javier Burguete Tolosa. * \copyright Copyright 2014 Javier Burguete Tolosa. All rights reserved. */ #define _GNU_SOURCE #include <stdio.h> #include <string.h> #include <math.h> #include <gsl/gsl_rng.h> #include <glib.h> #if HAVE_MPI #include <mpi.h> #endif #include "bits.h" #include "entity.h" #include "population.h" #include "reproduction.h" #include "selection.h" #include "evolution.h" #include "genetic.h" #define DEBUG_GENETIC 0 ///< Macro to debug the genetic functions. static Population genetic_population[1]; ///< Population of the genetic algorithm. static double (*genetic_simulation) (Entity *); ///< Pointer to the function to perform a simulation. /** * Function to get a variable encoded in the genome of an entity. * * \return Variable value. */ double genetic_get_variable (Entity * entity, ///< Entity struct. GeneticVariable * variable) ///< Variable data. { double x; #if DEBUG_GENETIC fprintf (stderr, "get variable: start\n"); #endif x = variable->minimum + bit_get_value (entity->genome, variable->location, variable->nbits) * (variable->maximum - variable->minimum) / ((unsigned long long int) 1L << variable->nbits); #if DEBUG_GENETIC fprintf (stderr, "get variable: value=%lg\n", x); fprintf (stderr, "get variable: end\n"); #endif return x; } /** * Funtion to apply the evolution of a population. */ static inline void genetic_evolution (Population * population, ///< Population gsl_rng * rng) ///< GSL random numbers generator. { #if DEBUG_GENETIC fprintf (stderr, "genetic_evolution: start\n"); #endif evolution_mutation (population, rng); evolution_reproduction (population, rng); evolution_adaptation (population, rng); #if DEBUG_GENETIC fprintf (stderr, "genetic_evolution: end\n"); #endif } /** * Funtion to perform the simulations on a thread. */ static void genetic_simulation_thread (GeneticThreadData * data) ///< Thread data. { unsigned int i; #if DEBUG_GENETIC fprintf (stderr, "genetic_simulation_thread: start\n"); fprintf (stderr, "genetic_simulation_thread: nmin=%u nmax=%u\n", data->nmin, data->nmax); #endif for (i = data->nmin; i < data->nmax && !genetic_population->stop; ++i) { genetic_population->objective[i] = genetic_simulation (genetic_population->entity + i); if (genetic_population->objective[i] < genetic_population->threshold) { g_mutex_lock (mutex); genetic_population->stop = 1; g_mutex_unlock (mutex); break; } } #if DEBUG_GENETIC fprintf (stderr, "genetic_simulation_thread: end\n"); #endif } /** * Function to perform the simulations on a task. */ static void genetic_simulation_master (unsigned int nsurvival) ///< Number of survival entities already simulated. { unsigned int j, nsimulate, nmin, nmax; GThread *thread[nthreads]; GeneticThreadData thread_data[nthreads]; Population *population; #if HAVE_MPI unsigned int i; unsigned int n[ntasks + 1]; unsigned int stop[ntasks]; char *genome_array; MPI_Status mpi_status; #endif #if DEBUG_GENETIC fprintf (stderr, "genetic_simulation_master: start\n"); #endif population = genetic_population; nmax = population->nentities; nsimulate = nmax - nsurvival; nmin = nsurvival; #if DEBUG_GENETIC fprintf (stderr, "genetic_simulation_master: nmax=%u nmin=%u nsimulate=%u\n", nmax, nmin, nsimulate); #endif #if HAVE_MPI nmax = nmin + nsimulate / ntasks; // Send genome information to the slaves #if DEBUG_GENETIC fprintf (stderr, "genetic_simulation_master: nmax=%u nmin=%u nsimulate=%u\n", nmax, nmin, nsimulate); #endif genome_array = (char *) g_malloc (nsimulate * population->genome_nbytes); for (j = 0; j < nsimulate; ++j) memcpy (genome_array + j * population->genome_nbytes, population->entity[nmin + j].genome, population->genome_nbytes); n[0] = 0; for (i = 0; (int) ++i < ntasks;) { n[i] = i * nsimulate / ntasks; j = (i + 1) * nsimulate / ntasks - n[i]; #if DEBUG_GENETIC fprintf (stderr, "genetic_simulation_master: send %u bytes on %u to task %u\n", j * population->genome_nbytes, nsurvival + n[i], i); #endif MPI_Send (genome_array + n[i] * population->genome_nbytes, j * population->genome_nbytes, MPI_CHAR, i, 1, MPI_COMM_WORLD); } n[i] = nsimulate; #if DEBUG_GENETIC for (j = 0; j <= ntasks; ++j) fprintf (stderr, "genetic_simulation_master: n[%u]=%u\n", j, n[j]); #endif g_free (genome_array); nsimulate = nmax - nmin; #endif #if DEBUG_GENETIC fprintf (stderr, "genetic_simulation_master: nsimulate=%u\n", nsimulate); fprintf (stderr, "genetic_simulation_master: performing simulations\n"); #endif thread_data[0].nmin = nmin; for (j = 0; ++j < nthreads;) thread_data[j - 1].nmax = thread_data[j].nmin = nmin + j * nsimulate / nthreads; thread_data[j - 1].nmax = nmax; for (j = 0; j < nthreads; ++j) thread[j] = g_thread_new (NULL, (GThreadFunc) (void (*)(void)) genetic_simulation_thread, thread_data + j); for (j = 0; j < nthreads; ++j) g_thread_join (thread[j]); #if HAVE_MPI // Receive objective function resuts from the slaves for (j = 0; (int) ++j < ntasks;) { #if DEBUG_GENETIC fprintf (stderr, "genetic_simulation_master: " "receive %u reals from task %u on %u\n", n[j + 1] - n[j], j, nsurvival + n[j]); #endif MPI_Recv (population->objective + nsurvival + n[j], n[j + 1] - n[j], MPI_DOUBLE, j, 1, MPI_COMM_WORLD, &mpi_status); #if DEBUG_GENETIC fprintf (stderr, "genetic_simulation_master: receive one integer from task %u\n", j); #endif MPI_Recv (stop + j, j, MPI_UNSIGNED, j, 1, MPI_COMM_WORLD, &mpi_status); if (stop[j]) genetic_population->stop = 1; } // Sending stop instruction to the slaves for (j = 0; (int) ++j < ntasks;) { #if DEBUG_GENETIC fprintf (stderr, "genetic_simulation_master: sending one integer to task %u\n", j); #endif MPI_Send (&genetic_population->stop, 1, MPI_UNSIGNED, j, 1, MPI_COMM_WORLD); } #endif #if DEBUG_GENETIC fprintf (stderr, "genetic_simulation_master: end\n"); #endif } #if HAVE_MPI /** * Function to perform the simulations on a task. */ static void genetic_simulation_slave (unsigned int nsurvival, ///< Number of survival entities already simulated. int rank) ///< Number of task. { unsigned int j, nsimulate, nmin, nmax, stop; GThread *thread[nthreads]; GeneticThreadData thread_data[nthreads]; Population *population; char *genome_array; MPI_Status mpi_status; #if DEBUG_GENETIC fprintf (stderr, "genetic_simulation_slave: rank=%d start\n", rank); #endif population = genetic_population; nmax = population->nentities; nsimulate = nmax - nsurvival; nmin = nsurvival; nmax = nmin + (rank + 1) * nsimulate / ntasks; nmin += rank * nsimulate / ntasks; // Receive genome information from the master nsimulate = nmax - nmin; genome_array = (char *) g_malloc (nsimulate * population->genome_nbytes); #if DEBUG_GENETIC fprintf (stderr, "genetic_simulation_slave: rank=%d receive %u bytes from master\n", rank, nsimulate * population->genome_nbytes); #endif MPI_Recv (genome_array, nsimulate * population->genome_nbytes, MPI_CHAR, 0, 1, MPI_COMM_WORLD, &mpi_status); #if DEBUG_GENETIC fprintf (stderr, "genetic_simulation_slave: rank=%d nmin=%u nsimulate=%u\n", rank, nmin, nsimulate); #endif for (j = 0; j < nsimulate; ++j) memcpy (population->entity[nmin + j].genome, genome_array + j * population->genome_nbytes, population->genome_nbytes); #if DEBUG_GENETIC fprintf (stderr, "genetic_simulation_slave: rank=%d freeing\n", rank); #endif g_free (genome_array); #if DEBUG_GENETIC fprintf (stderr, "genetic_simulation_slave: rank=%d performing simulations\n", rank); #endif thread_data[0].nmin = nmin; for (j = 0; ++j < nthreads;) thread_data[j - 1].nmax = thread_data[j].nmin = nmin + j * nsimulate / nthreads; thread_data[j - 1].nmax = nmax; for (j = 0; j < nthreads; ++j) thread[j] = g_thread_new (NULL, (GThreadFunc) (void (*)(void)) genetic_simulation_thread, thread_data + j); for (j = 0; j < nthreads; ++j) g_thread_join (thread[j]); #if DEBUG_GENETIC fprintf (stderr, "genetic_simulation_slave: rank=%d send %u reals on %u to master\n", rank, nsimulate, nmin); #endif // Send the objective function resuts to the master MPI_Send (population->objective + nmin, nsimulate, MPI_DOUBLE, 0, 1, MPI_COMM_WORLD); #if DEBUG_GENETIC fprintf (stderr, "genetic_simulation_slave: rank=%d send one integer to master\n", rank); #endif // Send the stop variable from the master MPI_Send (&genetic_population->stop, 1, MPI_UNSIGNED, 0, 1, MPI_COMM_WORLD); #if DEBUG_GENETIC fprintf (stderr, "genetic_simulation_slave: " "rank=%d receive one integer from master\n", rank); #endif // Receive the stop variable from the master MPI_Recv (&stop, 1, MPI_UNSIGNED, 0, 1, MPI_COMM_WORLD, &mpi_status); if (stop) genetic_population->stop = 1; #if DEBUG_GENETIC fprintf (stderr, "genetic_simulation_slave: rank=%d end\n", rank); #endif } #endif /** * Function to create the data of the genetic algorithm. * * \return 1 on succes, 0 on error. */ int genetic_new (unsigned int nvariables, ///< Number of variables. GeneticVariable * variable, ///< Array of variables data. unsigned int nentities, ///< Number of entities in each generation. double mutation_ratio, ///< Mutation ratio. double reproduction_ratio, ///< Reproduction ratio. double adaptation_ratio, ///< Adaptation ratio. double threshold) ///< Threshold to finish the simulations. { unsigned int i, genome_nbits, nprocesses; #if DEBUG_GENETIC fprintf (stderr, "genetic_new: start\n"); #endif // Checking variables number if (!nvariables) { fprintf (stderr, "ERROR: no variables\n"); return 0; } // Checking variable bits number for (i = genome_nbits = 0; i < nvariables; ++i) { if (!variable[i].nbits || variable[i].nbits > 32) { fprintf (stderr, "ERROR: bad bits number in variable %u\n", i + 1); return 0; } variable[i].location = genome_nbits; genome_nbits += variable[i].nbits; } // Checking processes number nprocesses = ntasks * nthreads; if (!nprocesses) { fprintf (stderr, "ERROR: no processes\n"); return 0; } // Init the population #if DEBUG_GENETIC fprintf (stderr, "genetic_new: init the population\n"); #endif if (!population_new (genetic_population, variable, nvariables, genome_nbits, nentities, mutation_ratio, reproduction_ratio, adaptation_ratio, threshold)) return 0; #if DEBUG_GENETIC fprintf (stderr, "genetic_new: end\n"); #endif return 1; } /** * Function to perform the genetic algorithm. * * \return 1 on succes, 0 on error. */ int genetic_algorithm (unsigned int nvariables, ///< Number of variables. GeneticVariable * variable, ///< Array of variables data. unsigned int nentities, ///< Number of entities in each generation. unsigned int ngenerations, ///< Number of generations. double mutation_ratio, ///< Mutation ratio. double reproduction_ratio, ///< Reproduction ratio. double adaptation_ratio, ///< Adaptation ratio. const gsl_rng_type * type_random, ///< Type of GSL random numbers generator algorithm. unsigned long random_seed, ///< Seed of the GSL random numbers generator. unsigned int type_reproduction, ///< Type of reproduction algorithm. unsigned int type_selection_mutation, ///< Type of mutation selection algorithm. unsigned int type_selection_reproduction, ///< Type of reproduction selection algorithm. unsigned int type_selection_adaptation, ///< Type of adaptation selection algorithm. double threshold, ///< Threshold to finish the simulations. double (*simulate_entity) (Entity *), ///< Pointer to the function to perform a simulation of an entity. char **best_genome, ///< Best genome. double **best_variables, ///< Best array of variables. double *best_objective) ///< Best objective function value. { unsigned int i; double *bv; gsl_rng *rng; Entity *best_entity; #if HAVE_MPI int rank; #endif #if DEBUG_GENETIC fprintf (stderr, "genetic_algorithm: start\n"); #endif // Init the data if (!genetic_new (nvariables, variable, nentities, mutation_ratio, reproduction_ratio, adaptation_ratio, threshold)) return 0; // Init the evaluation function genetic_simulation = simulate_entity; // Get the rank #if HAVE_MPI MPI_Comm_rank (MPI_COMM_WORLD, &rank); #endif // Variables to init only by master task #if HAVE_MPI if (rank == 0) { #endif // Init the GSL random numbers generator rng = gsl_rng_alloc (type_random); if (random_seed) gsl_rng_set (rng, random_seed); // Init genomes population_init_genomes (genetic_population, rng); // Init selection, mutation and reproduction algorithms reproduction_init (type_reproduction); selection_init (type_selection_mutation, type_selection_reproduction, type_selection_adaptation); #if HAVE_MPI } if (rank == 0) { #endif // First simulation of all entities #if DEBUG_GENETIC fprintf (stderr, "genetic_algorithm: first simulation of all entities\n"); #endif genetic_simulation_master (0); // Sorting by objective function results #if DEBUG_GENETIC fprintf (stderr, "genetic_algorithm: sorting by objective function results\n"); #endif evolution_sort (genetic_population); // Population generations #if DEBUG_GENETIC fprintf (stderr, "genetic_algorithm: ngenerations=%u\n", ngenerations); #endif for (i = 1; i < ngenerations && !genetic_population->stop; ++i) { // Evolution #if DEBUG_GENETIC fprintf (stderr, "genetic_algorithm: evolution of the population\n"); #endif genetic_evolution (genetic_population, rng); // Simulation of the new entities #if DEBUG_GENETIC fprintf (stderr, "genetic_algorithm: simulation of the new entities\n"); #endif genetic_simulation_master (genetic_population->nsurvival); // Sorting by objective function results #if DEBUG_GENETIC fprintf (stderr, "genetic_algorithm: sorting by objective function results\n"); #endif evolution_sort (genetic_population); } // Saving the best #if DEBUG_GENETIC fprintf (stderr, "genetic_algorithm: saving the best\n"); #endif best_entity = genetic_population->entity; *best_objective = genetic_population->objective[0]; *best_genome = (char *) g_malloc (genetic_population->genome_nbytes); memcpy (*best_genome, best_entity->genome, genetic_population->genome_nbytes); *best_variables = bv = (double *) g_malloc (nvariables * sizeof (double)); for (i = 0; i < nvariables; ++i) bv[i] = genetic_get_variable (best_entity, variable + i); gsl_rng_free (rng); #if HAVE_MPI } else { // First simulation of all entities #if DEBUG_GENETIC fprintf (stderr, "genetic_algorithm: first simulation of all entities\n"); #endif genetic_simulation_slave (0, rank); // Population generations for (i = 1; i < ngenerations && !genetic_population->stop; ++i) { // Simulation of the new entities #if DEBUG_GENETIC fprintf (stderr, "genetic_algorithm: simulation of the new entities\n"); #endif genetic_simulation_slave (genetic_population->nsurvival, rank); } } #endif // Freeing memory #if DEBUG_GENETIC fprintf (stderr, "genetic_algorithm: freeing memory\n"); #endif population_free (genetic_population); #if DEBUG_GENETIC fprintf (stderr, "genetic_algorithm: rank=%d\n", rank); fprintf (stderr, "genetic_algorithm: end\n"); #endif return 1; } /** * Function to perform the genetic algorithm with default random and evolution * algorithms. * * \return 1 on succes, 0 on error. */ int genetic_algorithm_default (unsigned int nvariables, ///< Number of variables. GeneticVariable * variable, ///< Array of variables data. unsigned int nentities, ///< Number of entities in each generation. unsigned int ngenerations, ///< Number of generations. double mutation_ratio, ///< Mutation ratio. double reproduction_ratio, ///< Reproduction ratio. double adaptation_ratio, ///< Adaptation ratio. unsigned long random_seed, ///< Seed of the GSL random numbers generator. double threshold, ///< Threshold to finish the simulations. double (*simulate_entity) (Entity *), ///< Pointer to the function to perform a simulation of an entity. char **best_genome, ///< Best genome. double **best_variables, ///< Best array of variables. double *best_objective) ///< Best objective function value. { return genetic_algorithm (nvariables, variable, nentities, ngenerations, mutation_ratio, reproduction_ratio, adaptation_ratio, gsl_rng_mt19937, random_seed, 0, 0, 0, 0, threshold, simulate_entity, best_genome, best_variables, best_objective); }
{ "alphanum_fraction": 0.627388535, "avg_line_length": 32.3307332293, "ext": "c", "hexsha": "0b193490a0673f0e0b6c0440f509d17636bdc7d2", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2017-05-22T08:54:08.000Z", "max_forks_repo_forks_event_min_datetime": "2017-05-22T08:54:08.000Z", "max_forks_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "jburguete/genetic", "max_forks_repo_path": "3.0.0/genetic.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "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": "jburguete/genetic", "max_issues_repo_path": "3.0.0/genetic.c", "max_line_length": 81, "max_stars_count": 3, "max_stars_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "jburguete/genetic", "max_stars_repo_path": "3.0.0/genetic.c", "max_stars_repo_stars_event_max_datetime": "2017-05-02T02:31:16.000Z", "max_stars_repo_stars_event_min_datetime": "2016-04-07T07:31:25.000Z", "num_tokens": 4851, "size": 20724 }
#include <math.h> #include <unistd.h> #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <time.h> #include <string.h> //#include <pthread.h> #include <omp.h> #include <complex.h> #include <fftw3.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_errno.h> #include "21CMMC.h" void ComputeInitialConditions(struct UserParams user_params, struct CosmoParams cosmo_params, struct InitialConditions boxes) { /* Generates the initial conditions: gaussian random density field (DIM^3) as well as the equal or lower resolution velocity fields, and smoothed density field (HII_DIM^3). See INIT_PARAMS.H and ANAL_PARAMS.H to set the appropriate parameters. Output is written to ../Boxes Author: Andrei Mesinger Date: 9/29/06 */ fftwf_plan plan; unsigned long long ct; int n_x, n_y, n_z, i, j, k, ii; float k_x, k_y, k_z, k_mag, p, a, b, k_sq; double pixel_deltax; float f_pixel_factor; gsl_rng * r; /************ INITIALIZATION **********************/ // Removed all references to threads as 21CMMC is always a single core implementation printf("%d\n",cosmo_params.RANDOM_SEED); // seed the random number generators // r = gsl_rng_alloc(gsl_rng_mt19937); // gsl_rng_set(r, cosmo_params.RANDOM_SEED); /* // allocate array for the k-space and real-space boxes HIRES_box = (fftwf_complex *) fftwf_malloc(sizeof(fftwf_complex)*user_params.KSPACE_NUM_PIXELS); HIRES_box_saved = (fftwf_complex *) fftwf_malloc(sizeof(fftwf_complex)*user_params.KSPACE_NUM_PIXELS); // now allocate memory for the lower-resolution box // use HII_DIM from ANAL_PARAMS LOWRES_density = (float *) malloc(sizeof(float)*HII_TOT_NUM_PIXELS); LOWRES_vx = (float *) malloc(sizeof(float)*HII_TOT_NUM_PIXELS); LOWRES_vy= (float *) malloc(sizeof(float)*HII_TOT_NUM_PIXELS); LOWRES_vz = (float *) malloc(sizeof(float)*HII_TOT_NUM_PIXELS); if(SECOND_ORDER_LPT_CORRECTIONS){ LOWRES_vx_2LPT = (float *) malloc(sizeof(float)*HII_TOT_NUM_PIXELS); LOWRES_vy_2LPT = (float *) malloc(sizeof(float)*HII_TOT_NUM_PIXELS); LOWRES_vz_2LPT = (float *) malloc(sizeof(float)*HII_TOT_NUM_PIXELS); } // find factor of HII pixel size / deltax pixel size f_pixel_factor = DIM/(float)HII_DIM; */ /************ END INITIALIZATION ******************/ /************ CREATE K-SPACE GAUSSIAN RANDOM FIELD ***********/ /* for (n_x=0; n_x<DIM; n_x++){ // convert index to numerical value for this component of the k-mode: k = (2*pi/L) * n if (n_x>MIDDLE) k_x =(n_x-DIM) * DELTA_K; // wrap around for FFT convention else k_x = n_x * DELTA_K; for (n_y=0; n_y<DIM; n_y++){ // convert index to numerical value for this component of the k-mode: k = (2*pi/L) * n if (n_y>MIDDLE) k_y =(n_y-DIM) * DELTA_K; else k_y = n_y * DELTA_K; // since physical space field is real, only half contains independent modes for (n_z=0; n_z<=MIDDLE; n_z++){ // convert index to numerical value for this component of the k-mode: k = (2*pi/L) * n k_z = n_z * DELTA_K; // now get the power spectrum; remember, only the magnitude of k counts (due to issotropy) // this could be used to speed-up later maybe k_mag = sqrt(k_x*k_x + k_y*k_y + k_z*k_z); p = power_in_k(k_mag); // ok, now we can draw the values of the real and imaginary part // of our k entry from a Gaussian distribution a = gsl_ran_ugaussian(r); b = gsl_ran_ugaussian(r); HIRES_box[C_INDEX(n_x, n_y, n_z)] = sqrt(VOLUME*p/2.0) * (a + b*I); } } } */ /***** Adjust the complex conjugate relations for a real array *****/ // adj_complex_conj(HIRES_box); /*** Let's also create a lower-resolution version of the density field ***/ /* memcpy(HIRES_box_saved, HIRES_box, sizeof(fftwf_complex)*KSPACE_NUM_PIXELS); if (DIM != HII_DIM) filter(HIRES_box, 0, L_FACTOR*BOX_LEN/(HII_DIM+0.0)); // FFT back to real space plan = fftwf_plan_dft_c2r_3d(DIM, DIM, DIM, (fftwf_complex *)HIRES_box, (float *)HIRES_box, FFTW_ESTIMATE); fftwf_execute(plan); // now sample the filtered box for (i=0; i<HII_DIM; i++){ for (j=0; j<HII_DIM; j++){ for (k=0; k<HII_DIM; k++){ LOWRES_density[HII_R_INDEX(i,j,k)] = *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i*f_pixel_factor+0.5), (unsigned long long)(j*f_pixel_factor+0.5), (unsigned long long)(k*f_pixel_factor+0.5)))/VOLUME; } } } */ /******* PERFORM INVERSE FOURIER TRANSFORM *****************/ // add the 1/VOLUME factor when converting from k space to real space /* memcpy(HIRES_box, HIRES_box_saved, sizeof(fftwf_complex)*KSPACE_NUM_PIXELS); for (ct=0; ct<KSPACE_NUM_PIXELS; ct++){ HIRES_box[ct] /= VOLUME; } plan = fftwf_plan_dft_c2r_3d(DIM, DIM, DIM, (fftwf_complex *)HIRES_box, (float *)HIRES_box, FFTW_ESTIMATE); fftwf_execute(plan); fftwf_destroy_plan(plan); fftwf_cleanup(); for (i=0; i<DIM; i++){ for (j=0; j<DIM; j++){ for (k=0; k<DIM; k++){ *((float *)HIRES_density + R_FFT_INDEX(i,j,k)) = *((float *)HIRES_box + R_FFT_INDEX(i,j,k)); } } } for(ii=0;ii<3;ii++) { memcpy(HIRES_box, HIRES_box_saved, sizeof(fftwf_complex)*KSPACE_NUM_PIXELS); // Now let's set the velocity field/dD/dt (in comoving Mpc) for (n_x=0; n_x<DIM; n_x++){ if (n_x>MIDDLE) k_x =(n_x-DIM) * DELTA_K; // wrap around for FFT convention else k_x = n_x * DELTA_K; for (n_y=0; n_y<DIM; n_y++){ if (n_y>MIDDLE) k_y =(n_y-DIM) * DELTA_K; else k_y = n_y * DELTA_K; for (n_z=0; n_z<=MIDDLE; n_z++){ k_z = n_z * DELTA_K; k_sq = k_x*k_x + k_y*k_y + k_z*k_z; // now set the velocities if ((n_x==0) && (n_y==0) && (n_z==0)){ // DC mode HIRES_box[0] = 0; } else{ if(ii==0) { HIRES_box[C_INDEX(n_x,n_y,n_z)] *= k_x*I/k_sq/VOLUME; } if(ii==1) { HIRES_box[C_INDEX(n_x,n_y,n_z)] *= k_y*I/k_sq/VOLUME; } if(ii==2) { HIRES_box[C_INDEX(n_x,n_y,n_z)] *= k_z*I/k_sq/VOLUME; } // note the last factor of 1/VOLUME accounts for the scaling in real-space, following the FFT } } } } if (DIM != HII_DIM) filter(HIRES_box, 0, L_FACTOR*BOX_LEN/(HII_DIM+0.0)); plan = fftwf_plan_dft_c2r_3d(DIM, DIM, DIM, (fftwf_complex *)HIRES_box, (float *)HIRES_box, FFTW_ESTIMATE); fftwf_execute(plan); // now sample to lower res // now sample the filtered box for (i=0; i<HII_DIM; i++){ for (j=0; j<HII_DIM; j++){ for (k=0; k<HII_DIM; k++){ if(ii==0) { LOWRES_vx[HII_R_INDEX(i,j,k)] = *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i*f_pixel_factor+0.5), (unsigned long long)(j*f_pixel_factor+0.5), (unsigned long long)(k*f_pixel_factor+0.5))); } if(ii==1) { LOWRES_vy[HII_R_INDEX(i,j,k)] = *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i*f_pixel_factor+0.5), (unsigned long long)(j*f_pixel_factor+0.5), (unsigned long long)(k*f_pixel_factor+0.5))); } if(ii==2) { LOWRES_vz[HII_R_INDEX(i,j,k)] = *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i*f_pixel_factor+0.5), (unsigned long long)(j*f_pixel_factor+0.5), (unsigned long long)(k*f_pixel_factor+0.5))); } } } } } // write out file */ /* *************************************************** * * BEGIN 2LPT PART * * *************************************************** */ // Generation of the second order Lagrangian perturbation theory (2LPT) corrections to the ZA // reference: Scoccimarro R., 1998, MNRAS, 299, 1097-1118 Appendix D /* // Parameter set in ANAL_PARAMS.H if(SECOND_ORDER_LPT_CORRECTIONS){ // use six supplementary boxes to store the gradients of phi_1 (eq. D13b) // Allocating the boxes #define PHI_INDEX(i, j) ((int) ((i) - (j)) + 3*((j)) - ((int)(j))/2 ) // ij -> INDEX // 00 -> 0 // 11 -> 3 // 22 -> 5 // 10 -> 1 // 20 -> 2 // 21 -> 4 fftwf_complex *phi_1[6]; for(i = 0; i < 3; ++i){ for(j = 0; j <= i; ++j){ phi_1[PHI_INDEX(i, j)] = (fftwf_complex *) fftwf_malloc(sizeof(fftwf_complex)*KSPACE_NUM_PIXELS); } } for(i = 0; i < 3; ++i){ for(j = 0; j <= i; ++j){ // read in the box memcpy(HIRES_box, HIRES_box_saved, sizeof(fftwf_complex)*KSPACE_NUM_PIXELS); // generate the phi_1 boxes in Fourier transform for (n_x=0; n_x<DIM; n_x++){ if (n_x>MIDDLE) k_x =(n_x-DIM) * DELTA_K; // wrap around for FFT convention else k_x = n_x * DELTA_K; for (n_y=0; n_y<DIM; n_y++){ if (n_y>MIDDLE) k_y =(n_y-DIM) * DELTA_K; else k_y = n_y * DELTA_K; for (n_z=0; n_z<=MIDDLE; n_z++){ k_z = n_z * DELTA_K; k_sq = k_x*k_x + k_y*k_y + k_z*k_z; float k[] = {k_x, k_y, k_z}; // now set the velocities if ((n_x==0) && (n_y==0) && (n_z==0)){ // DC mode phi_1[PHI_INDEX(i, j)][0] = 0; } else{ phi_1[PHI_INDEX(i, j)][C_INDEX(n_x,n_y,n_z)] = -k[i]*k[j]*HIRES_box[C_INDEX(n_x, n_y, n_z)]/k_sq/VOLUME; // note the last factor of 1/VOLUME accounts for the scaling in real-space, following the FFT } } } } // Now we can generate the real phi_1[i,j] plan = fftwf_plan_dft_c2r_3d(DIM, DIM, DIM, (fftwf_complex *)phi_1[PHI_INDEX(i, j)], (float *)phi_1[PHI_INDEX(i, j)], FFTW_ESTIMATE); fftwf_execute(plan); } } // Then we will have the laplacian of phi_2 (eq. D13b) // After that we have to return in Fourier space and generate the Fourier transform of phi_2 int m, l; for (i=0; i<DIM; i++){ for (j=0; j<DIM; j++){ for (k=0; k<DIM; k++){ *( (float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i), (unsigned long long)(j), (unsigned long long)(k) )) = 0.0; for(m = 0; m < 3; ++m){ for(l = m+1; l < 3; ++l){ *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i),(unsigned long long)(j),(unsigned long long)(k)) ) += ( *((float *)(phi_1[PHI_INDEX(l, l)]) + R_FFT_INDEX((unsigned long long) (i),(unsigned long long) (j),(unsigned long long) (k))) ) * ( *((float *)(phi_1[PHI_INDEX(m, m)]) + R_FFT_INDEX((unsigned long long)(i),(unsigned long long)(j),(unsigned long long)(k))) ); *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i),(unsigned long long)(j),(unsigned long long)(k)) ) -= ( *((float *)(phi_1[PHI_INDEX(l, m)]) + R_FFT_INDEX((unsigned long long)(i),(unsigned long long) (j),(unsigned long long)(k) ) ) ) * ( *((float *)(phi_1[PHI_INDEX(l, m)]) + R_FFT_INDEX((unsigned long long)(i),(unsigned long long)(j),(unsigned long long)(k) )) ); *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i),(unsigned long long)(j),(unsigned long long)(k)) ) /= TOT_NUM_PIXELS; } } } } } plan = fftwf_plan_dft_r2c_3d(DIM, DIM, DIM, (float *)HIRES_box, (fftwf_complex *)HIRES_box, FFTW_ESTIMATE); fftwf_execute(plan); memcpy(HIRES_box_saved, HIRES_box, sizeof(fftwf_complex)*KSPACE_NUM_PIXELS); // Now we can store the content of box in a back-up file // Then we can generate the gradients of phi_2 (eq. D13b and D9) */ /***** Write out back-up k-box RHS eq. D13b *****/ /* // For each component, we generate the velocity field (same as the ZA part) // Now let's set the velocity field/dD/dt (in comoving Mpc) // read in the box // TODO correct free of phi_1 for(ii=0;ii<3;ii++) { if(ii>0) { memcpy(HIRES_box, HIRES_box_saved, sizeof(fftwf_complex)*KSPACE_NUM_PIXELS); } // set velocities/dD/dt for (n_x=0; n_x<DIM; n_x++){ if (n_x>MIDDLE) k_x =(n_x-DIM) * DELTA_K; // wrap around for FFT convention else k_x = n_x * DELTA_K; for (n_y=0; n_y<DIM; n_y++){ if (n_y>MIDDLE) k_y =(n_y-DIM) * DELTA_K; else k_y = n_y * DELTA_K; for (n_z=0; n_z<=MIDDLE; n_z++){ k_z = n_z * DELTA_K; k_sq = k_x*k_x + k_y*k_y + k_z*k_z; // now set the velocities if ((n_x==0) && (n_y==0) && (n_z==0)){ // DC mode HIRES_box[0] = 0; } else{ if(ii==0) { HIRES_box[C_INDEX(n_x,n_y,n_z)] *= k_x*I/k_sq; } if(ii==1) { HIRES_box[C_INDEX(n_x,n_y,n_z)] *= k_y*I/k_sq; } if(ii==2) { HIRES_box[C_INDEX(n_x,n_y,n_z)] *= k_z*I/k_sq; } // note the last factor of 1/VOLUME accounts for the scaling in real-space, following the FFT } } } } if (DIM != HII_DIM) filter(HIRES_box, 0, L_FACTOR*BOX_LEN/(HII_DIM+0.0)); plan = fftwf_plan_dft_c2r_3d(DIM, DIM, DIM, (fftwf_complex *)HIRES_box, (float *)HIRES_box, FFTW_ESTIMATE); fftwf_execute(plan); // now sample to lower res // now sample the filtered box for (i=0; i<HII_DIM; i++){ for (j=0; j<HII_DIM; j++){ for (k=0; k<HII_DIM; k++){ if(ii==0) { LOWRES_vx_2LPT[HII_R_INDEX(i,j,k)] = *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i*f_pixel_factor+0.5), (unsigned long long)(j*f_pixel_factor+0.5), (unsigned long long)(k*f_pixel_factor+0.5))); } if(ii==1) { LOWRES_vy_2LPT[HII_R_INDEX(i,j,k)] = *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i*f_pixel_factor+0.5), (unsigned long long)(j*f_pixel_factor+0.5), (unsigned long long)(k*f_pixel_factor+0.5))); } if(ii==2) { LOWRES_vz_2LPT[HII_R_INDEX(i,j,k)] = *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i*f_pixel_factor+0.5), (unsigned long long)(j*f_pixel_factor+0.5), (unsigned long long)(k*f_pixel_factor+0.5))); } } } } } // deallocate the supplementary boxes for(i = 0; i < 3; ++i){ for(j = 0; j <= i; ++j){ fftwf_free(phi_1[PHI_INDEX(i,j)]); } } } */ /* *********************************************** * * END 2LPT PART * * *********************************************** */ // deallocate // fftwf_free(HIRES_box); // fftwf_free(HIRES_box_saved); } /***** Adjust the complex conjugate relations for a real array *****/ /* void adj_complex_conj(){ int i, j, k; // corners HIRES_box[C_INDEX(0,0,0)] = 0; HIRES_box[C_INDEX(0,0,MIDDLE)] = crealf(HIRES_box[C_INDEX(0,0,MIDDLE)]); HIRES_box[C_INDEX(0,MIDDLE,0)] = crealf(HIRES_box[C_INDEX(0,MIDDLE,0)]); HIRES_box[C_INDEX(0,MIDDLE,MIDDLE)] = crealf(HIRES_box[C_INDEX(0,MIDDLE,MIDDLE)]); HIRES_box[C_INDEX(MIDDLE,0,0)] = crealf(HIRES_box[C_INDEX(MIDDLE,0,0)]); HIRES_box[C_INDEX(MIDDLE,0,MIDDLE)] = crealf(HIRES_box[C_INDEX(MIDDLE,0,MIDDLE)]); HIRES_box[C_INDEX(MIDDLE,MIDDLE,0)] = crealf(HIRES_box[C_INDEX(MIDDLE,MIDDLE,0)]); HIRES_box[C_INDEX(MIDDLE,MIDDLE,MIDDLE)] = crealf(HIRES_box[C_INDEX(MIDDLE,MIDDLE,MIDDLE)]); // do entire i except corners for (i=1; i<MIDDLE; i++){ // just j corners for (j=0; j<=MIDDLE; j+=MIDDLE){ for (k=0; k<=MIDDLE; k+=MIDDLE){ HIRES_box[C_INDEX(i,j,k)] = conjf(HIRES_box[C_INDEX(DIM-i,j,k)]); } } // all of j for (j=1; j<MIDDLE; j++){ for (k=0; k<=MIDDLE; k+=MIDDLE){ HIRES_box[C_INDEX(i,j,k)] = conjf(HIRES_box[C_INDEX(DIM-i,DIM-j,k)]); HIRES_box[C_INDEX(i,DIM-j,k)] = conjf(HIRES_box[C_INDEX(DIM-i,j,k)]); } } } // end loop over i // now the i corners for (i=0; i<=MIDDLE; i+=MIDDLE){ for (j=1; j<MIDDLE; j++){ for (k=0; k<=MIDDLE; k+=MIDDLE){ HIRES_box[C_INDEX(i,j,k)] = conjf(HIRES_box[C_INDEX(i,DIM-j,k)]); } } } // end loop over remaining j } */
{ "alphanum_fraction": 0.4653087206, "avg_line_length": 42.8155136268, "ext": "c", "hexsha": "bf9219a2f7df8858e17ec7bf48510ea43fbc1338", "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": "984aa88ee4543db24095a3ba8529e1f4d0b1048d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "BradGreig/Hybrid21CMMC", "max_forks_repo_path": "src/py21cmmc/_21cmfast/src/GenerateICs.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "984aa88ee4543db24095a3ba8529e1f4d0b1048d", "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": "BradGreig/Hybrid21CMMC", "max_issues_repo_path": "src/py21cmmc/_21cmfast/src/GenerateICs.c", "max_line_length": 406, "max_stars_count": null, "max_stars_repo_head_hexsha": "984aa88ee4543db24095a3ba8529e1f4d0b1048d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "BradGreig/Hybrid21CMMC", "max_stars_repo_path": "src/py21cmmc/_21cmfast/src/GenerateICs.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5264, "size": 20423 }
// Copyright Jean Pierre Cimalando 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at // http://www.boost.org/LICENSE_1_0.txt) #pragma once #include "configuration.h" #include "utility/geometry.h" #include "utility/SDL++.h" #include <SDL.h> #include <gsl/gsl> #include <mutex> #include <vector> #include <memory> class File_Browser; class File_Entry; class Metadata_Display; class Level_Meter; class Modal_Box; class Player; struct Player_State; class Main_Layout; struct Midi_Output; class Application { public: static const Point size_; Application(); ~Application(); SDL_Window *init_window(); SDL_Renderer *init_renderer(); void exec(); void set_scale_factor(SDL_Window *win, unsigned sf); void paint(SDL_Renderer *rr, int paint); void paint_scaled(SDL_Renderer *rr, int paint, unsigned scale); void paint_cached_background(SDL_Renderer *rr); bool handle_key_pressed(const SDL_KeyboardEvent &event); bool handle_key_released(const SDL_KeyboardEvent &event); bool handle_mouse_pressed(const SDL_MouseButtonEvent &event); bool handle_mouse_released(const SDL_MouseButtonEvent &event); bool handle_text_input(const SDL_TextInputEvent &event); void play_file(const std::string &dir, const File_Entry *entries, size_t index, size_t count); void play_random(const std::string &dir, const File_Entry &entry); void set_current_path(const std::string &path); static bool filter_file_name(const std::string &name); static bool filter_file_entry(const File_Entry &ent); void request_update(); void update_modals(); void open_help_dialog(); void open_fx_dialog(); void choose_midi_output(bool ask, gsl::cstring_span choice); void choose_synth(bool ask, gsl::cstring_span choice); void get_midi_outputs(std::vector<Midi_Output> &outputs); void choose_theme(gsl::cstring_span choice); void get_themes(std::vector<std::string> &themes); void load_theme(gsl::cstring_span theme); void load_default_theme(); void load_theme_configuration(const CSimpleIniA &ini); void get_fx_parameters(const CSimpleIniA &ini, int *values) const; void engage_shutdown(); void engage_shutdown_if_esc_key(); void advance_shutdown(); bool should_quit() const; private: std::unique_ptr<CSimpleIniA> initialize_config(); private: void receive_state_in_other_thread(const Player_State &ps); private: SDLpp_Window_u window_; SDLpp_Renderer_u renderer_; SDL_TimerID update_timer_ = 0; std::unique_ptr<Main_Layout> layout_; std::vector<std::unique_ptr<Modal_Box>> modal_; SDLpp_Texture_u cached_background_; SDLpp_Surface_u logo_image_; SDLpp_Surface_u wallpaper_image_; bool fadeout_engaged_ = false; int fadeout_time_ = 0; uint32_t esc_key_timer_ = 0; unsigned scale_factor_ = 1; std::unique_ptr<File_Browser> file_browser_; std::unique_ptr<Metadata_Display> metadata_display_; std::unique_ptr<Level_Meter> level_meter_[10]; std::unique_ptr<Player> player_; std::string last_midi_output_choice_; std::string last_synth_choice_; std::string last_theme_choice_; std::unique_ptr<Player_State> ps_; std::mutex ps_mutex_; enum Info_Mode { Info_File, Info_Metadata, Info_Mode_Count, }; Info_Mode info_mode_ = Info_File; };
{ "alphanum_fraction": 0.7338337182, "avg_line_length": 29.3559322034, "ext": "h", "hexsha": "856ae8e062860141a33bc8bfb8b1588f7c125548", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-11-22T08:05:13.000Z", "max_forks_repo_forks_event_min_datetime": "2020-07-10T18:48:10.000Z", "max_forks_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "jpcima/smf-dsp", "max_forks_repo_path": "sources/application.h", "max_issues_count": 19, "max_issues_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_issues_repo_issues_event_max_datetime": "2022-01-16T20:44:07.000Z", "max_issues_repo_issues_event_min_datetime": "2020-07-05T23:59:33.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "jpcima/smf-dsp", "max_issues_repo_path": "sources/application.h", "max_line_length": 98, "max_stars_count": 22, "max_stars_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "jpcima/smf-dsp", "max_stars_repo_path": "sources/application.h", "max_stars_repo_stars_event_max_datetime": "2022-03-26T23:08:17.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-08T15:23:44.000Z", "num_tokens": 809, "size": 3464 }
#include "lah.h" #ifdef HAVE_LAPACK /* Use a LAPACK package to do the heavy work */ /*#include <cblas.h>*/ #include <lapacke.h> lah_Return lah_forwardSub(lah_mat *B, lah_mat const *L) { if ( L == NULL || B == NULL || L->nR != B->nR || B->nR != L->nC) { return lahReturnParameterError; } /* matrix_layout = LAH_LAPACK_LAYOUT; if (matrix_layout == LAPACK_COL_MAJOR) { lda = L->nR; ldb = B->nR; } else { lda = L->nC; ldb = B->nC; } */ return (!POTRS(LAH_LAPACK_LAYOUT, 'L', L->nR, B->nC, L->data, LAH_LEADING_DIM(L), B->data, LAH_LEADING_DIM(B))) ? lahReturnOk : lahReturnExternError; } #else /* fallback to primitive linear algebra subroutines */ #include <stdlib.h> #include <math.h> lah_Return lah_forwardSub(lah_mat *B, const lah_mat *L) { lah_index i, j, k; lah_value *diag, *row, *Aij, *bi, *bj; if ( L == NULL || B == NULL || L->nR != B->nR || B->nR != L->nC) { return lahReturnParameterError; } /* loop over cols of x and b */ for (k = 0; k < B->nC; k++) { /* initialize pointers for i-loop*/ bi = B->data + k * B->incCol; diag = L->data; row = L->data; /* loop over rows of x*/ for (i = 0; i < B->nR; i++) { /* initialize pointers for j-loop */ bj = B->data + k * B->incCol; Aij = row; /* substitute up to (excluding) current x */ for (j = 0; j < i; j++) { *bi -= *Aij * *bj; /* End of Loop: Increment Pointers */ bj += B->incRow; Aij += L->incCol; } /* divide xi by diagonal element of L */ if (fabs(*diag) > 0.00001) *bi /= *diag; else return lahReturnMathError; /* End of Loop: Increment Pointers */ diag += L->incRow + L->incCol; bi += B->incRow; row += L->incRow; } } return lahReturnOk; } #endif /* endif primitive implementation */
{ "alphanum_fraction": 0.4671201814, "avg_line_length": 25.9411764706, "ext": "c", "hexsha": "f430addd9f3181cf200fe98b0cd3357fc82e8ef7", "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": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "maj0e/linear-algebra-helpers", "max_forks_repo_path": "Source/lah_forwardSub.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "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": "maj0e/linear-algebra-helpers", "max_issues_repo_path": "Source/lah_forwardSub.c", "max_line_length": 115, "max_stars_count": null, "max_stars_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "maj0e/linear-algebra-helpers", "max_stars_repo_path": "Source/lah_forwardSub.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 634, "size": 2205 }
// // Copyright (C) 2019 Assured Information Security, Inc. // // 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. /// /// @file bfgsl.h /// #ifndef BFGSL_H #define BFGSL_H #if defined(__clang__) || defined(__GNUC__) #pragma GCC system_header #endif #include <string.h> /// @cond #define concat1(a,b) a ## b #define concat2(a,b) concat1(a,b) #define ___ concat2(dont_care, __COUNTER__) /// @endcond #ifndef NEED_GSL_LITE #include <gsl/gsl> namespace gsl { /// @cond #define expects(cond) Expects(cond) #define ensures(cond) Ensures(cond) template <class F> class final_act_success { public: explicit final_act_success(F f) noexcept : f_(std::move(f)), invoke_(true) {} final_act_success(final_act_success &&other) noexcept : f_(std::move(other.f_)), invoke_(other.invoke_) { other.invoke_ = false; } final_act_success(const final_act_success &) = delete; final_act_success &operator=(const final_act_success &) = delete; ~final_act_success() noexcept { if (std::uncaught_exception()) { return; } if (invoke_) { f_(); } } private: F f_; bool invoke_; }; template <class F> class final_act_failure { public: explicit final_act_failure(F f) noexcept : f_(std::move(f)), invoke_(true) {} final_act_failure(final_act_failure &&other) noexcept : f_(std::move(other.f_)), invoke_(other.invoke_) { other.invoke_ = false; } final_act_failure(const final_act_failure &) = delete; final_act_failure &operator=(const final_act_failure &) = delete; ~final_act_failure() noexcept { if (!std::uncaught_exception()) { return; } if (invoke_) { f_(); } } private: F f_; bool invoke_; }; template <class F> inline final_act_success<F> on_success(const F &f) noexcept { return final_act_success<F>(f); } template <class F> inline final_act_success<F> on_success(F &&f) noexcept { return final_act_success<F>(std::forward<F>(f)); } template <class F> inline final_act_failure<F> on_failure(const F &f) noexcept { return final_act_failure<F>(f); } template <class F> inline final_act_failure<F> on_failure(F &&f) noexcept { return final_act_failure<F>(std::forward<F>(f)); } /// @endcond /// Memset /// /// Same as std::memset, but for spans /// /// @param dst The span to memset /// @param val The value to set the span to /// @return Returns dst /// template<class DstElementType, std::ptrdiff_t DstExtent, class T> auto memset(span<DstElementType, DstExtent> dst, T val) { expects(dst.size() > 0); return std::memset( dst.data(), static_cast<int>(val), static_cast<std::size_t>(dst.size()) ); } } #else #ifdef NEED_STD_LITE #include <bfstd.h> #endif /// @cond #if defined(__clang__) || defined(__GNUC__) #define gsl_likely(x) __builtin_expect(!!(x), 1) #define gsl_unlikely(x) __builtin_expect(!!(x), 0) #else #define gsl_likely(x) (x) #define gsl_unlikely(x) (x) #endif #ifndef GSL_ABORT #define GSL_ABORT abort #endif #define expects(cond) \ if (gsl_unlikely(!(cond))) { \ GSL_ABORT(); \ } #define ensures(cond) \ if (gsl_unlikely(!(cond))) { \ GSL_ABORT(); \ } /// @endcond namespace gsl { /// Narrow Cast /// /// A rename of static_cast to indicate a narrow (e.g. 64bit to 32bit) /// /// @param u the value to narrow /// @return static_cast<T>(u) /// template<class T, class U> inline constexpr T narrow_cast(U &&u) noexcept { return static_cast<T>(std::forward<U>(u)); } /// At /// /// Returns a reference to an element in an array given an index. Unlike /// the [] operator, if the indexis out-of-bounds, an exception is thrown, /// or std::terminate() is called. /// /// @param arr the array /// @param index the index of the element to retrieve. /// @return a reference to /// template<class T, size_t N, class I> constexpr T & at(T(&arr)[N], I index) { expects(index >= 0 && index < narrow_cast<I>(N)); return arr[static_cast<size_t>(index)]; } /// At /// /// Returns a reference to an element in an array given an index. Unlike /// the [] operator, if the indexis out-of-bounds, an exception is thrown, /// or std::terminate() is called. /// /// @param arr the array /// @param index the index of the element to retrieve. /// @return a reference to /// template<class T, size_t N, class I> const constexpr T & at(const T(&arr)[N], I index) { expects(index >= 0 && index < narrow_cast<I>(N)); return arr[static_cast<size_t>(index)]; } /// At /// /// Returns a reference to an element in an array given an index. Unlike /// the [] operator, if the indexis out-of-bounds, an exception is thrown, /// or std::terminate() is called. /// /// @param arr the array /// @param N the size of the array /// @param index the index of the element to retrieve. /// @return a reference to /// template<class T, class I> constexpr T & at(T *arr, size_t N, I index) { expects(index >= 0 && index < narrow_cast<I>(N)); return arr[static_cast<size_t>(index)]; } /// At /// /// Returns a reference to an element in an array given an index. Unlike /// the [] operator, if the indexis out-of-bounds, an exception is thrown, /// or std::terminate() is called. /// /// @param arr the array /// @param N the size of the array /// @param index the index of the element to retrieve. /// @return a reference to /// template<class T, class I> const constexpr T & at(const T *arr, size_t N, I index) { expects(index >= 0 && index < narrow_cast<I>(N)); return arr[static_cast<size_t>(index)]; } } #endif #endif
{ "alphanum_fraction": 0.6280084448, "avg_line_length": 24.8426573427, "ext": "h", "hexsha": "7367805e985a85e20757980c61e52345071518d9", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-06-17T15:04:38.000Z", "max_forks_repo_forks_event_min_datetime": "2020-05-21T22:57:04.000Z", "max_forks_repo_head_hexsha": "7c1dce35e9e54601de1c4655565fde803ab446f0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "chp-io/hypervisor", "max_forks_repo_path": "bfsdk/include/bfgsl.h", "max_issues_count": 7, "max_issues_repo_head_hexsha": "7c1dce35e9e54601de1c4655565fde803ab446f0", "max_issues_repo_issues_event_max_datetime": "2018-02-14T18:37:18.000Z", "max_issues_repo_issues_event_min_datetime": "2017-11-07T00:25:25.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "chp-io/hypervisor", "max_issues_repo_path": "bfsdk/include/bfgsl.h", "max_line_length": 107, "max_stars_count": 5, "max_stars_repo_head_hexsha": "7c1dce35e9e54601de1c4655565fde803ab446f0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "chp-io/hypervisor", "max_stars_repo_path": "bfsdk/include/bfgsl.h", "max_stars_repo_stars_event_max_datetime": "2022-03-16T07:51:29.000Z", "max_stars_repo_stars_event_min_datetime": "2020-03-28T18:31:24.000Z", "num_tokens": 1691, "size": 7105 }
#pragma once #include <stdlib.h> #include <unistd.h> #include <string.h> #include "core/common.h" #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> void batch_linterp_continuous_axis(float** yy, double* x, size_t size, size_t stride, size_t count); void linterp_continuous_axis(float** yy, double* x, size_t size, double dt); void gsl_interp_continuous_axis(float** yy, double* x, size_t size, double dx, gsl_interp_accel **acc, gsl_spline **spline); void batch_gsl_interp_continuous_axis(float** yy, double* x, size_t size, size_t stride, size_t count);
{ "alphanum_fraction": 0.7610619469, "avg_line_length": 33.2352941176, "ext": "h", "hexsha": "169e591f5f7f29627c73d1fc47a41ba9ef27898a", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-07-05T02:31:52.000Z", "max_forks_repo_forks_event_min_datetime": "2017-09-05T15:12:04.000Z", "max_forks_repo_head_hexsha": "221910cb2f4e981e0d512744a1561c04dad26184", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "godsic/semargl-ng", "max_forks_repo_path": "core/interp.h", "max_issues_count": 4, "max_issues_repo_head_hexsha": "221910cb2f4e981e0d512744a1561c04dad26184", "max_issues_repo_issues_event_max_datetime": "2018-07-02T14:31:15.000Z", "max_issues_repo_issues_event_min_datetime": "2017-04-22T14:07:30.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "godsic/semargl-ng", "max_issues_repo_path": "core/interp.h", "max_line_length": 124, "max_stars_count": 2, "max_stars_repo_head_hexsha": "221910cb2f4e981e0d512744a1561c04dad26184", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "godsic/semargl-ng", "max_stars_repo_path": "core/interp.h", "max_stars_repo_stars_event_max_datetime": "2017-04-22T18:00:50.000Z", "max_stars_repo_stars_event_min_datetime": "2016-10-25T16:24:43.000Z", "num_tokens": 149, "size": 565 }
/* multiroots/gsl_multiroots.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 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. */ #ifndef __GSL_MULTIROOTS_H__ #define __GSL_MULTIROOTS_H__ #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.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 /* Definition of vector-valued functions with parameters based on gsl_vector */ struct gsl_multiroot_function_struct { int (* f) (const gsl_vector * x, void * params, gsl_vector * f); size_t n; void * params; }; typedef struct gsl_multiroot_function_struct gsl_multiroot_function ; #define GSL_MULTIROOT_FN_EVAL(F,x,y) (*((F)->f))(x,(F)->params,(y)) int gsl_multiroot_fdjacobian (gsl_multiroot_function * F, const gsl_vector * x, const gsl_vector * f, double epsrel, gsl_matrix * jacobian); typedef struct { const char *name; size_t size; int (*alloc) (void *state, size_t n); int (*set) (void *state, gsl_multiroot_function * function, gsl_vector * x, gsl_vector * f, gsl_vector * dx); int (*iterate) (void *state, gsl_multiroot_function * function, gsl_vector * x, gsl_vector * f, gsl_vector * dx); void (*free) (void *state); } gsl_multiroot_fsolver_type; typedef struct { const gsl_multiroot_fsolver_type * type; gsl_multiroot_function * function ; gsl_vector * x ; gsl_vector * f ; gsl_vector * dx ; void *state; } gsl_multiroot_fsolver; gsl_multiroot_fsolver * gsl_multiroot_fsolver_alloc (const gsl_multiroot_fsolver_type * T, size_t n); void gsl_multiroot_fsolver_free (gsl_multiroot_fsolver * s); int gsl_multiroot_fsolver_set (gsl_multiroot_fsolver * s, gsl_multiroot_function * f, gsl_vector * x); int gsl_multiroot_fsolver_iterate (gsl_multiroot_fsolver * s); const char * gsl_multiroot_fsolver_name (const gsl_multiroot_fsolver * s); gsl_vector * gsl_multiroot_fsolver_root (const gsl_multiroot_fsolver * s); gsl_vector * gsl_multiroot_fsolver_dx (const gsl_multiroot_fsolver * s); gsl_vector * gsl_multiroot_fsolver_f (const gsl_multiroot_fsolver * s); /* Definition of vector-valued functions and gradient with parameters based on gsl_vector */ struct gsl_multiroot_function_fdf_struct { int (* f) (const gsl_vector * x, void * params, gsl_vector * f); int (* df) (const gsl_vector * x, void * params, gsl_matrix * df); int (* fdf) (const gsl_vector * x, void * params, gsl_vector * f, gsl_matrix *df); size_t n; void * params; }; typedef struct gsl_multiroot_function_fdf_struct gsl_multiroot_function_fdf ; #define GSL_MULTIROOT_FN_EVAL_F(F,x,y) ((*((F)->f))(x,(F)->params,(y))) #define GSL_MULTIROOT_FN_EVAL_DF(F,x,dy) ((*((F)->df))(x,(F)->params,(dy))) #define GSL_MULTIROOT_FN_EVAL_F_DF(F,x,y,dy) ((*((F)->fdf))(x,(F)->params,(y),(dy))) typedef struct { const char *name; size_t size; int (*alloc) (void *state, size_t n); int (*set) (void *state, gsl_multiroot_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_matrix * J, gsl_vector * dx); int (*iterate) (void *state, gsl_multiroot_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_matrix * J, gsl_vector * dx); void (*free) (void *state); } gsl_multiroot_fdfsolver_type; typedef struct { const gsl_multiroot_fdfsolver_type * type; gsl_multiroot_function_fdf * fdf ; gsl_vector * x; gsl_vector * f; gsl_matrix * J; gsl_vector * dx; void *state; } gsl_multiroot_fdfsolver; gsl_multiroot_fdfsolver * gsl_multiroot_fdfsolver_alloc (const gsl_multiroot_fdfsolver_type * T, size_t n); int gsl_multiroot_fdfsolver_set (gsl_multiroot_fdfsolver * s, gsl_multiroot_function_fdf * fdf, gsl_vector * x); int gsl_multiroot_fdfsolver_iterate (gsl_multiroot_fdfsolver * s); void gsl_multiroot_fdfsolver_free (gsl_multiroot_fdfsolver * s); const char * gsl_multiroot_fdfsolver_name (const gsl_multiroot_fdfsolver * s); gsl_vector * gsl_multiroot_fdfsolver_root (const gsl_multiroot_fdfsolver * s); gsl_vector * gsl_multiroot_fdfsolver_dx (const gsl_multiroot_fdfsolver * s); gsl_vector * gsl_multiroot_fdfsolver_f (const gsl_multiroot_fdfsolver * s); int gsl_multiroot_test_delta (const gsl_vector * dx, const gsl_vector * x, double epsabs, double epsrel); int gsl_multiroot_test_residual (const gsl_vector * f, double epsabs); GSL_VAR const gsl_multiroot_fsolver_type * gsl_multiroot_fsolver_dnewton; GSL_VAR const gsl_multiroot_fsolver_type * gsl_multiroot_fsolver_broyden; GSL_VAR const gsl_multiroot_fsolver_type * gsl_multiroot_fsolver_hybrid; GSL_VAR const gsl_multiroot_fsolver_type * gsl_multiroot_fsolver_hybrids; GSL_VAR const gsl_multiroot_fdfsolver_type * gsl_multiroot_fdfsolver_newton; GSL_VAR const gsl_multiroot_fdfsolver_type * gsl_multiroot_fdfsolver_gnewton; GSL_VAR const gsl_multiroot_fdfsolver_type * gsl_multiroot_fdfsolver_hybridj; GSL_VAR const gsl_multiroot_fdfsolver_type * gsl_multiroot_fdfsolver_hybridsj; __END_DECLS #endif /* __GSL_MULTIROOTS_H__ */
{ "alphanum_fraction": 0.7274664045, "avg_line_length": 34.4745762712, "ext": "h", "hexsha": "9e28897f7bd0e22726d0f95af11db5a1925b7143", "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": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "andrewkern/segSiteHMM", "max_forks_repo_path": "extern/include/gsl/gsl_multiroots.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "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": "andrewkern/segSiteHMM", "max_issues_repo_path": "extern/include/gsl/gsl_multiroots.h", "max_line_length": 132, "max_stars_count": null, "max_stars_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "andrewkern/segSiteHMM", "max_stars_repo_path": "extern/include/gsl/gsl_multiroots.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1629, "size": 6102 }
#pragma once /* * (C) Copyright 2020 UCAR * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. */ /// \file Copying.h /// \brief Generic copying facility /// \note Feature is under development. This is a placeholder header file. #include <algorithm> #include <gsl/gsl-lite.hpp> #include <memory> #include <set> #include <utility> #include <vector> #include "ioda/Group.h" #include "ioda/defs.h" namespace ioda { class Group; class Has_Variables; class ObjectSelection; struct ScaleMapping; /// \todo This function is not yet complete. /// It exists in its present form to provide the guts for /// a timing test. Do not use. /// \brief Generic data copying function /// \param from contains the objects that we are copying /// \param to contains the destination(s) of the copy /// \param scale_map contains settings regarding how dimension scales /// are propagated IODA_DL void copy(const ObjectSelection& from, ObjectSelection& to, const ScaleMapping& scale_map); /// \brief Allows you to select objects for a copy operation class IODA_DL ObjectSelection { // friend IODA_DL void copy(const ObjectSelection&, ObjectSelection&, const ScaleMapping&); public: Group g_; bool recurse_ = false; public: ~ObjectSelection(); ObjectSelection(); ObjectSelection(const Group& g, bool recurse = true); /* ObjectSelection(const Variable& v) : ObjectSelection() { insert(v); } ObjectSelection(const std::vector<Variable>& v) : ObjectSelection() { insert(v); } ObjectSelection(const Has_Variables& v) : ObjectSelection() { insert(v); } ObjectSelection(const Group& g, const std::vector<std::string>& v) : ObjectSelection() { insert(g,v); } void insert(const ObjectSelection&); void insert(const Variable&); void insert(const std::vector<Variable>&); void insert(const Has_Variables&); void insert(const Group&, const std::vector<std::string>&); void insert(const Group&, bool recurse = true); ObjectSelection operator+(const ObjectSelection&) const; ObjectSelection operator+(const Variable&) const; ObjectSelection operator+(const std::vector<Variable>&) const; ObjectSelection operator+(const Has_Variables&) const; // Group insertions need to be wrapped by an ObjectSelection. ObjectSelection& operator+=(const ObjectSelection&); ObjectSelection& operator+=(const Variable&); ObjectSelection& operator+=(const std::vector<Variable>&); ObjectSelection& operator+=(const Has_Variables&); */ }; /// \brief Settings for how to remap dimension scales struct IODA_DL ScaleMapping { public: ~ScaleMapping(); std::vector<std::pair<Variable, Variable>> map_from_to; std::vector<Variable> map_new; bool autocreate = false; }; } // namespace ioda
{ "alphanum_fraction": 0.73302524, "avg_line_length": 31.9659090909, "ext": "h", "hexsha": "8fa6d91bf7340d657c19c72fdad5b2a30e6d8d6c", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-11-14T09:19:25.000Z", "max_forks_repo_forks_event_min_datetime": "2021-06-09T16:12:02.000Z", "max_forks_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "NOAA-EMC/ioda", "max_forks_repo_path": "src/engines/ioda/include/ioda/Copying.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "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": "NOAA-EMC/ioda", "max_issues_repo_path": "src/engines/ioda/include/ioda/Copying.h", "max_line_length": 99, "max_stars_count": 1, "max_stars_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "NOAA-EMC/ioda", "max_stars_repo_path": "src/engines/ioda/include/ioda/Copying.h", "max_stars_repo_stars_event_max_datetime": "2021-06-09T16:11:50.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-09T16:11:50.000Z", "num_tokens": 655, "size": 2813 }
/* vector/gsl_check_range.h * * Copyright (C) 2003, 2004, 2007 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_CHECK_RANGE_H__ #define __GSL_CHECK_RANGE_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> #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 GSL_VAR int gsl_check_range; /* Turn range checking on by default, unless the user defines GSL_RANGE_CHECK_OFF, or defines GSL_RANGE_CHECK to 0 explicitly */ #ifdef GSL_RANGE_CHECK_OFF # ifndef GSL_RANGE_CHECK # define GSL_RANGE_CHECK 0 # else # error "cannot set both GSL_RANGE_CHECK and GSL_RANGE_CHECK_OFF" # endif #else # ifndef GSL_RANGE_CHECK # define GSL_RANGE_CHECK 1 # endif #endif __END_DECLS #endif /* __GSL_CHECK_RANGE_H__ */
{ "alphanum_fraction": 0.7264502395, "avg_line_length": 27.6323529412, "ext": "h", "hexsha": "5b0a521fa3a00cbdf349aee26979a4e334299afc", "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": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_path": "deps/include/gsl/gsl_check_range.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "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": "berkus/music-cs", "max_issues_repo_path": "deps/include/gsl/gsl_check_range.h", "max_line_length": 82, "max_stars_count": 2, "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_path": "deps/include/gsl/gsl_check_range.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": 463, "size": 1879 }
/*! \file allvars.c * \brief provides instances of all global variables. */ #include <stdio.h> #include <gsl/gsl_rng.h> #include "tags.h" #include "allvars.h" int ThisTask; /*!< the rank of the local processor */ int NTask; /*!< number of processors */ int PTask; /*!< smallest integer such that NTask <= 2^PTask */ int NumPart; /*!< number of particles on the LOCAL processor */ int N_gas; /*!< number of gas particles on the LOCAL processor */ long long Ntype[6]; /*!< total number of particles of each type */ int NtypeLocal[6]; /*!< local number of particles of each type */ int NumForceUpdate; /*!< number of active particles on local processor in current timestep */ int NumSphUpdate; /*!< number of active SPH particles on local processor in current timestep */ double CPUThisRun; /*!< Sums the CPU time for the process (current submission only) */ int RestartFlag; /*!< taken from command line used to start code. 0 is normal start-up from initial conditions, 1 is resuming a run from a set of restart files, while 2 marks a restart from a snapshot file. */ char *Exportflag; /*!< Buffer used for flagging whether a particle needs to be exported to another process */ int *Ngblist; /*!< Buffer to hold indices of neighbours retrieved by the neighbour search routines */ int TreeReconstructFlag; /*!< Signals that a new tree needs to be constructed */ int Flag_FullStep; /*!< This flag signals that the current step involves all particles */ int ZeroTimestepEncountered; /*!< Flag used by AMUSE. When a particle is assigned a timestep of zero, an exception is raised instead of forcing the application to exit. */ gsl_rng *random_generator; /*!< the employed random number generator of the GSL library */ double RndTable[RNDTABLE]; /*!< Hold a table with random numbers, refreshed every timestep */ double DomainCorner[3]; /*!< gives the lower left corner of simulation volume */ double DomainCenter[3]; /*!< gives the center of simulation volume */ double DomainLen; /*!< gives the (maximum) side-length of simulation volume */ double DomainFac; /*!< factor used for converting particle coordinates to a Peano-Hilbert mesh covering the simulation volume */ int DomainMyStart; /*!< first domain mesh cell that resides on the local processor */ int DomainMyLast; /*!< last domain mesh cell that resides on the local processor */ int *DomainStartList; /*!< a table that lists the first domain mesh cell for all processors */ int *DomainEndList; /*!< a table that lists the last domain mesh cell for all processors */ double *DomainWork; /*!< a table that gives the total "work" due to the particles stored by each processor */ int *DomainCount; /*!< a table that gives the total number of particles held by each processor */ int *DomainCountSph; /*!< a table that gives the total number of SPH particles held by each processor */ int *DomainTask; /*!< this table gives for each leaf of the top-level tree the processor it was assigned to */ int *DomainNodeIndex; /*!< this table gives for each leaf of the top-level tree the corresponding node of the gravitational tree */ FLOAT *DomainTreeNodeLen; /*!< this table gives for each leaf of the top-level tree the side-length of the corresponding node of the gravitational tree */ FLOAT *DomainHmax; /*!< this table gives for each leaf of the top-level tree the maximum SPH smoothing length among the particles of the corresponding node of the gravitational tree */ struct DomainNODE *DomainMoment; /*!< this table stores for each node of the top-level tree corresponding node data from the gravitational tree */ peanokey *DomainKeyBuf; /*!< this points to a buffer used during the exchange of particle data */ peanokey *Key; /*!< a table used for storing Peano-Hilbert keys for particles */ peanokey *KeySorted; /*!< holds a sorted table of Peano-Hilbert keys for all particles, used to construct top-level tree */ int NTopnodes; /*!< total number of nodes in top-level tree */ int NTopleaves; /*!< number of leaves in top-level tree. Each leaf can be assigned to a different processor */ struct topnode_data *TopNodes; /*!< points to the root node of the top-level tree */ double TimeOfLastTreeConstruction; /*!< holds what it says, only used in connection with FORCETEST */ /* variables for input/output, usually only used on process 0 */ char ParameterFile[MAXLEN_FILENAME]; /*!< file name of parameterfile used for starting the simulation */ FILE *FdInfo; /*!< file handle for info.txt log-file. */ FILE *FdEnergy; /*!< file handle for energy.txt log-file. */ FILE *FdTimings; /*!< file handle for timings.txt log-file. */ FILE *FdCPU; /*!< file handle for cpu.txt log-file. */ #ifdef FORCETEST FILE *FdForceTest; /*!< file handle for forcetest.txt log-file. */ #endif double DriftTable[DRIFT_TABLE_LENGTH]; /*!< table for the cosmological drift factors */ double GravKickTable[DRIFT_TABLE_LENGTH]; /*!< table for the cosmological kick factor for gravitational forces */ double HydroKickTable[DRIFT_TABLE_LENGTH]; /*!< table for the cosmological kick factor for hydrodynmical forces */ void *CommBuffer; /*!< points to communication buffer, which is used in the domain decomposition, the parallel tree-force computation, the SPH routines, etc. */ /*! This structure contains data which is the SAME for all tasks (mostly code parameters read from the * parameter file). Holding this data in a structure is convenient for writing/reading the restart file, and * it allows the introduction of new global variables in a simple way. The only thing to do is to introduce * them into this structure. */ struct global_data_all_processes All; /*! This structure holds all the information that is * stored for each particle of the simulation. */ struct particle_data *P, /*!< holds particle data on local processor */ *DomainPartBuf; /*!< buffer for particle data used in domain decomposition */ /* the following struture holds data that is stored for each SPH particle in addition to the collisionless * variables. */ struct sph_particle_data *SphP, /*!< holds SPH particle data on local processor */ *DomainSphBuf; /*!< buffer for SPH particle data in domain decomposition */ /* Variables for Tree */ int MaxNodes; /*!< maximum allowed number of internal nodes */ int Numnodestree; /*!< number of (internal) nodes in each tree */ struct NODE *Nodes_base, /*!< points to the actual memory allocted for the nodes */ *Nodes; /*!< this is a pointer used to access the nodes which is shifted such that Nodes[All.MaxPart] gives the first allocated node */ int *Nextnode; /*!< gives next node in tree walk */ int *Father; /*!< gives parent node in tree */ struct extNODE /*!< this structure holds additional tree-node information which is not needed in the actual gravity computation */ *Extnodes_base, /*!< points to the actual memory allocted for the extended node information */ *Extnodes; /*!< provides shifted access to extended node information, parallel to Nodes/Nodes_base */ /*! Header for the standard file format. */ struct io_header header; /*!< holds header for snapshot files */ char Tab_IO_Labels[IO_NBLOCKS][4]; /*<! This table holds four-byte character tags used for fileformat 2 */ /* global state of system, used for global statistics */ struct state_of_system SysState; /*<! Structure for storing some global statistics about the simulation. */ /* Various structures for communication */ struct gravdata_in *GravDataIn, /*!< holds particle data to be exported to other processors */ *GravDataGet, /*!< holds particle data imported from other processors */ *GravDataResult, /*!< holds the partial results computed for imported particles. Note: We use GravDataResult = GravDataGet, such that the result replaces the imported data */ *GravDataOut; /*!< holds partial results received from other processors. This will overwrite the GravDataIn array */ struct gravdata_index *GravDataIndexTable; /*!< the particles to be exported are grouped by task-number. This table allows the results to be disentangled again and to be assigned to the correct particle */ struct densdata_in *DensDataIn, /*!< holds particle data for SPH density computation to be exported to other processors */ *DensDataGet; /*!< holds imported particle data for SPH density computation */ struct densdata_out *DensDataResult, /*!< stores the locally computed SPH density results for imported particles */ *DensDataPartialResult; /*!< imported partial SPH density results from other processors */ struct hydrodata_in *HydroDataIn, /*!< holds particle data for SPH hydro-force computation to be exported to other processors */ *HydroDataGet; /*!< holds imported particle data for SPH hydro-force computation */ struct hydrodata_out *HydroDataResult, /*!< stores the locally computed SPH hydro results for imported particles */ *HydroDataPartialResult; /*!< imported partial SPH hydro-force results from other processors */ #ifdef TIMESTEP_LIMITER struct timedata_in *TimeDataIn, *TimeDataGet; #endif #ifndef NOMPI #include <mpi.h> MPI_Comm GADGET_WORLD; #endif
{ "alphanum_fraction": 0.6876386368, "avg_line_length": 45.495412844, "ext": "c", "hexsha": "4f59d12d0bd2f979d45fabfaadf81cd06a0ad684", "lang": "C", "max_forks_count": 102, "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:29:43.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-22T10:00:29.000Z", "max_forks_repo_head_hexsha": "3ac3b6b8f922643657279ddee5c8ab3fc0440d5e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "rieder/amuse", "max_forks_repo_path": "src/amuse/community/gadget2/src/allvars.c", "max_issues_count": 690, "max_issues_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:15:58.000Z", "max_issues_repo_issues_event_min_datetime": "2015-10-17T12:18:08.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "rknop/amuse", "max_issues_repo_path": "src/amuse/community/gadget2/src/allvars.c", "max_line_length": 194, "max_stars_count": 131, "max_stars_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "rknop/amuse", "max_stars_repo_path": "src/amuse/community/gadget2/src/allvars.c", "max_stars_repo_stars_event_max_datetime": "2022-02-01T12:11:29.000Z", "max_stars_repo_stars_event_min_datetime": "2015-06-04T09:06:57.000Z", "num_tokens": 2068, "size": 9918 }
/* * Copyright (c) 2009-2010 Simon van Heeringen <s.vanheeringen@ncmls.ru.nl> * * This module is free software. You can redistribute it and/or modify it under * the terms of the MIT License, see the file COPYING included with this * distribution. * * This module contains all the code to compare motifs * */ #include <Python.h> #include <math.h> #include <string.h> #include <stdio.h> #include <gsl/gsl_cdf.h> void fill_matrix(double matrix[][4], PyObject *matrix_o) { // Parse a PyObject matrix into a C array // Structure of the matrix is as follows: [[freqA, freqC, freqG, freqT], ...] int matrix_len = PyList_Size(matrix_o); int i,j; PyObject *item; for (i = 0; i < matrix_len; i++) { PyObject *row = PyList_GetItem(matrix_o, i); if (!PyList_Check(row)) { PyErr_SetString( PyExc_TypeError, "wrong matrix structure"); return; } if (PyList_Size(row) != 4) { PyErr_SetString( PyExc_TypeError, "4 nucleotides!"); return; } for (j = 0; j < 4; j++) { item = PyList_GetItem(row, j); matrix[i][j] = PyFloat_AsDouble(item); } } } double mean(double array[], double length) { double sum = 0; int i; for (i = 0; i < length; i++) { sum += array[i]; } return sum / length; } double sum(double array[], double length) { double sum = 0; int i; for (i = 0; i < length; i++) { sum += array[i]; } return sum; } double wic(double col1[], double col2[]) { int n; double x,y; double log2 = log(2.0); double factor = 2.5; double score = 0;; double score_a = 0.0; double score_b = 0.0; double pseudo = 0.0000001; for (n = 0; n < 4; n++) { x = col1[n] * log((col1[n] + pseudo) / 0.25) / log2; y = col2[n] * log((col2[n] + pseudo) / 0.25) / log2; score += fabs(x - y); score_a += x; score_b += y; } return sqrt(score_a * score_b) - factor * score; } double matrix_wic_mean(double matrix1[][4], double matrix2[][4], int length) { // Return the mean pcc of two matrices int i; double result[length]; for (i = 0; i < length; i++ ) { result[i] = wic(matrix1[i], matrix2[i]); } return mean(result, length); } double matrix_wic_sum(double matrix1[][4], double matrix2[][4], int length) { // Return the mean pcc of two matrices int i; double result[length]; for (i = 0; i < length; i++ ) { result[i] = wic(matrix1[i], matrix2[i]); } return sum(result, length); } double pcc(double col1[], double col2[]) { // Return the Pearson correlation coefficient of two motif columns int n; double sum1 = 0; double sum2 = 0; double mean1, mean2; for (n = 0; n < 4; n++) { sum1 += col1[n]; sum2 += col2[n]; } mean1 = sum1 / 4; mean2 = sum2 / 4; float a = 0; float x = 0; float y = 0; for (n = 0; n < 4; n++) { if (((col1[n] - mean1) != 0) && ((col2[n] - mean2) != 0)) { a += (col1[n] - mean1) * (col2[n] - mean2); x += pow((col1[n] - mean1), 2); y += pow((col2[n] - mean2), 2); } else { return 0; } } return a / sqrt(x * y); } double matrix_pcc_mean(double matrix1[][4], double matrix2[][4], int length) { // Return the mean pcc of two matrices int i; double result[length]; for (i = 0; i < length; i++ ) { result[i] = pcc(matrix1[i], matrix2[i]); } return mean(result, length); } double ed(double col1[], double col2[]) { // Return the euclidian distance of two motif columns int n; double score = 0; for (n = 0; n < 4; n++) { score = score + pow((col1[n] - col2[n]), 2); } return -sqrt(score); } double matrix_ed_mean(double matrix1[][4], double matrix2[][4], int length) { // Return the mean euclidian distance of two matrices int i; double result[length]; for (i = 0; i < length; i++ ) { result[i] = ed(matrix1[i], matrix2[i]); } return mean(result, length); } double distance(double col1[], double col2[]) { // Return the distance between two motifs (Harbison et al.) int n; double d = 0; for (n = 0; n < 4; n++) { d = d + pow(col1[n] - col2[n], 2); } d = d * 1 / sqrt(2); return -d; } double matrix_distance_mean(double matrix1[][4], double matrix2[][4], int length) { // Return the mean distance (Harbison et al.) of two matrices int i; double result[length]; for (i = 0; i < length; i++ ) { result[i] = distance(matrix1[i], matrix2[i]); } return mean(result, length); } double chisq(double col1[], double col2[]) { // Return the distance between two motifs (Harbison et al.) int n; double sum1 = 0; double sum2 = 0; double e1, e2; double c = 0; for (n = 0; n < 4; n++) { sum1 += col1[n]; sum2 += col2[n]; } for (n = 0; n < 4; n++) { e1 = (sum1 * (col1[n] + col2[n])) / (sum1 + sum2); e2 = (sum2 * (col1[n] + col2[n])) / (sum1 + sum2); c += pow((col1[n] - e1), 2) / e1; c += pow((col2[n] - e2), 2) / e2; } return 1 - gsl_cdf_chisq_P(c, 3.0); } double matrix_chisq_mean(double matrix1[][4], double matrix2[][4], int length) { // Return the mean distance (Harbison et al.) of two matrices int i; double result[length]; for (i = 0; i < length; i++ ) { result[i] = chisq(matrix1[i], matrix2[i]); } return mean(result, length); } static PyObject * c_metrics_score(PyObject *self, PyObject * args) { PyObject *matrix1_o; PyObject *matrix2_o; const char *metric; const char *combine; int matrix1_len; int matrix2_len; if (!PyArg_ParseTuple(args, "OOss", &matrix1_o, &matrix2_o, &metric, &combine)) { PyErr_SetString( PyExc_TypeError, "Error parsing arguments"); return NULL; } // Retrieve frequency matrix if (!PyList_Check(matrix1_o)) { PyErr_SetString( PyExc_TypeError, "Error: missing required argument matrix1"); return NULL; } if (!PyList_Check(matrix2_o)) { PyErr_SetString( PyExc_TypeError, "Error: missing required argument matrix2"); return NULL; } // Fill matrix1 matrix1_len = PyList_Size(matrix1_o); double matrix1[matrix1_len][4]; fill_matrix(matrix1, matrix1_o); // Fill matrix2 matrix2_len = PyList_Size(matrix2_o); double matrix2[matrix2_len][4]; fill_matrix(matrix2, matrix2_o); if (matrix1_len != matrix2_len) { PyErr_SetString( PyExc_TypeError, "Error: matrices have different sizes"); return NULL; } int i; double result[matrix1_len]; if (!strcmp(metric, "chisq")) { for (i = 0; i < matrix1_len; i++ ) { result[i] = chisq(matrix1[i], matrix2[i]); } } else if (!strcmp(metric, "wic")) { for (i = 0; i < matrix1_len; i++ ) { result[i] = wic(matrix1[i], matrix2[i]); } } else if (!strcmp(metric, "ed")) { for (i = 0; i < matrix1_len; i++ ) { result[i] = ed(matrix1[i], matrix2[i]); } } else if (!strcmp(metric, "pcc")) { for (i = 0; i < matrix1_len; i++ ) { result[i] = pcc(matrix1[i], matrix2[i]); } } else if (!strcmp(metric, "distance")) { for (i = 0; i < matrix1_len; i++ ) { result[i] = distance(matrix1[i], matrix2[i]); } } else { PyErr_SetString( PyExc_TypeError, "Unknown metric"); return NULL; } if (!strcmp(combine, "mean")) { return Py_BuildValue("f", mean(result, matrix1_len)); } else if (!strcmp(combine, "sum")) { return Py_BuildValue("f", sum(result, matrix1_len)); } else { PyErr_SetString( PyExc_TypeError, "Unknown combine"); return NULL; } } int get_truncate_len(len1, len2, pos) { // if (pos < 0) { len2 += pos; } else if (pos > 0) { len1 -= pos; } if (len1 > len2) { return len2; } else { return len1; } } void fill_tmp_matrices(double matrix1[][4], double matrix2[][4], int pos, int l, double tmp_matrix1[][4], double tmp_matrix2[][4]) { int start1 = 0; int start2 = 0; int i, n; if (pos < 0) { start2 = -pos; } else { start1 = pos; } for (i = 0; i < l; i++) { for (n = 0; n < 4; n++) { tmp_matrix1[i][n] = matrix1[start1 + i][n]; tmp_matrix2[i][n] = matrix2[start2 + i][n]; } } } int index_at_max(double scores[], int len) { double max = scores[0]; int i_at_max = 0; int i; if (len == 1) { return 0; } for (i = 1; i < len; i++) { if (scores[i] > max) { max = scores[i]; i_at_max = i; } } return i_at_max; } void fill_rc_matrix(double matrix[][4], int len, double rc_matrix[][4]) { int i = 0; for (i = 0; i < len; i++) { rc_matrix[i][0] = matrix[len - i - 1][3]; rc_matrix[i][1] = matrix[len - i - 1][2]; rc_matrix[i][2] = matrix[len - i - 1][1]; rc_matrix[i][3] = matrix[len - i - 1][0]; } } static PyObject * c_metrics_max_subtotal(PyObject *self, PyObject * args) { PyObject *matrix1_o; PyObject *matrix2_o; const char *metric; const char *combine; int matrix1_len; int matrix2_len; if (!PyArg_ParseTuple(args, "OOss", &matrix1_o, &matrix2_o, &metric, &combine)) { PyErr_SetString( PyExc_TypeError, "Error parsing arguments"); return NULL; } // Retrieve frequency matrix if (!PyList_Check(matrix1_o)) { PyErr_SetString( PyExc_TypeError, "Error: missing required argument matrix1"); return NULL; } if (!PyList_Check(matrix2_o)) { PyErr_SetString( PyExc_TypeError, "Error: missing required argument matrix2"); return NULL; } // Fill matrix1 matrix1_len = PyList_Size(matrix1_o); double matrix1[matrix1_len][4]; fill_matrix(matrix1, matrix1_o); // Fill matrix2 matrix2_len = PyList_Size(matrix2_o); double matrix2[matrix2_len][4]; fill_matrix(matrix2, matrix2_o); // Fill rc matrix2 double rc_matrix2[matrix2_len][4]; fill_rc_matrix(matrix2, matrix2_len, rc_matrix2); // Assign correct function int pos = -2; int l; float max_score; int min_overlap = 6; int nr_matches; int start_pos = -(matrix2_len - min_overlap); nr_matches = matrix1_len + matrix2_len - 2 * min_overlap + 1; int i; int positions[nr_matches * 2]; double scores[nr_matches * 2]; int orients[nr_matches * 2]; double (*ptr_metric_function)(double[][4], double[][4], int) = NULL; if ((!strcmp(metric, "chisq")) && (!strcmp(combine, "mean"))) { ptr_metric_function = &matrix_chisq_mean; } else if ((!strcmp(metric, "wic")) && (!strcmp(combine, "mean"))) { ptr_metric_function = &matrix_wic_mean; } else if ((!strcmp(metric, "wic")) && (!strcmp(combine, "sum"))) { ptr_metric_function = &matrix_wic_sum; } else if ((!strcmp(metric, "pcc")) && (!strcmp(combine, "mean"))) { ptr_metric_function = &matrix_pcc_mean; } else if ((!strcmp(metric, "ed")) && (!strcmp(combine, "mean"))) { ptr_metric_function = &matrix_ed_mean; } else if ((!strcmp(metric, "distance")) && (!strcmp(combine, "mean"))) { ptr_metric_function = &matrix_distance_mean; } else { PyErr_SetString( PyExc_TypeError, "Unknown metric or combination"); return NULL; } for (i = 0; i < nr_matches; i++) { pos = i + start_pos; l = get_truncate_len(matrix1_len, matrix2_len, pos); // Normal matrix double tmp_matrix1[l][4]; double tmp_matrix2[l][4]; fill_tmp_matrices(matrix1, matrix2, pos, l, tmp_matrix1, tmp_matrix2); max_score = (*ptr_metric_function) (tmp_matrix1, tmp_matrix2, l); positions[i] = pos; scores[i] = max_score; orients[i] = 1; //printf("CC 1 Len %i score %f\n", l, max_score); // Reverse complement matrix fill_tmp_matrices(matrix1, rc_matrix2, pos, l, tmp_matrix1, tmp_matrix2); max_score = (*ptr_metric_function) (tmp_matrix1, tmp_matrix2, l); positions[i + nr_matches] = pos; scores[i + nr_matches] = max_score; orients[i+ nr_matches] = -1; //printf("CC -1 Len %i score %f\n", l, max_score); } i = index_at_max(scores, nr_matches * 2); return Py_BuildValue("fii", scores[i], positions[i], orients[i]); } static PyObject * c_metrics_pwmscan(PyObject *self, PyObject * args) { PyObject *seq_o; PyObject *pwm_o; PyObject *cutoff_o; char *seq; int seq_len; int n_report; int pwm_len; int i, j; double zeta = 0.01; int scan_rc; if (!PyArg_ParseTuple(args, "OOOii", &seq_o, &pwm_o, &cutoff_o, &n_report, &scan_rc)) return NULL; // Sequence and length if (!PyString_Check(seq_o)) return NULL; seq = PyString_AsString(seq_o); seq_len = PyString_Size(seq_o); //Py_DECREF(seq_o); // Retrieve frequency matrix if (!PyList_Check(pwm_o)) return NULL; // Weight matrices pwm_len = PyList_Size(pwm_o); double pwm[pwm_len][4]; fill_matrix(pwm, pwm_o); //Py_DECREF(pwm_o); // Cutoff for every spacer length double cutoff; cutoff = PyFloat_AsDouble(cutoff_o); // Scan sequence int j_max = seq_len - pwm_len + 1; double score_matrix[j_max]; double rc_score_matrix[j_max]; double score, rc_score; if (j_max < 0) { j_max = 0;} int m; double g = 0.25; double z = 0.01; for (j = 0; j < j_max; j++) { score = 0; rc_score = 0; for (m = 0; m < pwm_len; m++) { switch(seq[j + m]) { case 'A': score += log(pwm[m][0] / g + z); rc_score += log(pwm[pwm_len - m - 1][3] / g + z); break; case 'C': score += log(pwm[m][1] / g + z); rc_score += log(pwm[pwm_len - m - 1][2] / g + z); break; case 'G': score += log(pwm[m][2] / g + z); rc_score += log(pwm[pwm_len - m - 1][1] / g + z); break; case 'T': score += log(pwm[m][3] / g + z); rc_score += log(pwm[pwm_len - m - 1][0] / g + z); break; } } score_matrix[j] = score; rc_score_matrix[j] = rc_score; } // Initialize matrices of n_report highest scores and corresponding positions + strands double maxScores[n_report]; double maxPos[n_report]; int maxStrand[n_report]; for (j = 0; j < n_report; j++) { maxScores[j] = -100; maxPos[j] = -1; maxStrand[j] = 1; } PyObject* return_list = PyList_New(0); int p,q; PyObject *x; for (j = 0; j < j_max; j++) { score = score_matrix[j]; if (n_report > 0) { if (score >= cutoff) { p = n_report - 1; while ((p >= 0) && (score > maxScores[p])) { p--; } if (p < (n_report-1)) { for (q = n_report - 1; q > (p + 1); q--) { maxScores[q] = maxScores[q - 1]; maxPos[q] = maxPos[q - 1]; maxStrand[q] = maxStrand[q - 1]; } maxScores[p + 1] = score; maxPos[p + 1] = j; maxStrand[p + 1] = 1; } } } else { if (score >= cutoff) { PyObject* row = PyList_New(0); x = PyFloat_FromDouble(score); PyList_Append(row, x); Py_DECREF(x); x = PyInt_FromLong((long) j); PyList_Append(row, x); Py_DECREF(x); x = PyInt_FromLong((long) 1); PyList_Append(row, x); Py_DECREF(x); PyList_Append(return_list, row); Py_DECREF(row); } } } if (scan_rc) { for (j = 0; j < j_max; j++) { score = rc_score_matrix[j]; if (n_report > 0) { if (score >= cutoff) { p = n_report - 1; while ((p >= 0) && (score > maxScores[p])) { p--; } if (p < (n_report-1)) { for (q = n_report - 1; q > (p + 1); q--) { maxScores[q] = maxScores[q - 1]; maxPos[q] = maxPos[q - 1]; maxStrand[q] = maxStrand[q - 1]; } maxScores[p + 1] = score; maxPos[p + 1] = j; maxStrand[p + 1] = -1; } } } else { if (score >= cutoff) { PyObject* row = PyList_New(0); x = PyFloat_FromDouble(score); PyList_Append(row, x); Py_DECREF(x); x = PyInt_FromLong((long) j); PyList_Append(row, x); Py_DECREF(x); x = PyInt_FromLong((long) 1); PyList_Append(row, x); Py_DECREF(x); PyList_Append(return_list, row); Py_DECREF(row); } } } } for (i = 0; i < n_report; i++) { if (maxPos[i] > - 1) { PyObject* row = PyList_New(0); x = PyFloat_FromDouble(maxScores[i]); PyList_Append(row, x); Py_DECREF(x); x = PyInt_FromLong((long)maxPos[i]); PyList_Append(row, x); Py_DECREF(x); x = PyInt_FromLong((long)maxStrand[i]); PyList_Append(row, x); Py_DECREF(x); PyList_Append(return_list, row); Py_DECREF(row); } } return return_list; } static PyMethodDef CoreMethods[] = { {"score", c_metrics_score, METH_VARARGS,"Test"}, {"c_max_subtotal", c_metrics_max_subtotal, METH_VARARGS,"Test"}, {"pwmscan", c_metrics_pwmscan, METH_VARARGS,"Test"}, {NULL, NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initc_metrics(void) { (void) Py_InitModule("c_metrics", CoreMethods); };
{ "alphanum_fraction": 0.6130167106, "avg_line_length": 23.3060029283, "ext": "c", "hexsha": "acfa514d04f240367bda09c0f65e4dfdc4590dee", "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": "gimmemotifs/c_metrics.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": "gimmemotifs/c_metrics.c", "max_line_length": 132, "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": "gimmemotifs/c_metrics.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": 5280, "size": 15918 }
/* ieee-utils/fp-sunos4.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 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 <sys/ieeefp.h> #include <floatingpoint.h> #include <signal.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_errno.h> int gsl_ieee_set_mode (int precision, int rounding, int exception_mask) { char * out ; switch (precision) { case GSL_IEEE_SINGLE_PRECISION: ieee_flags ("set", "precision", "single", out) ; break ; case GSL_IEEE_DOUBLE_PRECISION: ieee_flags ("set", "precision", "double", out) ; break ; case GSL_IEEE_EXTENDED_PRECISION: ieee_flags ("set", "precision", "extended", out) ; break ; default: ieee_flags ("set", "precision", "extended", out) ; } switch (rounding) { case GSL_IEEE_ROUND_TO_NEAREST: ieee_flags ("set", "direction", "nearest", out) ; break ; case GSL_IEEE_ROUND_DOWN: ieee_flags ("set", "direction", "negative", out) ; break ; case GSL_IEEE_ROUND_UP: ieee_flags ("set", "direction", "positive", out) ; break ; case GSL_IEEE_ROUND_TO_ZERO: ieee_flags ("set", "direction", "tozero", out) ; break ; default: ieee_flags ("set", "direction", "nearest", out) ; } if (exception_mask & GSL_IEEE_MASK_INVALID) { ieee_handler ("set", "invalid", SIGFPE_IGNORE) ; } else { ieee_handler ("set", "invalid", SIGFPE_ABORT) ; } if (exception_mask & GSL_IEEE_MASK_DENORMALIZED) { ieee_handler ("set", "denormalized", SIGFPE_IGNORE) ; } else { GSL_ERROR ("sunos4 does not support the denormalized operand exception. " "Use 'mask-denormalized' to work around this.", GSL_EUNSUP) ; } if (exception_mask & GSL_IEEE_MASK_DIVISION_BY_ZERO) { ieee_handler ("set", "division", SIGFPE_IGNORE) ; } else { ieee_handler ("set", "division", SIGFPE_ABORT) ; } if (exception_mask & GSL_IEEE_MASK_OVERFLOW) { ieee_handler ("set", "overflow", SIGFPE_IGNORE) ; } else { ieee_handler ("set", "overflow", SIGFPE_ABORT) ; } if (exception_mask & GSL_IEEE_MASK_UNDERFLOW) { ieee_handler ("set", "underflow", SIGFPE_IGNORE) ; } else { ieee_handler ("set", "underflow", SIGFPE_ABORT) ; } if (exception_mask & GSL_IEEE_TRAP_INEXACT) { ieee_handler ("set", "inexact", SIGFPE_ABORT) ; } else { ieee_handler ("set", "inexact", SIGFPE_IGNORE) ; } return GSL_SUCCESS ; }
{ "alphanum_fraction": 0.6404151404, "avg_line_length": 26.6341463415, "ext": "c", "hexsha": "307b5380554462f308ac1567878f89b218126634", "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/ieee-utils/fp-sunos4.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/ieee-utils/fp-sunos4.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/ieee-utils/fp-sunos4.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": 881, "size": 3276 }
/* specfunc/test_hermite.c * * Copyright (C) 2011, 2012, 2013, 2014 Konrad Griessinger * * 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 <gsl/gsl_math.h> #include <gsl/gsl_test.h> #include <gsl/gsl_sf.h> #include "test_sf.h" #define WKB_TOL (1.0e+04 * TEST_SQRT_TOL0) /* * Test the identities: * * Sum_{k=0}^n (n choose k) (2 y)^{n - k} H_k(x) = H_n(x + y) * * and * * Sum_{k=0}^n (n choose k) y^{n-k} He_k(x) = He_n(x + y) * * see: http://mathworld.wolfram.com/HermitePolynomial.html (Eq. 55) */ void test_hermite_id1(const int n, const double x, const double y) { double *a = malloc((n + 1) * sizeof(double)); double *b = malloc((n + 1) * sizeof(double)); double lhs, rhs; int k; a[0] = gsl_pow_int(2.0 * y, n); b[0] = gsl_pow_int(y, n); for (k = 1; k <= n; ++k) { double fac = (n - k + 1.0) / (k * y); a[k] = 0.5 * fac * a[k - 1]; b[k] = fac * b[k - 1]; } lhs = gsl_sf_hermite_phys_series(n, x, a); rhs = gsl_sf_hermite_phys(n, x + y); gsl_test_rel(lhs, rhs, TEST_TOL4, "identity1 phys n=%d x=%g y=%g", n, x, y); lhs = gsl_sf_hermite_prob_series(n, x, b); rhs = gsl_sf_hermite_prob(n, x + y); gsl_test_rel(lhs, rhs, TEST_TOL3, "identity1 prob n=%d x=%g y=%g", n, x, y); free(a); free(b); } int test_hermite(void) { gsl_sf_result r; int s = 0; int m, n, sa; double res[256]; double x; const double aizero1 = -2.3381074104597670384891972524467; /* first zero of the Airy function Ai */ /* test some known identities */ test_hermite_id1(10, 0.75, 0.33); test_hermite_id1(8, -0.75, 1.20); test_hermite_id1(7, 2.88, -3.2); x = 0.75; TEST_SF(s, gsl_sf_hermite_prob_e, (0, 0.75, &r), 1., TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_hermite_prob_e, (1, 0.75, &r), x, TEST_TOL0, GSL_SUCCESS); n = 25; TEST_SF(s, gsl_sf_hermite_prob_e, (n, 0., &r), 0., TEST_TOL0, GSL_SUCCESS); n = 28; TEST_SF(s, gsl_sf_hermite_prob_e, (n, 0., &r), 213458046676875, TEST_TOL0, GSL_SUCCESS); n = 25; TEST_SF(s, gsl_sf_hermite_prob_e, (n, 0.75, &r), -1.08128685847680748265939328423e12, TEST_TOL0, GSL_SUCCESS); n = 28; TEST_SF(s, gsl_sf_hermite_prob_e, (n, 0.75, &r), -1.60620252094658918105511125135e14, TEST_TOL0, GSL_SUCCESS); #if 0 n = 10025; x = ((sqrt(2*n+1.)+aizero1/pow(8.*n,1/6.))/2)*M_SQRT2; TEST_SF(s, gsl_sf_hermite_prob_e, (n, x, &r), -3.3090527852387782540121569578e18961, TEST_TOL0, GSL_SUCCESS); n = 10028; x = ((sqrt(2*n+1.)+aizero1/pow(8.*n,1/6.))/2)*M_SQRT2; TEST_SF(s, gsl_sf_hermite_prob_e, (n, x, &r), -7.515478445930242044360704363e18967, TEST_TOL0, GSL_SUCCESS); n = 10025; x = (sqrt(2*n+1.)-(aizero1/pow(8.*n,1/6.))/2)*M_SQRT2; TEST_SF(s, gsl_sf_hermite_prob_e, (n, x, &r), 4.1369269649092456235914193753e22243, TEST_TOL0, GSL_SUCCESS); n = 10028; x = (sqrt(2*n+1.)-(aizero1/pow(8.*n,1/6.))/2)*M_SQRT2; TEST_SF(s, gsl_sf_hermite_prob_e, (n, x, &r), 8.363694992558646923734666303e22250, TEST_TOL0, GSL_SUCCESS); n = 10025; x = (sqrt(2*n+1.)-2*(aizero1/pow(8.*n,1/6.)))*M_SQRT2; TEST_SF(s, gsl_sf_hermite_prob_e, (n, x, &r), 7.398863979737363164340057757e22273, TEST_TOL0, GSL_SUCCESS); n = 10028; x = (sqrt(2*n+1.)-2*(aizero1/pow(8.*n,1/6.)))*M_SQRT2; TEST_SF(s, gsl_sf_hermite_prob_e, (n, x, &r), 1.507131397474022356488976968e22281, TEST_TOL0, GSL_SUCCESS); #endif x = 0.75; n = 128; m = 225; TEST_SF(s, gsl_sf_hermite_prob_der_e, (m, n, x, &r), 0., TEST_TOL0, GSL_SUCCESS); n = 128; m = 5; TEST_SF(s, gsl_sf_hermite_prob_der_e, (m, n, x, &r), -3.0288278964712702882066404e112, TEST_TOL1, GSL_SUCCESS); sa = 0; gsl_sf_hermite_prob_array(0, x, res); TEST_SF_VAL(sa, res[0], +0.0, 1.0, TEST_TOL0); gsl_test(sa, "gsl_sf_hermite_prob_array(0, 0.75)"); s += sa; sa = 0; gsl_sf_hermite_prob_array(1, x, res); TEST_SF_VAL(sa, res[0], +0.0, 1.0, TEST_TOL0); TEST_SF_VAL(sa, res[1], +0.0, x, TEST_TOL0); gsl_test(sa, "gsl_sf_hermite_prob_array(1, 0.75)"); s += sa; sa = 0; gsl_sf_hermite_prob_array(100, x, res); TEST_SF_VAL(sa, res[0], +0.0, 1.0, TEST_TOL0); TEST_SF_VAL(sa, res[10], +0.0, 823.810509681701660156250, TEST_TOL0); TEST_SF_VAL(sa, res[100], +0.0, 1.03749254986255755872498e78, TEST_TOL1); gsl_test(sa, "gsl_sf_hermite_prob_array(100, 0.75)"); s += sa; sa = 0; gsl_sf_hermite_prob_array_der(0, 100, x, res); TEST_SF_VAL(sa, res[0], +0.0, 1.0, TEST_TOL0); TEST_SF_VAL(sa, res[10], +0.0, 823.810509681701660156250, TEST_TOL0); TEST_SF_VAL(sa, res[100], +0.0, 1.03749254986255755872498e78, TEST_TOL1); gsl_test(sa, "gsl_sf_hermite_prob_array_der(0, 100, 0.75)"); s += sa; sa = 0; gsl_sf_hermite_prob_array_der(1000, 100, x, res); TEST_SF_VAL(sa, res[0], +0.0, 0.0, TEST_TOL0); TEST_SF_VAL(sa, res[10], +0.0, 0.0, TEST_TOL0); TEST_SF_VAL(sa, res[100], +0.0, 0.0, TEST_TOL0); gsl_test(sa, "gsl_sf_hermite_prob_array_der(1000, 100, 0.75)"); s += sa; sa = 0; gsl_sf_hermite_prob_array_der(23, 100, x, res); TEST_SF_VAL(sa, res[10], +0.0, 0.0, TEST_TOL0); TEST_SF_VAL(sa, res[37], +0.0, 2.3592417210568968566591219172e37, TEST_TOL0); TEST_SF_VAL(sa, res[100], +0.0, 2.6503570965896336273549197e100, TEST_TOL0); gsl_test(sa, "gsl_sf_hermite_prob_array(23, 37, 0.75)"); s += sa; sa = 0; gsl_sf_hermite_prob_der_array(100, 50, x, res); TEST_SF_VAL(sa, res[0], +0.0, -3.88338863813139372375411561e31, TEST_TOL0); TEST_SF_VAL(sa, res[10], +0.0, 7.9614368698398116765703194e38, TEST_TOL0); TEST_SF_VAL(sa, res[100], +0.0, 0.0, TEST_TOL0); gsl_test(sa, "gsl_sf_hermite_prob_der_array(100, 50, 0.75)"); s += sa; n = 128; res[0] = 1.; for(m=1; m<=n; m++){ res[m] = res[m-1]/2.; } TEST_SF(s, gsl_sf_hermite_prob_series_e, (n, x, res, &r), -4.0451066556993485405907339548e68, TEST_TOL0, GSL_SUCCESS); /* phys */ x = 0.75; TEST_SF(s, gsl_sf_hermite_phys_e, (0, 0.75, &r), 1., TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_hermite_phys_e, (1, 0.75, &r), 2.*x, TEST_TOL0, GSL_SUCCESS); n = 25; TEST_SF(s, gsl_sf_hermite_phys_e, (n, 0., &r), 0., TEST_TOL0, GSL_SUCCESS); n = 28; TEST_SF(s, gsl_sf_hermite_phys_e, (n, 0., &r), 3497296636753920000, TEST_TOL0, GSL_SUCCESS); n = 25; TEST_SF(s, gsl_sf_hermite_phys_e, (n, 0.75, &r), -9.7029819451106077507781088352e15, TEST_TOL0, GSL_SUCCESS); n = 28; TEST_SF(s, gsl_sf_hermite_phys_e, (n, 0.75, &r), 3.7538457078067672096408339776e18, TEST_TOL0, GSL_SUCCESS); #if 0 n = 10025; x = ((sqrt(2*n+1.)+aizero1/pow(8.*n,1/6.))/2); TEST_SF(s, gsl_sf_hermite_phys_e, (n, x, &r), -2.7074282783315424535693575770e20470, TEST_TOL0, GSL_SUCCESS); n = 10028; x = ((sqrt(2*n+1.)+aizero1/pow(8.*n,1/6.))/2); TEST_SF(s, gsl_sf_hermite_phys_e, (n, x, &r), -1.7392214893577690864150561850e20477, TEST_TOL0, GSL_SUCCESS); n = 10025; x = (sqrt(2*n+1.)-(aizero1/pow(8.*n,1/6.))/2); TEST_SF(s, gsl_sf_hermite_phys_e, (n, x, &r), 3.3847852473526979744366379542e23752, TEST_TOL0, GSL_SUCCESS); n = 10028; x = (sqrt(2*n+1.)-(aizero1/pow(8.*n,1/6.))/2); TEST_SF(s, gsl_sf_hermite_phys_e, (n, x, &r), 1.9355145738418079256435712027e23760, TEST_TOL0, GSL_SUCCESS); n = 10025; x = (sqrt(2*n+1.)-2*(aizero1/pow(8.*n,1/6.))); TEST_SF(s, gsl_sf_hermite_phys_e, (n, x, &r), 6.053663953512337293393128307e23782, TEST_TOL0, GSL_SUCCESS); n = 10028; x = (sqrt(2*n+1.)-2*(aizero1/pow(8.*n,1/6.))); TEST_SF(s, gsl_sf_hermite_phys_e, (n, x, &r), 3.487782358276961096026268141e23790, TEST_TOL0, GSL_SUCCESS); #endif x = 0.75; n = 128; m = 225; TEST_SF(s, gsl_sf_hermite_phys_der_e, (m, n, x, &r), 0., TEST_TOL0, GSL_SUCCESS); n = 128; m = 5; TEST_SF(s, gsl_sf_hermite_phys_der_e, (m, n, x, &r), 2.89461215568095657569833e132, TEST_TOL0, GSL_SUCCESS); sa = 0; gsl_sf_hermite_phys_array(0, x, res); TEST_SF_VAL(sa, res[0], +0.0, 1.0, TEST_TOL0); gsl_test(sa, "gsl_sf_hermite_phys_array(0, 0.75)"); s += sa; sa = 0; gsl_sf_hermite_phys_array(1, x, res); TEST_SF_VAL(sa, res[0], +0.0, 1.0, TEST_TOL0); TEST_SF_VAL(sa, res[1], +0.0, 2.*x, TEST_TOL0); gsl_test(sa, "gsl_sf_hermite_phys_array(1, 0.75)"); s += sa; sa = 0; gsl_sf_hermite_phys_array(100, x, res); TEST_SF_VAL(sa, res[0], +0.0, 1.0, TEST_TOL0); TEST_SF_VAL(sa, res[10], +0.0, 38740.4384765625, TEST_TOL0); TEST_SF_VAL(sa, res[100], +0.0, -1.4611185395125104593177790757e93, TEST_TOL0); gsl_test(sa, "gsl_sf_hermite_phys_array(100, 0.75)"); s += sa; sa = 0; gsl_sf_hermite_phys_array_der(0, 100, x, res); TEST_SF_VAL(sa, res[0], +0.0, 1.0, TEST_TOL0); TEST_SF_VAL(sa, res[10], +0.0, 38740.4384765625, TEST_TOL0); TEST_SF_VAL(sa, res[100], +0.0, -1.4611185395125104593177790757e93, TEST_TOL0); gsl_test(sa, "gsl_sf_hermite_phys_array_der(0, 100, 0.75)"); s += sa; sa = 0; gsl_sf_hermite_phys_array_der(1000, 100, x, res); TEST_SF_VAL(sa, res[0], +0.0, 0.0, TEST_TOL0); TEST_SF_VAL(sa, res[10], +0.0, 0.0, TEST_TOL0); TEST_SF_VAL(sa, res[100], +0.0, 0.0, TEST_TOL0); gsl_test(sa, "gsl_sf_hermite_phys_array_der(1000, 100, 0.75)"); s += sa; sa = 0; gsl_sf_hermite_phys_array_der(23, 100, x, res); TEST_SF_VAL(sa, res[10], +0.0, 0.0, TEST_TOL0); TEST_SF_VAL(sa, res[37], +0.0, 1.930387357696033719818118732e46, TEST_TOL0); TEST_SF_VAL(sa, res[100], +0.0, 2.957966000491202678467161e118, TEST_TOL0); gsl_test(sa, "gsl_sf_hermite_phys_array(23, 37, 0.75)"); s += sa; sa = 0; gsl_sf_hermite_phys_der_array(100, 50, x, res); TEST_SF_VAL(sa, res[0], +0.0, -8.2663221830586310072686183e38, TEST_TOL0); TEST_SF_VAL(sa, res[10], +0.0, 1.52281030265187793605875604e49, TEST_TOL0); TEST_SF_VAL(sa, res[100], +0.0, 0.0, TEST_TOL0); gsl_test(sa, "gsl_sf_hermite_phys_der_array(100, 50, 0.75)"); s += sa; n = 128; /* arbitrary weights */ res[0] = 1.; for(m=1; m<=n; m++){ res[m] = res[m-1]/2.; } TEST_SF(s, gsl_sf_hermite_phys_series_e, (n, x, res, &r), 1.07772223811696567390619566842e88, TEST_TOL0, GSL_SUCCESS); x = 0.75; n = 28; TEST_SF(s, gsl_sf_hermite_func_e, (n, 0, &r), 0.290371943657199641200016132937, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_hermite_func_e, (n, x, &r), 0.23526280808621240649319140441, TEST_TOL0, GSL_SUCCESS); n = 100028; TEST_SF(s, gsl_sf_hermite_func_e, (n, x, &r), -0.02903467369856961147236598086, TEST_TOL4, GSL_SUCCESS); n = 10025; x = ((sqrt(2*n+1.)+aizero1/pow(8.*n,1/6.))/2.5); TEST_SF(s, gsl_sf_hermite_func_e, (n, x, &r), -0.05301278920004176459797680403, TEST_TOL4, GSL_SUCCESS); n = 10028; x = ((sqrt(2*n+1.)+aizero1/pow(8.*n,1/6.))/2.5); TEST_SF(s, gsl_sf_hermite_func_e, (n, x, &r), 0.06992968509693993526829596970, TEST_TOL3, GSL_SUCCESS); n = 10025; x = (sqrt(2*n+1.)-(aizero1/pow(8.*n,1/6.))/2.5); TEST_SF(s, gsl_sf_hermite_func_e, (n, x, &r), 0.08049000991742150521366671021, TEST_TOL4, GSL_SUCCESS); n = 10028; x = (sqrt(2*n+1.)-(aizero1/pow(8.*n,1/6.))/2.5); TEST_SF(s, gsl_sf_hermite_func_e, (n, x, &r), 0.08048800667512084252723933250, TEST_TOL4, GSL_SUCCESS); n = 10025; x = (sqrt(2*n+1.)-2.5*(aizero1/pow(8.*n,1/6.))); TEST_SF(s, gsl_sf_hermite_func_e, (n, x, &r), 7.97206830806663013555068100e-6, TEST_TOL4, GSL_SUCCESS); n = 10028; x = (sqrt(2*n+1.)-2.5*(aizero1/pow(8.*n,1/6.))); TEST_SF(s, gsl_sf_hermite_func_e, (n, x, &r), 7.97188517397786729928465829e-6, TEST_TOL4, GSL_SUCCESS); x = 0.75; sa = 0; gsl_sf_hermite_func_array(100, x, res); TEST_SF_VAL(sa, res[0], +0.0, 0.566979307027693616978839335983, TEST_TOL0); TEST_SF_VAL(sa, res[10], +0.0, 0.360329854170806945032958735574, TEST_TOL0); TEST_SF_VAL(sa, res[100], +0.0, -0.07616422890563462489003733382, TEST_TOL1); gsl_test(sa, "gsl_sf_hermite_func_array(100, 0.75)"); s += sa; n = 128; /* arbitrary weights */ res[0] = 1.; for(m=1; m<=n; m++){ res[m] = res[m-1]/2.; } TEST_SF(s, gsl_sf_hermite_func_series_e, (n, x, res, &r), 0.81717103529960997134154552556, TEST_TOL0, GSL_SUCCESS); m = 5; n = 28; TEST_SF(s, gsl_sf_hermite_func_der_e, (0, n, x, &r), 0.235262808086212406493191404, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_hermite_func_der_e, (m, n, x, &r), 4035.32788513029308540826835, TEST_TOL1, GSL_SUCCESS); { /* positive zeros of the probabilists' Hermite polynomial of order 17 */ double He17z[8] = { 0.751842600703896170737870774614, 1.50988330779674075905491513417, 2.28101944025298889535537879396, 3.07379717532819355851658337833, 3.90006571719800990903311840097, 4.77853158962998382710540812497, 5.74446007865940618125547815768,6.88912243989533223256205432938 }; n = 17; for (m=1; m<=n/2; m++) { TEST_SF(s, gsl_sf_hermite_prob_zero_e, (n, m, &r), He17z[m-1], TEST_TOL0, GSL_SUCCESS); } } { /* positive zeros of the probabilists' Hermite polynomial of order 18 */ double He18z[9] = { 0.365245755507697595916901619097, 1.09839551809150122773848360538, 1.83977992150864548966395498992, 2.59583368891124032910545091458, 3.37473653577809099529779309480, 4.18802023162940370448450911428, 5.05407268544273984538327527397, 6.00774591135959752029303858752, 7.13946484914647887560975631213 }; n = 18; for (m=1; m<=n/2; m++) { TEST_SF(s, gsl_sf_hermite_prob_zero_e, (n, m, &r), He18z[m-1], TEST_TOL0, GSL_SUCCESS); } } { /* positive zeros of the probabilists' Hermite polynomial of order 23 */ double He23z[11] = { 0.648471153534495816722576841197, 1.29987646830397886997876116860, 1.95732755293342410739100839243, 2.62432363405918177067330340783, 3.30504002175296456723204112903, 4.00477532173330406712238633738, 4.73072419745147329426707133987, 5.49347398647179412855289367747, 6.31034985444839982842886078177, 7.21465943505186138595859194492, 8.29338602741735258945596770157 }; n = 23; for (m=1; m<=n/2; m++) { TEST_SF(s, gsl_sf_hermite_prob_zero_e, (n, m, &r), He23z[m-1], TEST_TOL0, GSL_SUCCESS); } } { /* positive zeros of the probabilists' Hermite polynomial of order 24 */ double He24z[12] = { 0.317370096629452319318170455994, 0.953421922932109084904629632351, 1.59348042981642010695074168129, 2.24046785169175236246653790858, 2.89772864322331368932008199475, 3.56930676407356024709649151613, 4.26038360501990548884317727406, 4.97804137463912033462166468006, 5.73274717525120114834341822330, 6.54167500509863444148277523364, 7.43789066602166310850331715501, 8.50780351919525720508386233432 }; n = 24; for (m=1; m<=n/2; m++) { TEST_SF(s, gsl_sf_hermite_prob_zero_e, (n, m, &r), He24z[m-1], TEST_TOL0, GSL_SUCCESS); } } { /* positive zeros of the physicists' Hermite polynomial of order 17 */ double H17z[8] = { 0.531633001342654731349086553718, 1.06764872574345055363045773799, 1.61292431422123133311288254454, 2.17350282666662081927537907149, 2.75776291570388873092640349574, 3.37893209114149408338327069289, 4.06194667587547430689245559698, 4.87134519367440308834927655662 }; n = 17; for (m=1; m<=n/2; m++) { TEST_SF(s, gsl_sf_hermite_phys_zero_e, (n, m, &r), H17z[m-1], TEST_TOL0, GSL_SUCCESS); } } { /* positive zeros of the physicists' Hermite polynomial of order 18 */ double H18z[9] = { 0.258267750519096759258116098711, 0.776682919267411661316659462284, 1.30092085838961736566626555439, 1.83553160426162889225383944409, 2.38629908916668600026459301424, 2.96137750553160684477863254906, 3.57376906848626607950067599377, 4.24811787356812646302342016090, 5.04836400887446676837203757885 }; n = 18; for (m=1; m<=n/2; m++) { TEST_SF(s, gsl_sf_hermite_phys_zero_e, (n, m, &r), H18z[m-1], TEST_TOL0, GSL_SUCCESS); } } { /* positive zeros of the physicists' Hermite polynomial of order 23 */ double H23z[11] = { 0.458538350068104797757887329284, 0.919151465442563765431719239593, 1.38403958568249523732634717118, 1.85567703767137106251504753718, 2.33701621147445578644623502174, 2.83180378712615690144806140734, 3.34512715994122457247439814585, 3.88447270810610186607248760288, 4.46209117374000667673186157071, 5.10153461047667712968749766165, 5.86430949898457256538748413474 }; n = 23; for (m=1; m<=n/2; m++) { TEST_SF(s, gsl_sf_hermite_phys_zero_e, (n, m, &r), H23z[m-1], TEST_TOL0, GSL_SUCCESS); } } { /* positive zeros of the physicists' Hermite polynomial of order 24 */ double H24z[12] = { 0.224414547472515585151136715527, 0.674171107037212236000245923730, 1.12676081761124507213306126773, 1.58425001096169414850563336202, 2.04900357366169891178708399532, 2.52388101701142697419907602333, 3.01254613756556482565453858421, 3.52000681303452471128987227609, 4.05366440244814950394766297923, 4.62566275642378726504864923776, 5.25938292766804436743072304398, 6.01592556142573971734857350899 }; n = 24; for (m=1; m<=n/2; m++) { TEST_SF(s, gsl_sf_hermite_phys_zero_e, (n, m, &r), H24z[m-1], TEST_TOL0, GSL_SUCCESS); } } n = 2121; x = -1.*n; res[0] = (double) n; sa = 0; for (m=1; m<=n/2; m++) { gsl_sf_hermite_prob_zero_e(n, m, &r); if (x>=r.val) { sa += TEST_SF_INCONS; printf("sanity check failed! (gsl_sf_hermite_prob_zero)\n"); } res[0] = GSL_MIN(res[0],fabs(x-r.val)); x = r.val; } gsl_test(sa, "gsl_sf_hermite_prob_zero(n, m, r)"); n = 2121; x = -1.*n; res[0] = (double) n; sa = 0; for (m=1; m<=n/2; m++) { gsl_sf_hermite_phys_zero_e(n, m, &r); if (x>=r.val) { sa += TEST_SF_INCONS; printf("sanity check failed! (gsl_sf_hermite_phys_zero)\n"); } res[0] = GSL_MIN(res[0],fabs(x-r.val)); x = r.val; } gsl_test(sa, "gsl_sf_hermite_phys_zero(n, m, r)"); return s; }
{ "alphanum_fraction": 0.6430368051, "avg_line_length": 39.2762096774, "ext": "c", "hexsha": "fc35a42d6812140e49afacae09fedaa4f5bf0f3b", "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": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_forks_repo_path": "gsl-2.4/specfunc/test_hermite.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "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": "peterahrens/FillEstimationIPDPS2017", "max_issues_repo_path": "gsl-2.4/specfunc/test_hermite.c", "max_line_length": 126, "max_stars_count": null, "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_path": "gsl-2.4/specfunc/test_hermite.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 7920, "size": 19481 }
/* multiroots/convergence.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_multiroots.h> int gsl_multiroot_test_delta (const gsl_vector * dx, const gsl_vector * x, double epsabs, double epsrel) { size_t i; int ok = 1; const size_t n = x->size ; if (epsrel < 0.0) { GSL_ERROR ("relative tolerance is negative", GSL_EBADTOL); } for (i = 0 ; i < n ; i++) { double xi = gsl_vector_get(x,i); double dxi = gsl_vector_get(dx,i); double tolerance = epsabs + epsrel * fabs(xi) ; if (fabs(dxi) < tolerance) { ok = 1; } else { ok = 0; break; } } if (ok) return GSL_SUCCESS ; return GSL_CONTINUE; } int gsl_multiroot_test_residual (const gsl_vector * f, double epsabs) { size_t i; double residual = 0; const size_t n = f->size; if (epsabs < 0.0) { GSL_ERROR ("absolute tolerance is negative", GSL_EBADTOL); } for (i = 0 ; i < n ; i++) { double fi = gsl_vector_get(f, i); residual += fabs(fi); } if (residual < epsabs) { return GSL_SUCCESS; } return GSL_CONTINUE ; }
{ "alphanum_fraction": 0.6223880597, "avg_line_length": 22.0879120879, "ext": "c", "hexsha": "82ef6976df6a13438181804e29587859da0a5ddb", "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/multiroots/convergence.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/multiroots/convergence.c", "max_line_length": 72, "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/multiroots/convergence.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": 555, "size": 2010 }
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* ** ** ** This file forms part of the Underworld geophysics modelling application. ** ** ** ** For full license and copyright information, please refer to the LICENSE.md file ** ** located at the project root, or contact the authors. ** ** ** **~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/ /* Given a block system A x = b, or ( K G )(u) = (f) ( D C )(p) (h) We define a symmetrically scaled system, L A R R^-1 x = L b, A'x' = b' where L = diag(L1, 1), R = diag(R1,1) are block diagonal and L_i and R_i are both diagonal matrirces. The scaling produces ( L1 )( K G )( R1 )( R1 )^-1(u) = ( L1 )(f) Du + Cp = (h) and we solve ( L1 )( K G )( R1 )(v) = ( L1 )(f) Du + Cp = (h) or ( L1*K*R1, L1*G )(v) = (L1*f) ( D*R1 , C )(p) = ( h ) The solution u,p is recovered via (u) = (R1*v) (p) = (p) */ #include <petsc.h> #include <petscmat.h> #include <petscvec.h> #include <StGermain/libStGermain/src/StGermain.h> #include <StgDomain/libStgDomain/src/StgDomain.h> #include "common-driver-utils.h" #include "stokes_Kblock_scaling.h" /* private prototypes */ PetscErrorCode BSSCR_MatStokesKBlock_ApplyScaling( MatStokesBlockScaling BA, Mat A, Vec b, Vec x, Mat S, PetscTruth sym ); PetscErrorCode BSSCR_mat_kblock_invert_scalings( MatStokesBlockScaling BA ); /* A x = b -> A'x' = b' */ /* Note this routine actually modifies the matrix and rhs b. */ // updated PetscErrorCode BSSCR_MatStokesKBlock_ApplyScaling( MatStokesBlockScaling BA, Mat A, Vec b, Vec x, Mat S, PetscTruth sym ) { Mat K,G,D; Vec L1,R1; Vec f,u; /* Get the scalings out the block mat data */ VecNestGetSubVec( BA->Lz, 0, &L1 ); VecNestGetSubVec( BA->Rz, 0, &R1 ); /* get the subblock solution and rhs */ if( x != PETSC_NULL ) { VecNestGetSubVec( x, 0, &u ); VecPointwiseDivide( u, u,R1); /* x <- x * 1/R1 */ } if( b != PETSC_NULL ) { VecNestGetSubVec( b, 0, &f ); VecPointwiseMult( f, f,L1); /* f <- f * L1 */ } /* Scale matrices */ MatNestGetSubMat( A, 0,0, &K ); MatNestGetSubMat( A, 0,1, &G ); MatNestGetSubMat( A, 1,0, &D ); if( K != PETSC_NULL ) { MatDiagonalScale( K, L1,R1 ); } if( G != PETSC_NULL ) { MatDiagonalScale( G, L1,PETSC_NULL ); } if( D != PETSC_NULL && !sym ) { MatDiagonalScale( D, PETSC_NULL,R1 ); } PetscFunctionReturn(0); } // updated PetscErrorCode BSSCR_MatStokesKBlockScalingCreate( MatStokesBlockScaling *_BA ) { MatStokesBlockScaling BA; PetscErrorCode ierr; ierr = PetscMalloc( sizeof(struct _p_MatStokesBlockScaling), &BA );CHKERRQ(ierr); BA->Lz = PETSC_NULL; BA->Rz = PETSC_NULL; BA->scaling_exists = PETSC_FALSE; BA->scalings_have_been_inverted = PETSC_FALSE; BA->system_has_been_scaled = PETSC_FALSE; *_BA = BA; PetscFunctionReturn(0); } // updated PetscErrorCode BSSCR_MatStokesKBlockScalingDestroy( MatStokesBlockScaling BA ) { if( BA->scaling_exists == PETSC_FALSE ) PetscFunctionReturn(0); if( BA->Lz != PETSC_NULL ) { Stg_VecDestroy(&BA->Lz ); BA->Lz = PETSC_NULL; } if( BA->Rz != PETSC_NULL ) { Stg_VecDestroy(&BA->Rz ); BA->Rz = PETSC_NULL; } PetscFree( BA ); PetscFunctionReturn(0); } /* A is 2x2 block matrix b and x are 2x1 block vectors */ // updated PetscErrorCode BSSCR_MatKBlock_ConstructScaling( MatStokesBlockScaling BA, Mat A, Vec b, Vec x, PetscTruth sym ) { if( BA->scaling_exists == PETSC_FALSE ) { //PetscInt M,N; //PetscTruth is_block; /* check A is 2x2 block matrix */ /* Stg_PetscTypeCompare( (PetscObject)A, "block", &is_block ); */ /* if (is_block==PETSC_FALSE) { */ /* Stg_SETERRQ( PETSC_ERR_SUP, "Only valid for MatType = block" ); */ /* } */ /* MatGetSize( A, &M, &N ); */ /* if ( (M!=2) || (N!=2) ) { */ /* Stg_SETERRQ2( PETSC_ERR_SUP, "Only valid for 2x2 block. Yours has dimension %Dx%D", M,N ); */ /* } */ VecDuplicate( x, &BA->Lz ); VecDuplicate( x, &BA->Rz ); BA->scaling_exists = PETSC_TRUE; } // if( BA->user_build_scaling != PETSC_NULL ) { // BA->user_build_scaling( A,b,x,BA->scaling_ctx); // } // else { BSSCR_MatStokesKBlockDefaultBuildScaling(BA,A,b,x, sym); // } BA->scalings_have_been_inverted = PETSC_FALSE; PetscFunctionReturn(0); } // updated PetscErrorCode BSSCR_mat_kblock_invert_scalings( MatStokesBlockScaling BA ) { Vec L1,R1; VecNestGetSubVec( BA->Lz, 0, &L1 ); VecNestGetSubVec( BA->Rz, 0, &R1 ); VecReciprocal(L1); VecReciprocal(R1); /* toggle inversion flag */ if( BA->scalings_have_been_inverted == PETSC_TRUE ) { BA->scalings_have_been_inverted = PETSC_FALSE; } if( BA->scalings_have_been_inverted == PETSC_FALSE ) { BA->scalings_have_been_inverted = PETSC_TRUE; } PetscFunctionReturn(0); } /* updated */ PetscErrorCode BSSCR_MatStokesKBlockScaleSystem( MatStokesBlockScaling BA, Mat A, Vec b, Vec x, Mat S, PetscTruth sym ) { if( BA->scaling_exists == PETSC_FALSE ) { BSSCR_MatKBlock_ConstructScaling( BA,A,b,x, sym ); } if( BA->scalings_have_been_inverted == PETSC_TRUE ) { BSSCR_mat_kblock_invert_scalings(BA); /* to undo inversion */ } BSSCR_MatStokesKBlock_ApplyScaling(BA,A,b,x,S,sym); BA->system_has_been_scaled = PETSC_TRUE; /* PetscPrintf( PETSC_COMM_WORLD, "Post Scaling \n"); MatBlock_ReportOperatorScales(A); */ PetscFunctionReturn(0); } // updated PetscErrorCode BSSCR_MatStokesKBlockUnScaleSystem( MatStokesBlockScaling BA, Mat A, Vec b, Vec x, Mat S, PetscTruth sym ) { if( BA->system_has_been_scaled == PETSC_FALSE ) { printf("Warning: MatBlock has not been scaled !! \n"); PetscFunctionReturn(0); } if( BA->scalings_have_been_inverted == PETSC_FALSE ) { BSSCR_mat_kblock_invert_scalings(BA); } BSSCR_MatStokesKBlock_ApplyScaling(BA,A,b,x,S,sym); BA->system_has_been_scaled = PETSC_FALSE; PetscFunctionReturn(0); } PetscErrorCode BSSCR_MatStokesKBlockReportOperatorScales( Mat A, PetscTruth sym ) { Vec rA, rG; PetscInt loc; PetscReal min, max; Mat K,G,D,C; //PetscTruth is_block; /* check A is 2x2 block matrix */ /* Stg_PetscTypeCompare( (PetscObject)A, "block", &is_block ); */ /* if (is_block==PETSC_FALSE) { */ /* Stg_SETERRQ( PETSC_ERR_SUP, "Only valid for MatType = block" ); */ /* } */ /* MatGetSize( A, &M, &N ); */ /* if ( (M!=2) || (N!=2) ) { */ /* Stg_SETERRQ2( PETSC_ERR_SUP, "Only valid for 2x2 block. Yours has dimension %Dx%D", M,N ); */ /* } */ MatNestGetSubMat( A, 0,0, &K ); MatNestGetSubMat( A, 0,1, &G ); MatNestGetSubMat( A, 1,0, &D ); MatNestGetSubMat( A, 1,1, &C ); MatGetVecs( K, PETSC_NULL, &rA ); VecDuplicate( rA, &rG ); /* Report the row max and mins */ if (K!=PETSC_NULL) { MatGetRowMaxAbs( K, rA, PETSC_NULL ); VecMax( rA, &loc, &max ); PetscPrintf( PETSC_COMM_WORLD, "Sup_max(K) = %g \n", max ); MatGetRowMinAbs( K, rA, PETSC_NULL ); VecMin( rA, &loc, &min ); PetscPrintf( PETSC_COMM_WORLD, "Sup_min(K) = %g \n\n", min ); } if( G != PETSC_NULL ) { MatGetRowMaxAbs( G, rG, PETSC_NULL ); VecMax( rG, &loc, &max ); PetscPrintf( PETSC_COMM_WORLD, "Sup_max(G) = %g \n", max ); MatGetRowMinAbs( G, rG, PETSC_NULL ); VecMin( rG, &loc, &min ); PetscPrintf( PETSC_COMM_WORLD, "Sup_min(G) = %g \n", min ); } if( D != PETSC_NULL && !sym ) { Vec rD; MatGetVecs( D, PETSC_NULL, &rD ); MatGetRowMaxAbs( D, rD, PETSC_NULL ); VecMax( rD, &loc, &max ); PetscPrintf( PETSC_COMM_WORLD, "Sup_max(D) = %g \n", max ); MatGetRowMinAbs( D, rD, PETSC_NULL ); VecMin( rD, &loc, &min ); PetscPrintf( PETSC_COMM_WORLD, "Sup_min(D) = %g \n", min ); Stg_VecDestroy(&rD ); } if( C != PETSC_NULL ) { Vec cG; MatGetVecs( G, &cG, PETSC_NULL ); MatGetRowMaxAbs( C, cG, PETSC_NULL ); VecMax( cG, &loc, &max ); PetscPrintf( PETSC_COMM_WORLD, "Sup_max(C) = %g \n", max ); MatGetRowMinAbs( C, cG, PETSC_NULL ); VecMin( cG, &loc, &min ); PetscPrintf( PETSC_COMM_WORLD, "Sup_min(C) = %g \n\n", min ); Stg_VecDestroy(&cG); } Stg_VecDestroy(&rA ); Stg_VecDestroy(&rG ); PetscFunctionReturn(0); } // updated PetscErrorCode BSSCR_MatStokesKBlockDefaultBuildScaling( MatStokesBlockScaling BA, Mat A, Vec b, Vec x, PetscTruth sym ) { Mat K; Vec rA; Vec L1, R1; VecNestGetSubVec( BA->Lz, 0, &L1 ); VecNestGetSubVec( BA->Rz, 0, &R1 ); rA = L1; MatNestGetSubMat( A, 0,0, &K ); /* Get diag of K */ MatGetDiagonal( K, rA); VecSqrt( rA ); VecReciprocal( rA ); /* leave Shat alone as the Schur Compliment is unchanged by any consistent scaling of K */ //MatGetDiagonal( Shat, rC); //VecSqrt( rC ); //VecReciprocal( rC ); /* no scaling for pressure */ //VecSet( rC, 1.0 ); VecCopy( L1, R1 ); PetscFunctionReturn(0); }
{ "alphanum_fraction": 0.6166978742, "avg_line_length": 25.5746478873, "ext": "c", "hexsha": "3c2a658a72bc47c3bc89213e2d78206002ade27f", "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": "76991c475ac565e092e99a364370fbae15bb40ac", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "rbeucher/underworld2", "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/stokes_Kblock_scaling.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "rbeucher/underworld2", "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/stokes_Kblock_scaling.c", "max_line_length": 122, "max_stars_count": null, "max_stars_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "rbeucher/underworld2", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/stokes_Kblock_scaling.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3306, "size": 9079 }
#include <stdio.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_deriv.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include <gbpLib.h> #include <gbpInterpolate.h> double interpolate_integral(interp_info *interp, double x_lo, double x_hi) { double x_lo_interp; double x_hi_interp; double x_lo_tmp; double x_hi_tmp; double x_min; double x_max; double y_x_min; double y_x_max; double r_val; double alpha; int flag_error = GBP_FALSE; x_min = ((interp_info *)interp)->x[0]; x_max = ((interp_info *)interp)->x[((interp_info *)interp)->n - 1]; y_x_min = ((interp_info *)interp)->y[0]; y_x_max = ((interp_info *)interp)->y[((interp_info *)interp)->n - 1]; r_val = 0.; x_lo_interp = x_lo; x_hi_interp = x_hi; if(x_hi > x_lo) { // Extrapolate integral to low-x assuming dI prop. to x^alpha if(x_lo < x_min) { x_lo_tmp = x_lo; x_hi_tmp = GBP_MIN(x_hi, x_min); alpha = interpolate_derivative(interp, ((interp_info *)interp)->x[0]); if(alpha < -1. && x_lo_tmp * x_hi_tmp == 0.) { fprintf(stderr, "ERROR: integration extrapolation to low-x is divergent! (alpha=%lf)\n", alpha); flag_error = GBP_TRUE; } else r_val += (y_x_min / (alpha + 1.)) * (pow(x_hi_tmp / x_min, alpha + 1.) - pow(x_lo_tmp / x_min, alpha + 1.)); x_lo_interp = x_min; } // Extrapolate integral to high-x assuming dI prop. to x^alpha if(x_hi > x_max) { x_lo_tmp = GBP_MAX(x_max, x_lo); x_hi_tmp = x_hi; alpha = interpolate_derivative(interp, ((interp_info *)interp)->x[((interp_info *)interp)->n - 1]); if(alpha < 0. && x_lo_tmp * x_hi_tmp == 0.) { fprintf(stderr, "ERROR: integration extrapolation to high-x is divergent! (alpha=%lf)\n", alpha); flag_error = GBP_TRUE; } else r_val += (y_x_min / (alpha + 1.)) * (pow(x_hi_tmp / x_min, alpha + 1.) - pow(x_lo_tmp / x_min, alpha + 1.)); x_hi_interp = x_max; } r_val += gsl_interp_eval_integ(((interp_info *)interp)->interp, ((interp_info *)interp)->x, ((interp_info *)interp)->y, x_lo_interp, x_hi_interp, ((interp_info *)interp)->accel); } return (r_val); }
{ "alphanum_fraction": 0.5345160046, "avg_line_length": 38.1323529412, "ext": "c", "hexsha": "7da7dc8de0daae9ce48b63f5c8c655fda9d72a48", "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/interpolate_integral.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/interpolate_integral.c", "max_line_length": 124, "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/interpolate_integral.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": 683, "size": 2593 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <limits.h> #include <getopt.h> #include <mpi.h> #include "compearth.h" #include "parmt_utils.h" #ifdef PARMT_USE_INTEL #include <mkl_cblas.h> #else #include <cblas.h> #endif #include "parmt_polarity.h" #include "parmt_postProcess.h" #include "parmt_mtsearch.h" #include "iscl/array/array.h" #include "iscl/memory/memory.h" #include "iscl/os/os.h" #define PROGRAM_NAME "postmt" #define OUTDIR "postprocess" #define WAVOUT_DIR "obsest" static int parseArguments(int argc, char *argv[], char iniFile[PATH_MAX]); static void printUsage(void); int parmt_freeData(struct parmtData_struct *data); int main(int argc, char *argv[]) { struct parmtGeneralParms_struct parms; struct parmtData_struct data; struct parmtPolarityParms_struct polarityParms; struct polarityData_struct polarityData; FILE *ofl; char fname[PATH_MAX]; char iniFile[PATH_MAX]; char programNameIn[256]; bool lpol; double U[9], Muse[6], Mned[6], lam[3], *betas, *deps, *depMPDF, *depMagMPDF, *G, *gammas, *kappas, *sigmas, *thetas, *M0s, *phi, *var, dip, epoch, lagTime, Mw, phiLoc, xnorm, xsum; int ierr, iobs, imtopt, jb, jg, jk, jloc, jm, joptLoc, js, jt, k, lag, myid, nb, ng, nk, nlags, nlocs, nm, nmt, npmax, npts, nprocs, ns, nt, provided; bool ldefault; // Start MPI MPI_Init_thread(&argc, &argv, MPI_THREAD_FUNNELED, &provided); MPI_Comm_rank(MPI_COMM_WORLD, &myid); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); // Initialize depMPDF = NULL; depMagMPDF = NULL; betas = NULL; deps = NULL; gammas = NULL; kappas = NULL; sigmas = NULL; thetas = NULL; M0s = NULL; phi = NULL; memset(&parms, 0, sizeof(struct parmtGeneralParms_struct)); memset(&data, 0, sizeof(struct parmtData_struct)); memset(&polarityParms, 0, sizeof(struct parmtPolarityParms_struct)); memset(&polarityData, 0, sizeof(struct polarityData_struct)); // Parse the input arguments ierr = parseArguments(argc, argv, iniFile); if (ierr != 0) { if (ierr ==-2){return 0;} printf("%s: Error parsing arguments\n", PROGRAM_NAME); return EXIT_FAILURE; } // Load the ini file - from this we should be able to deduce the archive ierr = parmt_utils_readGeneralParms(iniFile, &parms); if (ierr != 0) { printf("%s: Error reading general parameters\n", PROGRAM_NAME); return EXIT_FAILURE; } if (!os_path_isfile(parms.postmtFile)) { printf("%s: Archive file %s doesn't exist\n", PROGRAM_NAME, parms.postmtFile); return EXIT_FAILURE; } ierr += parmt_utils_readPolarityParms(iniFile, &polarityParms); // TODO make this a config if (!os_path_isdir(OUTDIR)) { os_makedirs(OUTDIR); } if (!os_path_isdir(WAVOUT_DIR)) { os_makedirs(WAVOUT_DIR); } // Load the data printf("%s: Reading data...\n", PROGRAM_NAME); ierr = utils_dataArchive_readAllWaveforms(parms.dataFile, &data); if (ierr != 0) { printf("%s: Error reading data\n", PROGRAM_NAME); goto ERROR; } data.est = (struct sacData_struct *) calloc((size_t) data.nobs, sizeof(struct sacData_struct)); // Read the archive printf("%s: Reading archive %s...\n", PROGRAM_NAME, parms.postmtFile); printf("%s %s %s\n", parms.resultsDir, parms.projnm, parms.resultsFileSuffix); ierr = parmt_io_readObjfnArchive64f( //parms.resultsDir, parms.projnm, parms.resultsFileSuffix, parms.postmtFile, //parms.parmtArchive, programNameIn, &nlocs, &deps, &nm, &M0s, &nb, &betas, &ng, &gammas, &nk, &kappas, &ns, &sigmas, &nt, &thetas, &nmt, &phi); if (ierr != 0) { printf("%s: Error loading archive\n", PROGRAM_NAME); goto ERROR; } /* double *phi1; ierr = parmt_io_readObjfnArchive64f( "bw", parms.projnm, "bodyWaves", &nlocs, &deps, &nm, &M0s, &nb, &betas, &ng, &gammas, &nk, &kappas, &ns, &sigmas, &nt, &thetas, &nmt, &phi1); for (int imt=0; imt<nmt; imt++) { phi[imt] = (12.0*phi1[imt] + 11*phi[imt]); } ierr = parmt_io_createObjfnArchive64f("joint", parms.projnm, "joint", 25, //data.nobs, nlocs, deps, nm, M0s, nb, betas, ng, gammas, nk, kappas, ns, sigmas, nt, thetas); ierr = parmt_io_writeObjectiveFunction64f( "joint", parms.projnm, "joint", nmt, phi); return 0; */ // Get the optimum moment tensor for the waveforms ierr = marginal_getOptimum(nlocs, nm, nb, ng, nk, ns, nt, phi, &jloc, &jm, &jb, &jg, &jk, &js, &jt); if (ierr != 0) { printf("%s: Failed to get optimum\n", PROGRAM_NAME); goto ERROR; } imtopt = jloc*nm*nb*ng*nk*ns*nt + jm*nb*ng*nk*ns*nt + jb*ng*nk*ns*nt + jg*nk*ns*nt + jk*ns*nt + js*nt + jt; //printf("%d %e\n", jm, M0s[jm]); //getchar(); compearth_m02mw(1, CE_KANAMORI_1978, &M0s[jm], &Mw); joptLoc = jloc; //printf("%d %d %d %d %d %d %d\n", jloc, jm, jg, jb, jk, js, jt); //jloc =4; jm = 5; jg =1; jb=0; jk=11; js=2; jt=4; printf("%s: Optimum information:\n", PROGRAM_NAME); printf(" Value: %f\n", phi[imtopt]); printf(" Depth: %f (km)\n", deps[jloc]); printf(" Magnitude: %f\n", Mw); printf(" Lune longitude: %f (deg)\n", gammas[jg]*180.0/M_PI); printf(" Lune latitude: %f (deg)\n", (M_PI_2 - betas[jb])*180.0/M_PI); printf(" Strike: %f (deg)\n", kappas[jk]*180.0/M_PI); printf(" Slip: %f (deg)\n", sigmas[js]*180.0/M_PI); printf(" Dip: %f (deg)\n", thetas[jt]*180.0/M_PI); // Display the moment tensor in USE format which is useful for obspy and gmt double gammaOpt = gammas[jg]*180.0/M_PI; double deltaOpt = 90.0-betas[jb]*180.0/M_PI; double kappaOpt = kappas[jk]*180.0/M_PI; double thetaOpt = thetas[jt]*180.0/M_PI; double sigmaOpt = sigmas[js]*180.0/M_PI; compearth_TT2CMT(1, &gammaOpt, &deltaOpt, &M0s[jm], &kappaOpt, &thetaOpt, &sigmaOpt, Muse, lam, U); /* compearth_tt2cmt(gammas[jg]*180.0/M_PI, (M_PI/2.0 - betas[jb])*180.0/M_PI, M0s[jm], kappas[jk]*180.0/M_PI, thetas[jt]*180.0/M_PI, sigmas[js]*180.0/M_PI, Muse, lam, U); */ /* Muse[0] = 28200000000000000.; // mrr Muse[1] = 283100000000000000.; // mtt Muse[2] =-311300000000000000.; // mpp Muse[3] =-243300000000000000.; // mrt Muse[4] =-149900000000000000.; // mrp Muse[5] = 467500000000000000.; // mtp compearth_convertMT(1, CE_USE, CE_NED, Muse, Mned); */ ierr = parmt_discretizeMT64f(1, &gammas[jg], 1, &betas[jb], 1, &M0s[jm], 1, &kappas[jk], 1, &thetas[jt], 1, &sigmas[js], 6, 1, Mned); printf("mtUSE =[%.6e,%.6e,%.6e,%.6e,%.6e,%.6e]\n", Muse[0], Muse[1], Muse[2], Muse[3], Muse[4], Muse[5]); printf("mtNED =[%.6e,%.6e,%.6e,%.6e,%.6e,%.6e]\n", Mned[0], Mned[1], Mned[2], Mned[3], Mned[4], Mned[5]); //printf("%e\n", M0s[jm]); //compearth_CMT2m0(1, 1, Mned, &M0s[jm]); //printf("%e\n", M0s[jm]); //getchar(); // Compute the polarities lpol = true; ierr = parmt_polarity_computeTTimesGreens(MPI_COMM_WORLD, polarityParms, data, &polarityData); if (ierr != 0) { printf("%s: Error computing polarity Green's functions\n", PROGRAM_NAME); ierr = 1; lpol = false; } if (lpol && polarityData.nPolarity > 0) { double *Gpol = memory_calloc64f(6*polarityData.nPolarity); double *est = memory_calloc64f(polarityData.nPolarity); double phiPol; int ipol, kt; kt = jloc*polarityData.nPolarity; printf("G\n"); for (ipol=0; ipol<polarityData.nPolarity; ipol++) { Gpol[6*ipol+0] = polarityData.Gxx[kt+ipol]; Gpol[6*ipol+1] = polarityData.Gyy[kt+ipol]; Gpol[6*ipol+2] = polarityData.Gzz[kt+ipol]; Gpol[6*ipol+3] = polarityData.Gxy[kt+ipol]; Gpol[6*ipol+4] = polarityData.Gxz[kt+ipol]; Gpol[6*ipol+5] = polarityData.Gyz[kt+ipol]; printf("%f %f %f %f %f %f\n", Gpol[6*ipol+0], Gpol[6*ipol+1], Gpol[6*ipol+2], Gpol[6*ipol+3], Gpol[6*ipol+4], Gpol[6*ipol+5]); } cblas_dgemv(CblasRowMajor, CblasNoTrans, polarityData.nPolarity, 6, 1.0, Gpol, 6, Mned, 1, 0.0, est, 1); for (ipol=0; ipol<polarityData.nPolarity; ipol++) { est[ipol] = copysign(1.0, est[ipol]); printf("Polarity: obs %f; est %f\n", polarityData.polarity[ipol], est[ipol]); } } // Write the output file struct globalMapOpts_struct globalMap; memset(&globalMap, 0, sizeof(struct globalMapOpts_struct)); strcpy(globalMap.outputScript, "gmtScripts/globalMap.sh"); strcpy(globalMap.psFile, "globalMap.ps"); array_copy64f_work(6, Muse, globalMap.mts); globalMap.basis = CE_USE; globalMap.evla = data.data[0].header.evla; globalMap.evlo = data.data[0].header.evlo; globalMap.evdp = deps[jloc]; globalMap.lwantMT = true; globalMap.lwantPolarity = true; printf("%f %f\n", globalMap.mts[0], globalMap.mts[1]); ierr = postmt_gmtHelper_writeGlobalMap(globalMap, data.nobs, data.data); /* printf("overriding ned and joptloc\n"); joptLoc=5; Mned[0] = 8.526325e+15; Mned[1] =-8.707938e+16; Mned[2] = 2.226786e+17; Mned[3] =-5.768950e+17; Mned[4] =-3.469420e+17; Mned[5] =-2.756277e+17; */ // Compute the scaling factor xnorm = marginal_computeNormalization(nlocs, deps, nm, M0s, nb, betas, ng, gammas, nk, kappas, ns, sigmas, nt, thetas, phi, &ierr); if (xnorm <= 0.0 || ierr != 0) { printf("%s: Failed to compute normalization factor - setting to 1\n", PROGRAM_NAME); ierr = 0; xnorm = 1.0; } printf("%s: Scaling factor: %e\n", PROGRAM_NAME, xnorm); cblas_dscal(nmt, 1.0/xnorm, phi, 1); printf("%s: Computing pure histograms\n", PROGRAM_NAME); double *locHist, *magHist, *betaHist, *gammaHist, *kappaHist, *sigmaHist, *thetaHist; ierr = postmt_gmtHelper_makeRegularHistograms(nlocs, nm, nb, ng, nk, ns, nt, nmt, phi, &locHist, &magHist, &betaHist, &gammaHist, &kappaHist, &sigmaHist, &thetaHist); int i; /* printf("Depths\n"); for (i=0; i<nlocs; i++) { printf("%f %f\n", deps[i], locHist[i]); } printf("Magnitudes\n"); for (i=0; i<nm; i++) { compearth_m02mw(1, CE_KANAMORI_1978, &M0s[i], &Mw); printf("%f %f\n", Mw, magHist[i]); } printf("Gammas\n"); for (i=0; i<ng; i++) { printf("%f %f\n", gammas[i]*180.0/M_PI, gammaHist[i]); } */ printf("Betas\n"); for (i=0; i<nb; i++) { printf("%f %f\n", 90.0 - betas[i]*180.0/M_PI, betaHist[i]); } /* printf("Kappas\n"); for (i=0; i<nk; i++) { printf("%f %f\n", kappas[i]*180.0/M_PI, kappaHist[i]); } printf("Sigmas\n"); for (i=0; i<ns; i++) { printf("%f %f\n", sigmas[i]*180.0/M_PI, sigmaHist[i]); } printf("Thetas\n"); for (i=0; i<nt; i++) { printf("%f %f\n", thetas[i]*180.0/M_PI, thetaHist[i]); } */ const char *scriptFile = "gmtScripts/boxes.sh"; const char *psFile = "boxes.ps"; ierr = postmt_gmtHelper_writeBetaBoxes(false, false, scriptFile, psFile, nb, jb, betas, betaHist); ierr = postmt_gmtHelper_writeGammaBoxes(true, false, scriptFile, psFile, ng, jg, gammas, gammaHist); ierr = postmt_gmtHelper_writeKappaBoxes(true, false, scriptFile, psFile, nk, jk, kappas, kappaHist); ierr = postmt_gmtHelper_writeSigmaBoxes(true, false, scriptFile, psFile, ns, js, sigmas, sigmaHist); ierr = postmt_gmtHelper_writeThetaBoxes(true, false, scriptFile, psFile, nt, jt, thetas, thetaHist); ierr = postmt_gmtHelper_writeMagnitudeBoxes(true, false, scriptFile, psFile, nm, jm, M0s, magHist); ierr = postmt_gmtHelper_writeDepthBoxes(true, true, scriptFile, psFile, nlocs, joptLoc, deps, locHist); // Start the post-processing - compute the depgh magnitude mPDFs printf("%s: Computing the depth MPDF's\n", PROGRAM_NAME); depMagMPDF = memory_calloc64f(nm*nlocs); depMPDF = memory_calloc64f(nlocs); ierr = marginal_computeDepthMPDF(nlocs, nm, M0s, nb, betas, ng, gammas, nk, kappas, ns, sigmas, nt, thetas, phi, depMagMPDF, depMPDF); if (ierr != 0) { printf("%s: Error computing depthMPDF\n", PROGRAM_NAME); goto ERROR; } // Print the station list for my edification for (k=0; k<data.nobs; k++) { printf("%8.3f %8.3f %6s\n", data.data[k].header.stlo, data.data[k].header.stla, data.data[k].header.kstnm); } int im, iloc; for (im=0; im<nm; im++) { compearth_m02mw(1, CE_KANAMORI_1978, &M0s[im], &Mw); printf("Writing magnitude: %f\n", Mw); memset(fname, 0, PATH_MAX*sizeof(char)); sprintf(fname, "%s/%s_dep.%d.txt", OUTDIR, parms.projnm, im+1); ofl = fopen(fname, "w"); for (iloc=0; iloc<nlocs; iloc++) { jloc = im*nlocs + iloc; fprintf(ofl, "%e %e\n", deps[iloc], depMagMPDF[jloc]); } fclose(ofl); } memset(fname, 0, PATH_MAX*sizeof(char)); sprintf(fname, "%s/%s_dep.txt", OUTDIR, parms.projnm); ofl = fopen(fname, "w"); for (iloc=0; iloc<nlocs; iloc++) { fprintf(ofl, "%e %e\n", deps[iloc], depMPDF[iloc]); } fclose(ofl); // Compute the optimal synthetics xsum = 0.0; for (iobs=0; iobs<data.nobs; iobs++) { // Extract the depth waveform npts = data.data[iobs].npts; npmax = npts; G = memory_calloc64f(6*npmax); var = memory_calloc64f(npmax); ierr = parmt_utils_setDataOnG(iobs, joptLoc, npmax, data, G); if (ierr != 0) { printf("%s: Failed to set data on G\n", PROGRAM_NAME); goto ERROR; } // Compute the lag time nlags = 0; lag = 0; if (parms.lwantLags) { //lagTime = data.data[iobs].header.user0; //if (lagTime < 0.0){lagTime = parms.defaultMaxLagTime;} lagTime = parmt_utils_getLagTime(data.data[iobs], parms.defaultMaxLagTime, &ldefault); nlags = (int) (lagTime/data.data[iobs].header.delta + 0.5); } ierr = parmt_mtSearchL164f(6, 1, npts, 1, nlags, parms.lwantLags, parms.lrescale, &G[0*npmax], &G[1*npmax], &G[2*npmax], &G[3*npmax], &G[4*npmax], &G[5*npmax], NULL, Mned, data.data[iobs].data, &phiLoc, var, &lag); if (ierr != 0) { printf("%s: Error computing lags for waveform %d\n", PROGRAM_NAME, iobs); goto ERROR; } // Compute the synthetic k = iobs*data.nlocs + joptLoc; parmt_utils_sacGrnsToEst(data.data[iobs], data.sacGxx[k], data.sacGyy[k], data.sacGzz[k], data.sacGxy[k], data.sacGxz[k], data.sacGyz[k], Mned, parms.lrescale, &data.est[iobs]); // Fix the timing ierr = sacio_getEpochalStartTime(data.est[iobs].header, &epoch); epoch = epoch + (double) lag*data.data[iobs].header.delta; sacio_setEpochalStartTime(epoch, &data.est[iobs].header); // Write the file memset(fname, 0, PATH_MAX*sizeof(char)); sprintf(fname, "%s/%s.%s.%s.%s.SAC", WAVOUT_DIR, data.data[iobs].header.knetwk, data.data[iobs].header.kstnm, data.data[iobs].header.kcmpnm, data.data[iobs].header.khole); sacio_writeTimeSeriesFile(fname, data.data[iobs]); memset(fname, 0, PATH_MAX*sizeof(char)); sprintf(fname, "%s/%s.%s.%s.%s.EST.SAC", WAVOUT_DIR, data.data[iobs].header.knetwk, data.data[iobs].header.kstnm, data.data[iobs].header.kcmpnm, data.data[iobs].header.khole); sacio_writeTimeSeriesFile(fname, data.est[iobs]); printf("Waveform %6s has lag %+4d=%+8.3e (s) and a fit of %f\n", data.data[iobs].header.kstnm, lag, lag*data.data[iobs].header.delta, phiLoc); memory_free64f(&G); memory_free64f(&var); xsum = xsum + phiLoc; } printf("Average %f\n", xsum/(double) data.nobs ); /* double *db = memory_calloc64f(nb); double *dg = memory_calloc64f(ng); double *dt = memory_calloc64f(nt); postprocess_computeBetaCellSpacing(nb, betas, db); printf("\n"); postprocess_computeGammaCellSpacing(ng, gammas, dg); printf("\n"); postprocess_computeThetaCellSpacing(nt, thetas, dt); */ // Free memory ERROR:; parmt_freeData(&data); memory_free64f(&depMagMPDF); memory_free64f(&depMPDF); memory_free64f(&deps); memory_free64f(&M0s); memory_free64f(&betas); memory_free64f(&gammas); memory_free64f(&kappas); memory_free64f(&sigmas); memory_free64f(&thetas); memory_free64f(&phi); iscl_finalize(); MPI_Finalize(); return ierr; } //============================================================================// /*! * @brief Parses the input arguments to get the ini file anme */ static int parseArguments(int argc, char *argv[], char iniFile[PATH_MAX]) { bool linFile; memset(iniFile, 0, PATH_MAX*sizeof(char)); while (true) { static struct option longOptions[] = { {"help", no_argument, 0, '?'}, {"help", no_argument, 0, 'h'}, {"ini_file", required_argument, 0, 'i'}, {0, 0, 0, 0} }; int c, optionIndex; c = getopt_long(argc, argv, "?hi:", longOptions, &optionIndex); if (c ==-1){break;} if (c == 'i') { strcpy(iniFile, (const char *) optarg); linFile = true; } else if (c == 'h' || c == '?') { printUsage(); return -2; } else { printf("%s: Unknown options: %s\n", PROGRAM_NAME, argv[optionIndex]); } } if (!linFile) { printf("%s: Error must specify ini file\n\n", PROGRAM_NAME); printUsage(); return -1; } return 0; } static void printUsage(void) { printf("Usage:\n postmt -i input_file\n\n"); printf("Required arguments:\n"); printf(" -i input_file specifies the initialization file\n"); printf("\n"); printf("Optional arguments:\n"); printf(" -h displays this message\n"); return; } int parmt_freeData(struct parmtData_struct *data) { int i; if (data->nobs > 0 && data->nlocs > 0 && data->sacGxx != NULL && data->sacGyy != NULL && data->sacGzz != NULL && data->sacGxy != NULL && data->sacGxz != NULL && data->sacGyz != NULL) { for (i=0; i<data->nobs*data->nlocs; i++) { sacio_freeData(&data->sacGxx[i]); sacio_freeData(&data->sacGyy[i]); sacio_freeData(&data->sacGzz[i]); sacio_freeData(&data->sacGxy[i]); sacio_freeData(&data->sacGxz[i]); sacio_freeData(&data->sacGyz[i]); } free(data->sacGxx); free(data->sacGyy); free(data->sacGzz); free(data->sacGxy); free(data->sacGxz); free(data->sacGyz); } if (data->nobs > 0 && data->data != NULL) { for (i=0; i<data->nobs; i++) { sacio_freeData(&data->data[i]); } free(data->data); } if (data->nobs > 0 && data->est != NULL) { free(data->est); } memset(data, 0, sizeof(struct parmtData_struct)); return 0; }
{ "alphanum_fraction": 0.5020253495, "avg_line_length": 35.650621118, "ext": "c", "hexsha": "acf976e353614f8f9e920165766ccfb3a8a3b170", "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": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_forks_repo_licenses": [ "Intel" ], "max_forks_repo_name": "bakerb845/parmt", "max_forks_repo_path": "postprocess/postmt.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Intel" ], "max_issues_repo_name": "bakerb845/parmt", "max_issues_repo_path": "postprocess/postmt.c", "max_line_length": 89, "max_stars_count": null, "max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_stars_repo_licenses": [ "Intel" ], "max_stars_repo_name": "bakerb845/parmt", "max_stars_repo_path": "postprocess/postmt.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6514, "size": 22959 }
/** \file LinkFunc.h * * `IRLS' is a C++ implementation of the IRLS algorithm for GLM * Copyright (C) 2013 Xioaquan Wen, Timothee Flutre * * 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, see <http://www.gnu.org/licenses/>. */ #ifndef _LINKFUNC_H_ #define _LINKFUNC_H_ #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> class LinkFunc { public: bool quasi; virtual void init_mv(gsl_vector * Y, gsl_vector * mv)=0; virtual void compute_z(gsl_vector * y, gsl_vector * mv, gsl_vector * offset, gsl_vector * z)=0; virtual void compute_weights(gsl_vector * mv, gsl_vector * w)=0; virtual void compute_mv(gsl_vector * bv, gsl_matrix * Xv, gsl_vector * offset, gsl_vector * mv)=0; virtual double compute_dispersion(gsl_vector * y, gsl_matrix * Xv, gsl_vector * bv, gsl_vector * offset, gsl_vector * mv, double rank, bool quasi_lik)=0; virtual ~LinkFunc() {}; }; // LinkFunc #endif // _LINKFUNC_H_
{ "alphanum_fraction": 0.7252673797, "avg_line_length": 33.2444444444, "ext": "h", "hexsha": "ca2e04827cd50faa4008a744122e18a28b156f4b", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-05-07T02:16:27.000Z", "max_forks_repo_forks_event_min_datetime": "2020-10-15T09:15:46.000Z", "max_forks_repo_head_hexsha": "3b1c7797bfdf0f7d3330339ace0929e8e2225a40", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Lan-lab/Chrom-Lasso-", "max_forks_repo_path": "Code/IRLS_glm/LinkFunc.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "3b1c7797bfdf0f7d3330339ace0929e8e2225a40", "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": "Lan-lab/Chrom-Lasso-", "max_issues_repo_path": "Code/IRLS_glm/LinkFunc.h", "max_line_length": 70, "max_stars_count": null, "max_stars_repo_head_hexsha": "3b1c7797bfdf0f7d3330339ace0929e8e2225a40", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Lan-lab/Chrom-Lasso-", "max_stars_repo_path": "Code/IRLS_glm/LinkFunc.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 392, "size": 1496 }
/******************************************************************************* NAME: diffimage ALGORITHM DESCRIPTION: Calculates statistics in each input file Calculates PSNR between the two input files Performs an fftMatch between the two input files Checks for differences in stats, a PSNR that is too low, and for shifts in geolocation ISSUES: The images must have at least 75% overlap. diffimage will occasionally fail to find the correct offset especially with noisy images or images with flat topography (low non-noise spatial frequency.) *******************************************************************************/ #include "asf.h" #include "asf_nan.h" #include <unistd.h> #include <math.h> #include <ctype.h> #include "fft.h" #include "fft2d.h" #include "ddr.h" #include "asf_raster.h" #include "typlim.h" #include "float_image.h" #include "uint8_image.h" #include "proj.h" #include "libasf_proj.h" #include "asf_jpeg.h" #include "asf_tiff.h" #include "geo_tiffp.h" #include "geo_keyp.h" #include <png.h> #include <gsl/gsl_math.h> #include "diffimage_tolerances.h" #include "geotiff_support.h" #include "asf_complex.h" #ifndef png_jmpbuf # define png_jmpbuf (png_ptr) ((png_ptr)->jmpbuf) #endif #define FLOAT_COMPARE_TOLERANCE(a, b, t) (fabs (a - b) <= t ? 1: 0) #define FLOAT_TOLERANCE 0.000001 #define FLOAT_EQUIVALENT2(a, b) (FLOAT_COMPARE_TOLERANCE \ (a, b, FLOAT_TOLERANCE)) #define MISSING_PSNR -32000 #define CORR_FILE "tmp_corr" #define MISSING_TIFF_DATA -1 typedef struct { uint32 width; uint32 height; short sample_format; short bits_per_sample; short planar_config; data_type_t data_type; // ASF data type short num_bands; int is_scanline_format; int is_palette_color_tiff; } tiff_data_t; #define MISSING_PNG_DATA -1 typedef struct { uint32 width; uint32 height; int bit_depth; int color_type; // Defined by PNG lib char color_type_str[64]; // Human-readable color type desc. int interlace_type; int compression_type; int filter_type; data_type_t data_type; // ASF data type int num_bands; } png_info_t; #define MISSING_PPM_PGM_DATA -1 typedef struct { char magic[2]; uint32 width; uint32 height; uint32 max_val; // May be 255 or less int ascii_data; uint32 img_offset; // Just past header int bit_depth; // Should only be 8-bits per element data_type_t data_type; // ASF data type int num_bands; // 1 or 3 } ppm_pgm_info_t; #define MISSING_JPEG_DATA -1 typedef struct { struct jpeg_error_mgr pub; jmp_buf setjmp_buffer; } jpeg_error_hdlr_t; typedef jpeg_error_hdlr_t *jpeg_err_hdlr; #define MISSING_GTIF_DATA -1 typedef struct { int gtif_data_exists; char *GTcitation; char *PCScitation; int tie_point_elements; // Number of tie point elements (usually a multiple of 6) int num_tie_points; // Number of elements divided by 6 since (i,j,k) maps to (x,y,z) double *tie_point; // Usually only 1, but who knows what evil lurks in the hearts of men? int pixel_scale_elements; // Usually a multiple of 3 int num_pixel_scales; double *pixel_scale; // Should always be 3 of these ...for ScaleX, ScaleY, and ScaleZ short model_type; short raster_type; short linear_units; double scale_factor; datum_type_t datum; char hemisphere; unsigned long pro_zone; // UTM zone (UTM only) short proj_coords_trans; short pcs; short geodetic_datum; short geographic_datum; double false_easting; double false_northing; double natLonOrigin; double lonCenter; double falseOriginLon; double falseOriginLat; double natLatOrigin; double latCenter; double stdParallel1; double stdParallel2; double lonPole; } geotiff_data_t; /**** PROTOTYPES ****/ void usage(char *name); void msg_out(FILE *fpLog, int quiet, char *msg); void err_out(FILE *fpError, int quiet, char *msg); int asf_img_file_found(char *file); graphics_file_t getGraphicsFileType (char *file); void graphicsFileType_toStr (graphics_file_t type, char *type_str); void fftDiff(char *inFile1, char *inFile2, float *bestLocX, float *bestLocY, float *certainty); float get_maxval(data_type_t data_type); void calc_asf_img_stats_2files(char *inFile1, char *inFile2, stats_t *inFile1_stats, stats_t *inFile2_stats, psnr_t *psnr, int band); void calc_ppm_pgm_stats_2files(char *inFile1, char *inFile2, char *outfile, stats_t *inFile1_stats, stats_t *inFile2_stats, psnr_t *psnr, int band); void calc_jpeg_stats_2files(char *inFile1, char *inFile2, char *outfile, stats_t *inFile1_stats, stats_t *inFile2_stats, psnr_t *psnr, int band); void calc_tiff_stats_2files(char *inFile1, char *inFile2, stats_t *inFile1_stats, stats_t *inFile2_stats, psnr_t *psnr, int band); void calc_png_stats_2files(char *inFile1, char *inFile2, char *outfile, stats_t *inFile1_stats, stats_t *inFile2_stats, psnr_t *psnr, int band); void print_stats_results(char *filename1, char *filename2, char *band_str1, char *band_str2, stats_t *s1, stats_t *s2, psnr_t psnr); void diff_check_stats(char *outputFile, char *inFile1, char *inFile2, stats_t *stats1, stats_t *stats2, psnr_t *psnr, int strict, data_type_t t, int num_bands); void diff_check_geotiff(char *outfile, geotiff_data_t *g1, geotiff_data_t *g2); void diff_check_geolocation(char *outputFile, char *inFile1, char *inFile2, int num_bands, shift_data_t *shift, stats_t *stats1, stats_t *stats2); void diffErrOut(char *outputFile, char *err_msg); void get_tiff_info_from_file(char *file, tiff_data_t *t); void get_tiff_info(TIFF *tif, tiff_data_t *t); void get_geotiff_keys(char *file, geotiff_data_t *g); void projection_type_2_str(projection_type_t proj, char *proj_str); int tiff_image_band_statistics_from_file(char *inFile, int band_no, int *stats_exist, double *min, double *max, double *mean, double *sdev, double *rmse, int use_mask_value, float mask_value); void tiff_image_band_psnr_from_files(char *inFile1, char *inFile2, int band1, int band2, psnr_t *psnr); float tiff_image_get_float_pixel(TIFF *tif, int row, int col, int band_no); void tiff_get_float_line(TIFF *tif, float *buf, int row, int band_no); void get_png_info_hdr_from_file(char *inFile, png_info_t *ihdr1, char *outfile); int png_image_band_statistics_from_file(char *inFile, char *outfile, int band_no, int *stats_exist, double *min, double *max, double *mean, double *sdev, double *rmse, int use_mask_value, float mask_value); void png_image_band_psnr_from_files(char *inFile1, char *inFile2, char *outfile, int band1, int band2, psnr_t *psnr); void png_sequential_get_float_line(png_structp png_ptr, png_infop info_ptr, float *buf, int band); void get_ppm_pgm_info_hdr_from_file(char *inFile, ppm_pgm_info_t *pgm, char *outfile); void ppm_pgm_get_float_line(FILE *fp, float *buf, int row, ppm_pgm_info_t *pgm, int band_no); int ppm_pgm_image_band_statistics_from_file(char *inFile, char *outfile, int band_no, int *stats_exist, double *min, double *max, double *mean, double *sdev, double *rmse, int use_mask_value, float mask_value); void ppm_pgm_image_band_psnr_from_files(char *inFile1, char *inFile2, char *outfile, int band1, int band2, psnr_t *psnr); void get_band_names(char *inFile, FILE *outputFP, char ***band_names, int *num_extracted_bands); void free_band_names(char ***band_names, int num_extracted_bands); METHODDEF(void) jpeg_err_exit(j_common_ptr cinfo); GLOBAL(void) get_jpeg_info_hdr_from_file(char *inFile, jpeg_info_t *jpg, char *outputFile); GLOBAL(void) jpeg_image_band_statistics_from_file(char *inFile, char *outfile, int band_no, int *stats_exist, double *min, double *max, double *mean, double *sdev, double *rmse, int use_mask_value, float mask_value); GLOBAL(void) jpeg_image_band_psnr_from_files(char *inFile1, char *inFile2, char *outfile, int band1, int band2, psnr_t *psnr); void make_generic_meta(char *file, uint32 height, uint32 width, data_type_t data_type); void fftShiftCheck(char *file1, char *file2, char *corr_file, shift_data_t *shifts); void export_ppm_pgm_to_asf_img(char *inFile, char *outfile, char *fft_file, char *fft_meta_file, uint32 height, uint32 width, data_type_t data_type, int band); void export_jpeg_to_asf_img(char *inFile, char *outfile, char *fft_file, char *fft_meta_file, uint32 height, uint32 width, data_type_t data_type, int band); void export_tiff_to_asf_img(char *inFile, char *outfile, char *fft_file, char *fft_meta_file, uint32 height, uint32 width, data_type_t data_type, int band); void export_png_to_asf_img(char *inFile, char *outfile, char *fft_file, char *fft_meta_file, uint32 height, uint32 width, data_type_t data_type, int band); char *pcs2description(int pcs); void calc_asf_complex_image_stats_2files(char *inFile1, char *inFile2, complex_stats_t *inFile1_complex_stats, complex_stats_t *inFile2_complex_stats, complex_psnr_t *psnr, int band); void calc_complex_stats_rmse_from_file(const char *inFile, const char *band, double mask, double *i_min, double *i_max, double *i_mean, double *i_sdev, double *i_rmse, gsl_histogram **i_histogram, double *q_min, double *q_max, double *q_mean, double *q_sdev, double *q_rmse, gsl_histogram **q_histogram); void diff_check_complex_stats(char *outputFile, char *inFile1, char *inFile2, complex_stats_t *cstats1, complex_stats_t *cstats2, complex_psnr_t *cpsnr, int strict, data_type_t data_type, int num_bands); int diffimage(char *inFile1, char *inFile2, char *outputFile, char *logFile, char ***bands1, char ***bands2, int *num_bands1, int *num_bands2, int *complex, stats_t **stats1, stats_t **stats2, complex_stats_t **complex_stats1, complex_stats_t **complex_stats2, psnr_t **psnrs, complex_psnr_t **complex_psnr, shift_data_t **data_shift) { extern FILE *fLog; /* output file descriptor, stdout or log file */ int bandflag, strictflag; int num_names_extracted1 = 0, num_names_extracted2 = 0, band = 0; char msg[1024], type_str[255]; stats_t inFile1_stats[MAX_BANDS], inFile2_stats[MAX_BANDS]; complex_stats_t inFile1_complex_stats[MAX_BANDS]; complex_stats_t inFile2_complex_stats[MAX_BANDS]; psnr_t psnr[MAX_BANDS]; // peak signal to noise ratio complex_psnr_t cpsnr[MAX_BANDS]; shift_data_t shifts[MAX_BANDS]; if (logFile && strlen(logFile) > 0) fLog = FOPEN(logFile, "w"); // Create temporary directory and file names char *baseName, tmpDir[1024]; char file1_fftFile[1024], file1_fftMetaFile[1024]; char file2_fftFile[1024], file2_fftMetaFile[1024]; if (outputFile && strlen(outputFile) > 0) baseName = get_basename(outputFile); else baseName = get_basename(inFile1); strcpy(tmpDir, baseName); strcat(tmpDir, "-"); strcat(tmpDir, time_stamp_dir()); create_clean_dir(tmpDir); sprintf(file1_fftFile, "%s/tmp_file1.img", tmpDir); sprintf(file2_fftFile, "%s/tmp_file2.img", tmpDir); sprintf(file1_fftMetaFile, "%s/tmp_file1.meta", tmpDir); sprintf(file2_fftMetaFile, "%s/tmp_file2.meta", tmpDir); // Empty the output file FILE *fp = NULL; if (outputFile && strlen(outputFile) > 0) fp = (FILE*) FOPEN(outputFile, "w"); if(fp) FCLOSE(fp); // Determine input file graphical format types and check to see if they are // supported and the same type (etc ...error checking) if (strcmp(inFile1, inFile2) == 0) { FREE(outputFile); return (0); // PASS - a file compared to itself is always the same } if (!fileExists(inFile1)) { sprintf(msg, "File not found: %s\n => Did you forget to use the filename " "extension?", inFile1); FREE(outputFile); asfPrintError(msg); } if (!fileExists(inFile2)) { sprintf(msg, "File not found: %s\n => Did you forget to use the filename " "extension?", inFile2); FREE(outputFile); asfPrintError(msg); } graphics_file_t type1, type2; type1 = getGraphicsFileType(inFile1); type2 = getGraphicsFileType(inFile2); if (type1 != ASF_IMG && type1 != JPEG_IMG && type1 != PGM_IMG && type1 != PPM_IMG && type1 != PNG_IMG && type1 != STD_TIFF_IMG && type1 != GEO_TIFF_IMG ) { graphicsFileType_toStr(type1, type_str); sprintf(msg, "Graphics file type %s is not currently supported " "(Image #1: %s)\n", type_str, inFile1); FREE(outputFile); asfPrintError(msg); } if (type2 != ASF_IMG && type2 != JPEG_IMG && type2 != PGM_IMG && type2 != PPM_IMG && type1 != PNG_IMG && type2 != STD_TIFF_IMG && type2 != GEO_TIFF_IMG ) { graphicsFileType_toStr(type2, type_str); sprintf(msg, "Graphics file type %s is not currently supported " "(Image #2: %s)\n", type_str, inFile2); FREE(outputFile); asfPrintError(msg); } if (type1 != type2) { char type1_str[255], type2_str[255]; graphicsFileType_toStr(type1, type1_str); graphicsFileType_toStr(type2, type2_str); sprintf(msg, "Graphics files must be the same type.\n" " %s is type %s, and %s is type %s\n", inFile1, type1_str, inFile2, type2_str); FREE(outputFile); asfPrintError(msg); } /***** Calculate stats and PSNR *****/ // Can't be here unless both graphics file types were the same, // so choose the input process based on just one of them. char **band_names1, **band_names2; char band_str1[255], band_str2[255]; switch (type1) { case ASF_IMG: { int band_count1, band_count2; char inFile1_meta[1024], inFile2_meta[1024]; char *f1, *f2, *c; meta_parameters *md1 = NULL; meta_parameters *md2 = NULL; // Read metadata and check for multi-bandedness get_band_names(inFile1, NULL, &band_names1, &num_names_extracted1); get_band_names(inFile2, NULL, &band_names2, &num_names_extracted2); *bands1 = band_names1; *bands2 = band_names2; *num_bands1 = num_names_extracted1; *num_bands2 = num_names_extracted2; if (inFile1 != NULL && strlen(inFile1) > 0) { f1 = STRDUP(inFile1); c = findExt(f1); *c = '\0'; sprintf(inFile1_meta, "%s.meta", f1); if (fileExists(inFile1_meta)) { md1 = meta_read(inFile1_meta); } else { // Can't find metadata file sprintf(msg, "Cannot find metadata file %s\n", inFile1_meta); diffErrOut(outputFile, msg); FREE(outputFile); FREE(f1); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); asfPrintError(msg); } if (md1 == NULL) { // Can't find metadata file sprintf(msg, "Cannot find metadata file %s\n", inFile1_meta); diffErrOut(outputFile, msg); FREE(outputFile); FREE(f1); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); asfPrintError(msg); } } if (inFile2 != NULL && strlen(inFile2) > 0) { f2 = STRDUP(inFile2); c = findExt(f2); *c = '\0'; sprintf(inFile2_meta, "%s.meta", f2); if (fileExists(inFile2_meta)) { md2 = meta_read(inFile2_meta); } else { // Can't find metadata file sprintf(msg, "Cannot find metadata file %s\n", inFile2_meta); diffErrOut(outputFile, msg); FREE(outputFile); FREE(f1); FREE(f2); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); asfPrintError(msg); } if (md2 == NULL) { // Can't find metadata file sprintf(msg, "Cannot find metadata file %s\n", inFile2_meta); diffErrOut(outputFile, msg); FREE(outputFile); FREE(f1); FREE(f2); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); asfPrintError(msg); } } band_count1 = md1->general->band_count; band_count2 = md2->general->band_count; if (bandflag && !(band < band_count1 && band < band_count2 && band >= 0)) { sprintf(msg, "Invalid band number. Band number must be 0 " "(first band)\nor greater, and less than the number of " "available bands in the file\nExample: If the files have 3 " "bands, then band numbers 0, 1, or 2 are\nthe valid band " "number choices.\n\nFile1 has %d bands. File2 has %d bands" "\n", band_count1, band_count2); diffErrOut(outputFile, msg); meta_free(md1); meta_free(md2); FREE(outputFile); FREE(f1); FREE(f2); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); asfPrintError(msg); } if (!bandflag && band_count1 != band_count2) { sprintf(msg, "Files do not have the same number of bands.\n" "Cannot compare all bands. Consider using the -band option" " to\ncompare individual bands within the files.\n" "\nFile1 has %d bands. File2 has %d bands\n", band_count1, band_count2); diffErrOut(outputFile, msg); meta_free(md1); meta_free(md2); FREE(outputFile); FREE(f1); FREE(f2); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); asfPrintError(msg); } if (md1->general->data_type != md2->general->data_type) { char *s1 = data_type2str(md1->general->data_type); char *s2 = data_type2str(md2->general->data_type); sprintf(msg, "Files do not have the same data type.\n" "\nFile1 has %s data. File2 has %s data\n", s1, s2); FREE(s1); FREE(s2); diffErrOut(outputFile, msg); meta_free(md1); meta_free(md2); FREE(outputFile); FREE(f1); FREE(f2); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); asfPrintError(msg); } int is_complex = md2->general->data_type == COMPLEX_BYTE || md2->general->data_type == COMPLEX_INTEGER16 || md2->general->data_type == COMPLEX_INTEGER32 || md2->general->data_type == COMPLEX_REAL32 || md2->general->data_type == COMPLEX_REAL64; // Allocate space for output *complex = is_complex; if (is_complex) { *complex_stats1 = (complex_stats_t *) MALLOC(sizeof(complex_stats_t)* num_names_extracted1); *complex_stats2 = (complex_stats_t *) MALLOC(sizeof(complex_stats_t)* num_names_extracted2); *complex_psnr = (complex_psnr_t *) MALLOC(sizeof(complex_psnr_t)); } else { *stats1 = (stats_t *) MALLOC(sizeof(stats_t)*num_names_extracted1); *stats2 = (stats_t *) MALLOC(sizeof(stats_t)*num_names_extracted2); *psnrs = (psnr_t *) MALLOC(sizeof(psnr_t)); } *data_shift = (shift_data_t *) MALLOC(sizeof(shift_data_t)); if (is_complex && md2->general->data_type != COMPLEX_BYTE) { char *data_type_str = data_type2str(md2->general->data_type); sprintf(msg, "Complex data types other than COMPLEX_BYTE not yet " "supported (Found %s)\n", data_type_str); if (data_type_str) FREE(data_type_str); diffErrOut(outputFile, msg); meta_free(md1); meta_free(md2); FREE(outputFile); FREE(f1); FREE(f2); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); FREE(data_type_str); asfPrintError(msg); } //////////////////////////////////////////////////////////////// // Calculate statistics, PSNR, measure image-to-image shift in // geolocation, and then check the results if (!bandflag) { // Process every available band int band_no; int empty_band1, empty_band2; for (band_no=0; band_no < band_count1; band_no++) { strcpy(band_str1, ""); strcpy(band_str2, ""); if (band_count1 > 0) { sprintf(band_str1, "Band %s in ", band_names1[band_no]); sprintf(band_str2, "Band %s in ", band_names2[band_no]); } asfPrintStatus("\nCalculating statistics for\n %s%s and\n %s%s\n", band_str1, inFile1, band_str2, inFile2); if (is_complex) { // For complex data, only check stats and psnr ...and don't check // for shifts in geolocation (doesn't make sense) calc_asf_complex_image_stats_2files(inFile1, inFile2, &inFile1_complex_stats[band_no], &inFile2_complex_stats[band_no], &cpsnr[band_no], band_no); (*complex_stats1)[band_no] = inFile1_complex_stats[band_no]; (*complex_stats2)[band_no] = inFile2_complex_stats[band_no]; (*complex_psnr)[band_no] = cpsnr[band_no]; } else { calc_asf_img_stats_2files(inFile1, inFile2, &inFile1_stats[band_no], &inFile2_stats[band_no], &psnr[band_no], band_no); (*stats1)[band_no] = inFile1_stats[band_no]; (*stats2)[band_no] = inFile2_stats[band_no]; (*psnrs)[band_no] = psnr[band_no]; empty_band1 = (FLOAT_EQUIVALENT2(inFile1_stats[band_no].mean, 0.0) && FLOAT_EQUIVALENT2(inFile1_stats[band_no].sdev, 0.0)) ? 1 : 0; empty_band2 = (FLOAT_EQUIVALENT2(inFile2_stats[band_no].mean, 0.0) && FLOAT_EQUIVALENT2(inFile2_stats[band_no].sdev, 0.0)) ? 1 : 0; if (!empty_band1 && !empty_band2 && inFile1_stats[band_no].stats_good && inFile2_stats[band_no].stats_good) { if (band_no == 0) { fftShiftCheck(inFile1, inFile2, CORR_FILE, &shifts[band_no]); (*data_shift)[band_no] = shifts[band_no]; } else { shifts[band_no].dx = 0.0; shifts[band_no].dy = 0.0; shifts[band_no].cert = 1.0; } } else { shifts[band_no].dx = 0.0; shifts[band_no].dy = 0.0; shifts[band_no].cert = 1.0; } } } // Assumes both files have the same band count and data types or // would not be here if (is_complex) { // No diff check on geolocation (doesn't make sense for // complex data) diff_check_complex_stats(outputFile, inFile1, inFile2, inFile1_complex_stats, inFile2_complex_stats, cpsnr, strictflag, md2->general->data_type, band_count2); } else { diff_check_stats(outputFile, inFile1, inFile2, inFile1_stats, inFile2_stats, psnr, strictflag, md2->general->data_type, band_count2); diff_check_geolocation(outputFile, inFile1, inFile2, 1, shifts, inFile1_stats, inFile2_stats); } } else { // Process selected band int empty_band1, empty_band2; asfPrintStatus("\nCalculating statistics for\n %s and\n %s\n", inFile1, inFile2); calc_asf_img_stats_2files(inFile1, inFile2, inFile1_stats, inFile2_stats, psnr, band); empty_band1 = (FLOAT_EQUIVALENT2(inFile1_stats[band].mean, 0.0) && FLOAT_EQUIVALENT2(inFile1_stats[band].sdev, 0.0)) ? 1 : 0; empty_band2 = (FLOAT_EQUIVALENT2(inFile2_stats[band].mean, 0.0) && FLOAT_EQUIVALENT2(inFile2_stats[band].sdev, 0.0)) ? 1 : 0; if (!empty_band1 && !empty_band2 && inFile1_stats[band].stats_good && inFile2_stats[band].stats_good) { // FIXME: Consider shift checking each band ... // shouldn't be necessary tho', so we // only check the first band for now. if (band == 0) { fftShiftCheck(inFile1, inFile2, CORR_FILE, &shifts[band]); (*data_shift)[band] = shifts[band]; } else { shifts[band].dx = 0.0; shifts[band].dy = 0.0; shifts[band].cert = 1.0; } } else { shifts[band].dx = 0.0; shifts[band].dy = 0.0; shifts[band].cert = 1.0; } // Assumes both files have the same band count and data types or // would not be here diff_check_stats(outputFile, inFile1, inFile2, &inFile1_stats[band], &inFile2_stats[band], &psnr[band], strictflag, md1->general->data_type, 1); diff_check_geolocation(outputFile, inFile1, inFile2, 1, shifts, &inFile1_stats[band], &inFile2_stats[band]); } ////////////////////////////////////////////// free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); } break; case JPEG_IMG: { int ii; jpeg_info_t jpg1, jpg2; // Determine number of bands and data type etc. get_jpeg_info_hdr_from_file(inFile1, &jpg1, outputFile); get_jpeg_info_hdr_from_file(inFile2, &jpg2, outputFile); get_band_names(inFile1, NULL, &band_names1, &num_names_extracted1); get_band_names(inFile2, NULL, &band_names2, &num_names_extracted2); *num_bands1 = jpg1.num_bands; *num_bands2 = jpg2.num_bands; *bands1 = (char**) MALLOC(sizeof(char*)*(*num_bands1)); for (ii=0; ii<(*num_bands1); ii++) { (*bands1)[ii] = (char *) MALLOC(sizeof(char)*64); strcpy((*bands1)[ii], band_names1[ii]); } *bands2 = (char**) MALLOC(sizeof(char*)*(*num_bands2)); for (ii=0; ii<(*num_bands2); ii++) { (*bands2)[ii] = (char *) MALLOC(sizeof(char)*64); strcpy((*bands2)[ii], band_names2[ii]); } *complex = 0; *stats1 = (stats_t *) MALLOC(sizeof(stats_t)*(*num_bands1)); *stats2 = (stats_t *) MALLOC(sizeof(stats_t)*(*num_bands2)); *psnrs = (psnr_t *) MALLOC(sizeof(psnr_t)*(*num_bands1)); *data_shift = (shift_data_t *) MALLOC(sizeof(shift_data_t)*(*num_bands1)); if (jpg1.data_type != jpg2.data_type) { char *s1 = data_type2str(jpg1.data_type); char *s2 = data_type2str(jpg2.data_type); sprintf(msg, "Files do not have the same data type.\n" "\nFile1 has %s data. File2 has %s data\n", s1, s2); FREE(s1); FREE(s2); diffErrOut(outputFile, msg); FREE(outputFile); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); asfPrintError(msg); } if (bandflag && !(band < jpg1.num_bands && band < jpg2.num_bands && band >= 0)) { sprintf(msg, "Invalid band number. Band number must be 0 (first " "band)\nor greater, and less than the number of available " "bands in the file\nExample: If the files have 3 bands, " "then band numbers 0, 1, or 2 are\n" "the valid band number choices. \n" "\nFile1 has %d bands. File2 has %d bands\n", jpg1.num_bands, jpg2.num_bands); diffErrOut(outputFile, msg); FREE(outputFile); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); asfPrintError(msg); } if (!bandflag && jpg1.num_bands != jpg2.num_bands) { sprintf(msg, "Files do not have the same number of bands.\n" "Cannot compare all bands. Consider using the -band option to\n" "compare individual bands within the files.\n" "\nFile1 has %d bands. File2 has %d bands\n", jpg1.num_bands, jpg2.num_bands); diffErrOut(outputFile, msg); FREE(outputFile); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); asfPrintError(msg); } ///////////////////////////////////////////////////////////// // Calculate statistics, PSNR, measure image-to-image shift in // geolocation, and then check the results if (!bandflag) { // Process every available band int band_no; for (band_no=0; band_no < jpg1.num_bands; band_no++) { strcpy(band_str1, ""); strcpy(band_str2, ""); if (jpg1.num_bands > 1) { sprintf(band_str1, "Band %s in ", band_names1[band_no]); sprintf(band_str2, "Band %s in ", band_names2[band_no]); } asfPrintStatus("\nCalculating statistics for\n %s%s and\n %s%s\n", band_str1, inFile1, band_str2, inFile2); calc_jpeg_stats_2files(inFile1, inFile2, outputFile, &inFile1_stats[band_no], &inFile2_stats[band_no], &psnr[band_no], band_no); (*stats1)[band_no] = inFile1_stats[band_no]; (*stats2)[band_no] = inFile2_stats[band_no]; (*psnrs)[band_no] = psnr[band_no]; asfPrintStatus("\nMeasuring image shift from\n %s%s to\n %s%s\n", band_str1, inFile1, band_str2, inFile2); int empty_band1, empty_band2; empty_band1 = (FLOAT_EQUIVALENT2(inFile1_stats[band_no].mean, 0.0) && FLOAT_EQUIVALENT2(inFile1_stats[band_no].sdev, 0.0)) ? 1 : 0; empty_band2 = (FLOAT_EQUIVALENT2(inFile2_stats[band_no].mean, 0.0) && FLOAT_EQUIVALENT2(inFile2_stats[band_no].sdev, 0.0)) ? 1 : 0; if (!empty_band1 && !empty_band2 && inFile1_stats[band_no].stats_good && inFile2_stats[band_no].stats_good) { // Find shift in geolocation (if it exists) // (Export to an ASF internal format file for fftMatch() // compatibility) export_jpeg_to_asf_img(inFile1, outputFile, file1_fftFile, file1_fftMetaFile, jpg1.height, jpg1.width, REAL32, band_no); export_jpeg_to_asf_img(inFile2, outputFile, file2_fftFile, file2_fftMetaFile, jpg2.height, jpg2.width, REAL32, band_no); // FIXME: Consider shift checking each band ... // shouldn't be necessary tho', so we // only check the first band for now. if (band_no == 0) { fftShiftCheck(file1_fftFile, file2_fftFile, CORR_FILE, &shifts[band_no]); (*data_shift)[band_no] = shifts[band_no]; } else { shifts[band_no].dx = 0.0; shifts[band_no].dy = 0.0; shifts[band_no].cert = 1.0; } } else { shifts[band_no].dx = 0.0; shifts[band_no].dy = 0.0; shifts[band_no].cert = 1.0; } } diff_check_stats(outputFile, inFile1, inFile2, inFile1_stats, inFile2_stats, psnr, strictflag, jpg1.data_type, jpg1.num_bands); diff_check_geolocation(outputFile, inFile1, inFile2, 1, shifts, inFile1_stats, inFile2_stats); } else { // Process selected band asfPrintStatus("\nCalculating statistics for\n %s and\n %s\n", inFile1, inFile2); calc_jpeg_stats_2files(inFile1, inFile2, outputFile, inFile1_stats, inFile2_stats, psnr, band); (*stats1)[band] = inFile1_stats[band]; (*stats2)[band] = inFile2_stats[band]; (*psnrs)[band] = psnr[band]; int empty_band1, empty_band2; empty_band1 = (FLOAT_EQUIVALENT2(inFile1_stats[band].mean, 0.0) && FLOAT_EQUIVALENT2(inFile1_stats[band].sdev, 0.0)) ? 1 : 0; empty_band2 = (FLOAT_EQUIVALENT2(inFile2_stats[band].mean, 0.0) && FLOAT_EQUIVALENT2(inFile2_stats[band].sdev, 0.0)) ? 1 : 0; if (!empty_band1 && !empty_band2 && inFile1_stats[band].stats_good && inFile2_stats[band].stats_good) { // Find shift in geolocation (if it exists) // (Export to an ASF internal format file for fftMatch() // compatibility) export_jpeg_to_asf_img(inFile1, outputFile, file1_fftFile, file1_fftMetaFile, jpg1.height, jpg1.width, REAL32, band); export_jpeg_to_asf_img(inFile2, outputFile, file2_fftFile, file2_fftMetaFile, jpg2.height, jpg2.width, REAL32, band); if (band == 0) { fftShiftCheck(file1_fftFile, file2_fftFile, CORR_FILE, &shifts[band]); (*data_shift)[band] = shifts[band]; } else { shifts[band].dx = 0.0; shifts[band].dy = 0.0; shifts[band].cert = 1.0; } } else { shifts[band].dx = 0.0; shifts[band].dy = 0.0; shifts[band].cert = 1.0; } // Check for differences in stats or geolocation diff_check_stats(outputFile, inFile1, inFile2, &inFile1_stats[band], &inFile2_stats[band], &psnr[band], strictflag, jpg1.data_type, 1); diff_check_geolocation(outputFile, inFile1, inFile2, 1, &shifts[band], &inFile1_stats[band], &inFile2_stats[band]); } /////////////////////////////////////////////////////////////////// free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); } break; case PNG_IMG: { png_info_t ihdr1, ihdr2; // Determine number of bands and data type etc. get_png_info_hdr_from_file(inFile1, &ihdr1, outputFile); get_png_info_hdr_from_file(inFile2, &ihdr2, outputFile); get_band_names(inFile1, NULL, &band_names1, &num_names_extracted1); get_band_names(inFile2, NULL, &band_names2, &num_names_extracted2); if (ihdr1.data_type != ihdr2.data_type) { char *s1 = data_type2str(ihdr1.data_type); char *s2 = data_type2str(ihdr2.data_type); sprintf(msg, "Files do not have the same data type.\n" "\nFile1 has %s data. File2 has %s data\n", s1, s2); FREE(s1); FREE(s2); diffErrOut(outputFile, msg); FREE(outputFile); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); asfPrintError(msg); } if (bandflag && !(band < ihdr1.num_bands && band < ihdr2.num_bands && band >= 0)) { sprintf(msg, "Invalid band number. Band number must be 0 (first " "band)\nor greater, and less than the number of available " "bands in the file\nExample: If the files have 3 bands, " "then band numbers 0, 1, or 2 are\n" "the valid band number choices. \n" "\nFile1 has %d bands. File2 has %d bands\n", ihdr1.num_bands, ihdr2.num_bands); diffErrOut(outputFile, msg); FREE(outputFile); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); asfPrintError(msg); } if (!bandflag && ihdr1.num_bands != ihdr2.num_bands) { sprintf(msg, "Files do not have the same number of bands.\n" "Cannot compare all bands. Consider using the -band option to\n" "compare individual bands within the files.\n" "\nFile1 has %d bands. File2 has %d bands\n", ihdr1.num_bands, ihdr2.num_bands); diffErrOut(outputFile, msg); FREE(outputFile); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); asfPrintError(msg); } /////////////////////////////////////////////////////////////// // Calculate statistics, PSNR, measure image-to-image shift in // geolocation, and then check the results if (!bandflag) { // Process every available band int band_no; for (band_no=0; band_no < ihdr1.num_bands; band_no++) { strcpy(band_str1, ""); strcpy(band_str2, ""); if (ihdr1.num_bands > 1) { sprintf(band_str1, "Band %s in ", band_names1[band_no]); sprintf(band_str2, "Band %s in ", band_names2[band_no]); } asfPrintStatus("\nCalculating statistics for\n %s%s and\n %s%s\n", band_str1, inFile1, band_str2, inFile2); calc_png_stats_2files(inFile1, inFile2, outputFile, &inFile1_stats[band_no], &inFile2_stats[band_no], &psnr[band_no], band_no); int empty_band1, empty_band2; empty_band1 = (FLOAT_EQUIVALENT2(inFile1_stats[band_no].mean, 0.0) && FLOAT_EQUIVALENT2(inFile1_stats[band_no].sdev, 0.0)) ? 1 : 0; empty_band2 = (FLOAT_EQUIVALENT2(inFile2_stats[band_no].mean, 0.0) && FLOAT_EQUIVALENT2(inFile2_stats[band_no].sdev, 0.0)) ? 1 : 0; if (!empty_band1 && !empty_band2 && inFile1_stats[band_no].stats_good && inFile2_stats[band_no].stats_good) { // Find shift in geolocation (if it exists) // (Export to an ASF internal format file for fftMatch() // compatibility) export_png_to_asf_img(inFile1, outputFile, file1_fftFile, file1_fftMetaFile, ihdr1.height, ihdr1.width, REAL32, band_no); export_png_to_asf_img(inFile2, outputFile, file2_fftFile, file2_fftMetaFile, ihdr2.height, ihdr2.width, REAL32, band_no); if (band_no == 0) { fftShiftCheck(file1_fftFile, file2_fftFile, CORR_FILE, &shifts[band_no]); } else { shifts[band_no].dx = 0.0; shifts[band_no].dy = 0.0; shifts[band_no].cert = 1.0; } } else { shifts[band_no].dx = 0.0; shifts[band_no].dy = 0.0; shifts[band_no].cert = 1.0; } } diff_check_stats(outputFile, inFile1, inFile2, inFile1_stats, inFile2_stats, psnr, strictflag, ihdr1.data_type, ihdr1.num_bands); diff_check_geolocation(outputFile, inFile1, inFile2, 1, shifts, inFile1_stats, inFile2_stats); } else { // Process selected band asfPrintStatus("\nCalculating statistics for\n %s and\n %s\n", inFile1, inFile2); calc_png_stats_2files(inFile1, inFile2, outputFile, inFile1_stats, inFile2_stats, psnr, band); int empty_band1, empty_band2; empty_band1 = (FLOAT_EQUIVALENT2(inFile1_stats[band].mean, 0.0) && FLOAT_EQUIVALENT2(inFile1_stats[band].sdev, 0.0)) ? 1 : 0; empty_band2 = (FLOAT_EQUIVALENT2(inFile2_stats[band].mean, 0.0) && FLOAT_EQUIVALENT2(inFile2_stats[band].sdev, 0.0)) ? 1 : 0; if (!empty_band1 && !empty_band2 && inFile1_stats[band].stats_good && inFile2_stats[band].stats_good) { // Find shift in geolocation (if it exists) // (Export to an ASF internal format file for fftMatch() // compatibility) export_png_to_asf_img(inFile1, outputFile, file1_fftFile, file1_fftMetaFile, ihdr1.height, ihdr1.width, REAL32, band); export_png_to_asf_img(inFile2, outputFile, file2_fftFile, file2_fftMetaFile, ihdr2.height, ihdr2.width, REAL32, band); if (band == 0) { fftShiftCheck(file1_fftFile, file2_fftFile, CORR_FILE, &shifts[band]); } else { shifts[band].dx = 0.0; shifts[band].dy = 0.0; shifts[band].cert = 1.0; } } else { shifts[band].dx = 0.0; shifts[band].dy = 0.0; shifts[band].cert = 1.0; } diff_check_stats(outputFile, inFile1, inFile2, &inFile1_stats[band], &inFile2_stats[band], &psnr[band], strictflag, ihdr1.data_type, 1); diff_check_geolocation(outputFile, inFile1, inFile2, 1, shifts, &inFile1_stats[band], &inFile2_stats[band]); } /////////////////////////////////////////////////////////////// free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); } break; case PPM_IMG: case PGM_IMG: { ppm_pgm_info_t pgm1, pgm2; // Determine number of bands and data type etc. get_ppm_pgm_info_hdr_from_file(inFile1, &pgm1, outputFile); get_ppm_pgm_info_hdr_from_file(inFile2, &pgm2, outputFile); get_band_names(inFile1, NULL, &band_names1, &num_names_extracted1); get_band_names(inFile2, NULL, &band_names2, &num_names_extracted2); if (pgm1.data_type != pgm2.data_type) { char *s1 = data_type2str(pgm1.data_type); char *s2 = data_type2str(pgm2.data_type); sprintf(msg, "Files do not have the same data type.\n" "\nFile1 has %s data. File2 has %s data\n", s1, s2); FREE(s1); FREE(s2); diffErrOut(outputFile, msg); FREE(outputFile); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); asfPrintError(msg); } if (bandflag && !(band < pgm1.num_bands && band < pgm2.num_bands && band >= 0)) { sprintf(msg, "Invalid band number. Band number must be 0 (first " "band)\nor greater, and less than the number of available " "bands in the file\nExample: If the files have 3 bands, " "then band numbers 0, 1, or 2 are\n" "the valid band number choices. \n" "\nFile1 has %d bands. File2 has %d bands\n", pgm1.num_bands, pgm2.num_bands); diffErrOut(outputFile, msg); FREE(outputFile); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); asfPrintError(msg); } if (!bandflag && pgm1.num_bands != pgm2.num_bands) { sprintf(msg, "Files do not have the same number of bands.\n" "Cannot compare all bands. Consider using the -band option " "to\ncompare individual bands within the files.\n" "\nFile1 has %d bands. File2 has %d bands\n", pgm1.num_bands, pgm2.num_bands); diffErrOut(outputFile, msg); FREE(outputFile); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); asfPrintError(msg); } ///////////////////////////////////////////////////////////// // Calculate statistics, PSNR, measure image-to-image shift in // geolocation, and then check the results if (!bandflag) { // Process every available band int band_no; for (band_no=0; band_no < pgm1.num_bands; band_no++) { strcpy(band_str1, ""); strcpy(band_str2, ""); if (pgm1.num_bands > 1) { sprintf(band_str1, "Band %s in ", band_names1[band_no]); sprintf(band_str2, "Band %s in ", band_names2[band_no]); } asfPrintStatus("\nCalculating statistics for\n %s%s and\n %s%s\n", band_str1, inFile1, band_str2, inFile2); calc_ppm_pgm_stats_2files(inFile1, inFile2, outputFile, &inFile1_stats[band_no], &inFile2_stats[band_no], &psnr[band_no], band_no); int empty_band1, empty_band2; empty_band1 = (FLOAT_EQUIVALENT2(inFile1_stats[band_no].mean, 0.0) && FLOAT_EQUIVALENT2(inFile1_stats[band_no].sdev, 0.0)) ? 1 : 0; empty_band2 = (FLOAT_EQUIVALENT2(inFile2_stats[band_no].mean, 0.0) && FLOAT_EQUIVALENT2(inFile2_stats[band_no].sdev, 0.0)) ? 1 : 0; if (!empty_band1 && !empty_band2 && inFile1_stats[band_no].stats_good && inFile2_stats[band_no].stats_good) { // Find shift in geolocation (if it exists) // (Export to an ASF internal format file for fftMatch() // compatibility) export_ppm_pgm_to_asf_img(inFile1, outputFile, file1_fftFile, file1_fftMetaFile, pgm1.height, pgm1.width, REAL32, band_no); export_ppm_pgm_to_asf_img(inFile2, outputFile, file2_fftFile, file2_fftMetaFile, pgm2.height, pgm2.width, REAL32, band_no); if (band_no == 0) { fftShiftCheck(file1_fftFile, file2_fftFile, CORR_FILE, &shifts[band_no]); } else { shifts[band_no].dx = 0.0; shifts[band_no].dy = 0.0; shifts[band_no].cert = 1.0; } } else { shifts[band_no].dx = 0.0; shifts[band_no].dy = 0.0; shifts[band_no].cert = 1.0; } } diff_check_stats(outputFile, inFile1, inFile2, inFile1_stats, inFile2_stats, psnr, strictflag, pgm1.data_type, pgm1.num_bands); diff_check_geolocation(outputFile, inFile1, inFile2, 1, shifts, inFile1_stats, inFile2_stats); } else { // Process selected band asfPrintStatus("\nCalculating statistics for\n %s and\n %s\n", inFile1, inFile2); calc_ppm_pgm_stats_2files(inFile1, inFile2, outputFile, inFile1_stats, inFile2_stats, psnr, band); int empty_band1, empty_band2; empty_band1 = (FLOAT_EQUIVALENT2(inFile1_stats[band].mean, 0.0) && FLOAT_EQUIVALENT2(inFile1_stats[band].sdev, 0.0)) ? 1 : 0; empty_band2 = (FLOAT_EQUIVALENT2(inFile2_stats[band].mean, 0.0) && FLOAT_EQUIVALENT2(inFile2_stats[band].sdev, 0.0)) ? 1 : 0; if (!empty_band1 && !empty_band2 && inFile1_stats[band].stats_good && inFile2_stats[band].stats_good) { // Find shift in geolocation (if it exists) // (Export to an ASF internal format file for fftMatch() // compatibility) export_ppm_pgm_to_asf_img(inFile1, outputFile, file1_fftFile, file1_fftMetaFile, pgm1.height, pgm1.width, REAL32, band); export_ppm_pgm_to_asf_img(inFile2, outputFile, file2_fftFile, file2_fftMetaFile, pgm2.height, pgm2.width, REAL32, band); if (band == 0) { fftShiftCheck(file1_fftFile, file2_fftFile, CORR_FILE, &shifts[band]); } else { shifts[band].dx = 0.0; shifts[band].dy = 0.0; shifts[band].cert = 1.0; } } else { shifts[band].dx = 0.0; shifts[band].dy = 0.0; shifts[band].cert = 1.0; } // Check for differences diff_check_stats(outputFile, inFile1, inFile2, &inFile1_stats[band], &inFile2_stats[band], &psnr[band], strictflag, pgm1.data_type, 1); diff_check_geolocation(outputFile, inFile1, inFile2, 1, shifts, &inFile1_stats[band], &inFile2_stats[band]); } ////////////////////////////////////////////////////////// free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); } break; case STD_TIFF_IMG: case GEO_TIFF_IMG: { int ii, geotiff = (type1 == GEO_TIFF_IMG) ? 1 : 0; tiff_data_t t1, t2; geotiff_data_t g1, g2; // Determine number of bands and data type get_tiff_info_from_file(inFile1, &t1); get_tiff_info_from_file(inFile2, &t2); get_band_names(inFile1, NULL, &band_names1, &num_names_extracted1); get_band_names(inFile2, NULL, &band_names2, &num_names_extracted2); *num_bands1 = t1.num_bands; *num_bands2 = t2.num_bands; *bands1 = (char**) MALLOC(sizeof(char*)*(*num_bands1)); for (ii=0; ii<(*num_bands1); ii++) { (*bands1)[ii] = (char *) MALLOC(sizeof(char)*64); strcpy((*bands1)[ii], band_names1[ii]); } *bands2 = (char**) MALLOC(sizeof(char*)*(*num_bands2)); for (ii=0; ii<(*num_bands2); ii++) { (*bands2)[ii] = (char *) MALLOC(sizeof(char)*64); strcpy((*bands2)[ii], band_names2[ii]); } *complex = 0; *stats1 = (stats_t *) MALLOC(sizeof(stats_t)*(*num_bands1)); *stats2 = (stats_t *) MALLOC(sizeof(stats_t)*(*num_bands2)); *psnrs = (psnr_t *) MALLOC(sizeof(psnr_t)*(*num_bands1)); *data_shift = (shift_data_t *) MALLOC(sizeof(shift_data_t)*(*num_bands1)); if (t1.data_type != t2.data_type) { char *s1 = data_type2str(t1.data_type); char *s2 = data_type2str(t2.data_type); sprintf(msg, "Files do not have the same data type.\n" "\nFile1 has %s data. File2 has %s data\n", s1, s2); FREE(s1); FREE(s2); diffErrOut(outputFile, msg); FREE(outputFile); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); asfPrintError(msg); } if (bandflag && !(band < t1.num_bands && band < t2.num_bands && band >= 0)) { sprintf(msg, "Invalid band number. Band number must be 0 (first " "band)\nor greater, and less than the number of available " "bands in the file\nExample: If the files have 3 bands, " "then band numbers 0, 1, or 2 are\n" "the valid band number choices. \n" "\nFile1 has %d bands. File2 has %d bands\n", t1.num_bands, t2.num_bands); diffErrOut(outputFile, msg); FREE(outputFile); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); asfPrintError(msg); } if (!bandflag && t1.num_bands != t2.num_bands) { sprintf(msg, "Files do not have the same number of bands.\n" "Cannot compare all bands. Consider using the -band option " "to\ncompare individual bands within the files.\n" "\nFile1 has %d bands. File2 has %d bands\n", t1.num_bands, t2.num_bands); diffErrOut(outputFile, msg); FREE(outputFile); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); asfPrintError(msg); } ///////////////////////////////////////////////////////////////////// // Calculate statistics, PSNR, measure image-to-image shift in // geolocation, and then check the results if (!bandflag) { // Process every available band int band_no; for (band_no=0; band_no < t1.num_bands; band_no++) { strcpy(band_str1, ""); strcpy(band_str2, ""); if (t1.num_bands > 1) { sprintf(band_str1, "Band %s in ", band_names1[band_no]); sprintf(band_str2, "Band %s in ", band_names2[band_no]); } asfPrintStatus("\nCalculating statistics for\n %s%s and\n %s%s\n", band_str1, inFile1, band_str2, inFile2); calc_tiff_stats_2files(inFile1, inFile2, &inFile1_stats[band_no], &inFile2_stats[band_no], &psnr[band_no], band_no); (*stats1)[band_no] = inFile1_stats[band_no]; (*stats2)[band_no] = inFile2_stats[band_no]; (*psnrs)[band_no] = psnr[band_no]; int empty_band1, empty_band2; empty_band1 = (FLOAT_EQUIVALENT2(inFile1_stats[band_no].mean, 0.0) && FLOAT_EQUIVALENT2(inFile1_stats[band_no].sdev, 0.0)) ? 1 : 0; empty_band2 = (FLOAT_EQUIVALENT2(inFile2_stats[band_no].mean, 0.0) && FLOAT_EQUIVALENT2(inFile2_stats[band_no].sdev, 0.0)) ? 1 : 0; if (!empty_band1 && !empty_band2 && inFile1_stats[band_no].stats_good && inFile2_stats[band_no].stats_good) { // Find shift in geolocation (if it exists) // (Export to an ASF internal format file for fftMatch() // compatibility) export_tiff_to_asf_img(inFile1, outputFile, file1_fftFile, file1_fftMetaFile, t1.height, t1.width, REAL32, band_no); export_tiff_to_asf_img(inFile2, outputFile, file2_fftFile, file2_fftMetaFile, t2.height, t2.width, REAL32, band_no); // FIXME: Consider shift checking each band ... // shouldn't be necessary tho', so we // only check the first band for now. if (band_no == 0) { fftShiftCheck(file1_fftFile, file2_fftFile, CORR_FILE, &shifts[band_no]); (*data_shift)[band_no] = shifts[band_no]; } else { shifts[band_no].dx = 0.0; shifts[band_no].dy = 0.0; shifts[band_no].cert = 1.0; } } else { shifts[band_no].dx = 0.0; shifts[band_no].dy = 0.0; shifts[band_no].cert = 1.0; } if (geotiff) { get_geotiff_keys(inFile1, &g1); get_geotiff_keys(inFile2, &g2); diff_check_geotiff(outputFile, &g1, &g2); } } diff_check_stats(outputFile, inFile1, inFile2, inFile1_stats, inFile2_stats, psnr, strictflag, t1.data_type, t1.num_bands); diff_check_geolocation(outputFile, inFile1, inFile2, 1, shifts, inFile1_stats, inFile2_stats); } else { // Process selected band asfPrintStatus("\nCalculating statistics for\n %s and\n %s\n", inFile1, inFile2); calc_tiff_stats_2files(inFile1, inFile2, inFile1_stats, inFile2_stats, psnr, band); (*stats1)[band] = inFile1_stats[band]; (*stats2)[band] = inFile2_stats[band]; (*psnrs)[band] = psnr[band]; int empty_band1, empty_band2; empty_band1 = (FLOAT_EQUIVALENT2(inFile1_stats[band].mean, 0.0) && FLOAT_EQUIVALENT2(inFile1_stats[band].sdev, 0.0)) ? 1 : 0; empty_band2 = (FLOAT_EQUIVALENT2(inFile2_stats[band].mean, 0.0) && FLOAT_EQUIVALENT2(inFile2_stats[band].sdev, 0.0)) ? 1 : 0; if (!empty_band1 && !empty_band2 && inFile1_stats[band].stats_good && inFile2_stats[band].stats_good) { // Find shift in geolocation (if it exists) // (Export to an ASF internal format file for fftMatch() // compatibility) export_tiff_to_asf_img(inFile1, outputFile, file1_fftFile, file1_fftMetaFile, t1.height, t1.width, REAL32, band); export_tiff_to_asf_img(inFile2, outputFile, file2_fftFile, file2_fftMetaFile, t2.height, t2.width, REAL32, band); if (band == 0) { fftShiftCheck(file1_fftFile, file2_fftFile, CORR_FILE, &shifts[band]); (*data_shift)[band] = shifts[band]; } else { shifts[band].dx = 0.0; shifts[band].dy = 0.0; shifts[band].cert = 1.0; } } else { shifts[band].dx = 0.0; shifts[band].dy = 0.0; shifts[band].cert = 1.0; } if (geotiff) { get_geotiff_keys(inFile1, &g1); get_geotiff_keys(inFile2, &g2); diff_check_geotiff(outputFile, &g1, &g2); } diff_check_stats(outputFile, inFile1, inFile2, &inFile1_stats[band], &inFile2_stats[band], &psnr[band], strictflag, t1.data_type, 1); diff_check_geolocation(outputFile, inFile1, inFile2, 1, shifts, &inFile1_stats[band], &inFile2_stats[band]); } ////////////////////////////////////////////////////////////////// free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); } break; default: sprintf(msg, "Unrecognized image file type found.\n"); diffErrOut(outputFile, msg); FREE(outputFile); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); asfPrintError(msg); break; } remove_dir(tmpDir); return (0); } graphics_file_t getGraphicsFileType (char *file) { FILE *fp = (FILE *)FOPEN(file, "rb"); uint8 magic[4]; graphics_file_t file_type = UNKNOWN_GRAPHICS_TYPE; TIFF *itif = NULL; GTIF *gtif = NULL; if (fp != NULL) { int i; // Read the magic number from the file header for (i=0; i<4; i++) { magic[i] = (uint8)fgetc(fp); } if(fp) FCLOSE(fp); // Check for a valid magic number combination if (magic[0] == 0xFF && magic[1] == 0xD8) { file_type = JPEG_IMG; } else if (magic[0] == 'P' && (magic[1] == '4' || magic[1] == '1')) { file_type = PBM_IMG; } else if (magic[0] == 'P' && (magic[1] == '5' || magic[1] == '2')) { file_type = PGM_IMG; } else if (magic[0] == 'P' && (magic[1] == '6' || magic[1] == '3')) { file_type = PPM_IMG; } else if ((magic[0] == 'I' && magic[1] == 'I') || (magic[0] == 'M' && magic[1] == 'M')) { file_type = STD_TIFF_IMG; itif = XTIFFOpen(file, "rb"); if (itif != NULL) { gtif = GTIFNew(itif); if (gtif != NULL) { double *tie_point = NULL; double *pixel_scale = NULL; short model_type, raster_type, linear_units; int read_count, tie_points, pixel_scales; (gtif->gt_methods.get) (gtif->gt_tif, GTIFF_TIEPOINTS, &tie_points, &tie_point); (gtif->gt_methods.get) (gtif->gt_tif, GTIFF_PIXELSCALE, &pixel_scales, &pixel_scale); read_count = GTIFKeyGet(gtif, GTModelTypeGeoKey, &model_type, 0, 1); read_count += GTIFKeyGet(gtif, GTRasterTypeGeoKey, &raster_type, 0, 0); read_count += GTIFKeyGet(gtif, ProjLinearUnitsGeoKey, &linear_units, 0, 1); if (tie_points == 6 && pixel_scales == 3 && read_count == 3) { file_type = GEO_TIFF_IMG; } if (tie_point != NULL) free(tie_point); if (pixel_scale != NULL) free(pixel_scale); GTIFFree(gtif); } XTIFFClose(itif); } } else if (magic[0] == 'B' && magic[1] == 'M') { file_type = BMP_IMG; } else if (magic[0] == 'G' && magic[1] == 'I' && magic[2] == 'F') { file_type = GIF_IMG; } else if (magic[1] == 'P' && magic[2] == 'N' && magic[3] == 'G') { file_type = PNG_IMG; } else if (asf_img_file_found(file)) { file_type = ASF_IMG; } else { file_type = UNKNOWN_GRAPHICS_TYPE; } } return file_type; } int asf_img_file_found(char *file) { int found = 0; if (fileExists(file) && strncmp(uc(findExt(file)), ".IMG", 4) == 0) { found = 1; } else { found = 0; } return found; } void fftDiff(char *inFile1, char *inFile2, float *bestLocX, float *bestLocY, float *certainty) { ; } void graphicsFileType_toStr (graphics_file_t type, char *type_str) { switch (type) { case ASF_IMG: strcpy (type_str, "ASF_IMG"); break; case JPEG_IMG: strcpy (type_str, "JPEG"); break; case PBM_IMG: strcpy (type_str, "PBM"); break; case PGM_IMG: strcpy (type_str, "PGM"); break; case PPM_IMG: strcpy (type_str, "PPM"); break; case STD_TIFF_IMG: strcpy (type_str, "TIFF"); break; case GEO_TIFF_IMG: strcpy (type_str, "GEOTIFF"); break; case BMP_IMG: strcpy (type_str, "BMP"); break; case GIF_IMG: strcpy (type_str, "GIF"); break; case PNG_IMG: strcpy (type_str, "PNG"); break; case UNKNOWN_GRAPHICS_TYPE: default: strcpy(type_str, "UNRECOGNIZED"); break; } } void calc_asf_complex_image_stats_2files(char *inFile1, char *inFile2, complex_stats_t *inFile1_complex_stats, complex_stats_t *inFile2_complex_stats, complex_psnr_t *psnr, int band) { char *f1; char *f2; char inFile1_meta[255], inFile2_meta[255]; char **band_names1 = NULL; char **band_names2 = NULL; char *c; int band_count1, band_count2; complex_stats_t *cs1 = inFile1_complex_stats; complex_stats_t *cs2 = inFile2_complex_stats; meta_parameters *md1 = NULL; meta_parameters *md2 = NULL; // Init stats // Presumed innocent until proven guilty cs1->i.stats_good = cs2->i.stats_good = 1; cs1->i.min = cs2->i.min = 0.0; cs1->i.max = cs2->i.max = 0.0; cs1->i.mean = cs2->i.mean = 0.0; cs1->i.sdev = cs2->i.sdev = 0.0; cs1->i.rmse = cs2->i.rmse = 0.0; psnr->i.psnr = 0.0; psnr->i.psnr_good = 0; // Presumed innocent until proven guilty cs1->q.stats_good = cs2->q.stats_good = 1; cs1->q.min = cs2->q.min = 0.0; cs1->q.max = cs2->q.max = 0.0; cs1->q.mean = cs2->q.mean = 0.0; cs1->q.sdev = cs2->q.sdev = 0.0; cs1->q.rmse = cs2->q.rmse = 0.0; psnr->q.psnr = 0.0; psnr->q.psnr_good = 0; // Read metadata and check for multi-bandedness if (inFile1 != NULL && strlen(inFile1) > 0) { f1 = STRDUP(inFile1); c = findExt(f1); *c = '\0'; sprintf(inFile1_meta, "%s.meta", f1); if (fileExists(inFile1_meta)) { md1 = meta_read(inFile1_meta); cs1->i.stats_good = (md1 != NULL) ? cs1->i.stats_good : 0; cs1->q.stats_good = (md1 != NULL) ? cs1->q.stats_good : 0; } } else { cs1->i.stats_good = 0; cs1->i.stats_good = 0; } if (inFile2 != NULL && strlen(inFile2) > 0) { f2 = STRDUP(inFile2); c = findExt(f2); *c = '\0'; sprintf(inFile2_meta, "%s.meta", f2); if (fileExists(inFile2_meta)) { md2 = meta_read(inFile2_meta); cs2->i.stats_good = (md2 != NULL) ? cs2->i.stats_good : 0; cs2->q.stats_good = (md2 != NULL) ? cs2->q.stats_good : 0; } } else { cs2->i.stats_good = 0; cs2->q.stats_good = 0; } band_count1 = (md1 != NULL) ? md1->general->band_count : 0; band_count2 = (md2 != NULL) ? md2->general->band_count : 0; // Calculate the stats from the data. cs1->i.hist = NULL; cs1->i.hist_pdf = NULL; cs1->q.hist = NULL; cs1->q.hist_pdf = NULL; cs2->i.hist = NULL; cs2->i.hist_pdf = NULL; cs2->q.hist = NULL; cs2->q.hist_pdf = NULL; if (band_count1 > 0 && md1 != NULL) { band_names1 = extract_band_names(md1->general->bands, md1->general->band_count); if (band_names1 != NULL) { asfPrintStatus("\nCalculating statistics for %s band in %s", band_names1[band], inFile1); calc_complex_stats_rmse_from_file(inFile1, band_names1[band], md1->general->no_data, &cs1->i.min, &cs1->i.max, &cs1->i.mean, &cs1->i.sdev, &cs1->i.rmse, &cs1->i.hist, &cs1->q.min, &cs1->q.max, &cs1->q.mean, &cs1->q.sdev, &cs1->q.rmse, &cs1->q.hist); } } if (band_count2 > 0 && md2 != NULL) { band_names2 = extract_band_names(md2->general->bands, md2->general->band_count); if (band_names2 != NULL) { asfPrintStatus("\nCalculating statistics for %s band in %s", band_names2[band], inFile2); calc_complex_stats_rmse_from_file(inFile2, band_names2[band], md2->general->no_data, &cs2->i.min, &cs2->i.max, &cs2->i.mean, &cs2->i.sdev, &cs2->i.rmse, &cs2->i.hist, &cs2->q.min, &cs2->q.max, &cs2->q.mean, &cs2->q.sdev, &cs2->q.rmse, &cs2->q.hist); } } // Calculate the peak signal to noise ratio (PSNR) between the two images double sse_i, sse_q; double rmse_i, rmse_q; int ii, jj; int band1 = band; int band2 = band; long pixel_count = 0; long lines, samples; long offset1 = md1->general->line_count * band1; long offset2 = md2->general->line_count * band2; float max_val; complexFloat *cdata1 = NULL; // components: real, imag complexFloat *cdata2 = NULL; if (md1 != NULL && md2 != NULL) { cdata1 = (complexFloat *)CALLOC(md1->general->sample_count, sizeof(complexFloat)); cdata2 = (complexFloat *)CALLOC(md2->general->sample_count, sizeof(complexFloat)); if (cdata1 == NULL || cdata2 == NULL || (md1->general->data_type != md2->general->data_type)) { psnr->i.psnr = MISSING_PSNR; psnr->i.psnr_good = 0; psnr->q.psnr = MISSING_PSNR; psnr->q.psnr_good = 0; } else { asfPrintStatus("\nCalculating PSNR between\n Band %s in %s and\n " "Band %s in %s\n", band_names1[band1], inFile1, band_names2[band2], inFile2); FILE *fp1 = fopen(inFile1, "rb"); FILE *fp2 = fopen(inFile2, "rb"); if (fp1 != NULL && fp2 != NULL) { sse_i = 0.0; sse_q = 0.0; max_val = get_maxval(md1->general->data_type); lines = MIN(md1->general->line_count, md2->general->line_count); if (lines < md1->general->line_count) { asfPrintWarning("File2 has fewer lines than File1 (%d v. %d).\n" "Only the first %d lines will be utilized for PSNR " "calculation\n", md2->general->line_count, md1->general->line_count, lines); } if (lines < md2->general->line_count) { asfPrintWarning("File1 has fewer lines than File2 (%d v. %d).\n" "Only the first %d lines will be utilized for PSNR " "calculation\n", md1->general->line_count, md2->general->line_count, lines); } samples = MIN(md1->general->sample_count, md2->general->sample_count); if (samples < md1->general->sample_count) { asfPrintWarning("File2 has fewer samples per line than File1 " "(%d v. %d).\nOnly the first %d samples within each " "line of data will be utilized for PSNR " "calculation\n", md2->general->sample_count, md1->general->sample_count, samples); } if (samples < md2->general->sample_count) { asfPrintWarning("File1 has fewer samples per line than File2 " "(%d v. %d).\nOnly the first %d samples within each " "line of data will be utilized for PSNR " "calculation\n", md1->general->sample_count, md2->general->sample_count, samples); } for (ii=0; ii<lines; ++ii) { asfPercentMeter((double)ii/(double)lines); get_complexFloat_line(fp1, md1, ii + offset1, cdata1); get_complexFloat_line(fp2, md2, ii + offset2, cdata2); for (jj=0; jj<samples; ++jj) { sse_i += (cdata1[jj].imag - cdata2[jj].imag) * (cdata1[jj].imag - cdata2[jj].imag); sse_q += (cdata1[jj].real - cdata2[jj].real) * (cdata1[jj].real - cdata2[jj].real); pixel_count++; } } asfPercentMeter(1.0); if (fp1) FCLOSE(fp1); if (fp2) FCLOSE(fp2); if (pixel_count > 0 && max_val > 0) { rmse_i = sqrt(sse_i/pixel_count); rmse_q = sqrt(sse_q/pixel_count); psnr->i.psnr = 10.0 * log10(max_val/(rmse_i+.00000000000001)); psnr->i.psnr_good = 1; psnr->q.psnr = 10.0 * log10(max_val/(rmse_q+.00000000000001)); psnr->q.psnr_good = 1; } else { psnr->i.psnr = MISSING_PSNR; psnr->i.psnr_good = 0; psnr->q.psnr = MISSING_PSNR; psnr->q.psnr_good = 0; } } else { psnr->i.psnr = MISSING_PSNR; psnr->i.psnr_good = 0; psnr->q.psnr = MISSING_PSNR; psnr->q.psnr_good = 0; } } } else { psnr->i.psnr = MISSING_PSNR; psnr->i.psnr_good = 0; psnr->q.psnr = MISSING_PSNR; psnr->q.psnr_good = 0; } // Cleanup and be gone FREE(f1); FREE(f2); if (band_names1 != NULL && md1 != NULL) { for (ii=0; ii<md1->general->band_count; ii++) { if (band_names1[ii] != NULL) FREE(band_names1[ii]); } FREE(band_names1); } if (band_names2 != NULL && md2 != NULL) { for (ii=0; ii<md2->general->band_count; ii++) { if (band_names2[ii] != NULL) FREE(band_names2[ii]); } FREE(band_names2); } FREE(cdata1); FREE(cdata2); if (md1 != NULL) meta_free(md1); if (md2 != NULL) meta_free(md2); } void calc_asf_img_stats_2files(char *inFile1, char *inFile2, stats_t *inFile1_stats, stats_t *inFile2_stats, psnr_t *psnr, int band) { char *f1; char *f2; char inFile1_meta[255], inFile2_meta[255]; char **band_names1 = NULL; char **band_names2 = NULL; char *c; int band_count1, band_count2; stats_t *s1 = inFile1_stats; stats_t *s2 = inFile2_stats; meta_parameters *md1 = NULL; meta_parameters *md2 = NULL; // Init stats s1->stats_good = s2->stats_good = 1; // Presumed innocent until proven guilty s1->min = s2->min = 0.0; s1->max = s2->max = 0.0; s1->mean = s2->mean = 0.0; s1->sdev = s2->sdev = 0.0; s1->rmse = s2->rmse = 0.0; psnr->psnr = 0.0; // Read metadata and check for multi-bandedness if (inFile1 != NULL && strlen(inFile1) > 0) { f1 = STRDUP(inFile1); c = findExt(f1); *c = '\0'; sprintf(inFile1_meta, "%s.meta", f1); if (fileExists(inFile1_meta)) { md1 = meta_read(inFile1_meta); s1->stats_good = (md1 != NULL) ? s1->stats_good : 0; } } else { s1->stats_good = 0; } if (inFile2 != NULL && strlen(inFile2) > 0) { f2 = STRDUP(inFile2); c = findExt(f2); *c = '\0'; sprintf(inFile2_meta, "%s.meta", f2); if (fileExists(inFile2_meta)) { md2 = meta_read(inFile2_meta); s2->stats_good = (md2 != NULL) ? s2->stats_good : 0; } } else { s2->stats_good = 0; } band_count1 = (md1 != NULL) ? md1->general->band_count : 0; band_count2 = (md2 != NULL) ? md2->general->band_count : 0; // Calculate the stats from the data. s1->hist = NULL; s1->hist_pdf = NULL; s2->hist = NULL; s2->hist_pdf = NULL; if (band_count1 > 0 && md1 != NULL) { band_names1 = extract_band_names(md1->general->bands, md1->general->band_count); if (band_names1 != NULL) { asfPrintStatus("\nCalculating statistics for %s band in %s", band_names1[band], inFile1); calc_stats_rmse_from_file(inFile1, band_names1[band], md1->general->no_data, &s1->min, &s1->max, &s1->mean, &s1->sdev, &s1->rmse, &s1->hist); } } if (band_count2 > 0 && md2 != NULL) { band_names2 = extract_band_names(md2->general->bands, md2->general->band_count); if (band_names2 != NULL) { asfPrintStatus("\nCalculating statistics for %s band in %s", band_names2[band], inFile2); calc_stats_rmse_from_file(inFile2, band_names2[band], md2->general->no_data, &s2->min, &s2->max, &s2->mean, &s2->sdev, &s2->rmse, &s2->hist); } } // Calculate the peak signal to noise ratio (PSNR) between the two images double sse; double rmse; int ii, jj; int band1 = band; int band2 = band; long pixel_count = 0; long lines, samples; long offset1 = md1->general->line_count * band1; long offset2 = md2->general->line_count * band2; float max_val; float *data1; float *data2; if (md1 != NULL && md2 != NULL) { data1 = (float*)MALLOC(sizeof(float) * md1->general->sample_count); data2 = (float*)MALLOC(sizeof(float) * md2->general->sample_count); if (data1 == NULL || data2 == NULL || (md1->general->data_type != md2->general->data_type)) { psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; } else { asfPrintStatus("\nCalculating PSNR between\n Band %s in %s and\n "\ "Band %s in %s\n", band_names1[band1], inFile1, band_names2[band2], inFile2); FILE *fp1 = fopen(inFile1, "rb"); FILE *fp2 = fopen(inFile2, "rb"); if (fp1 != NULL && fp2 != NULL) { sse = 0.0; // Since both file's data types are the same, this is OK max_val = get_maxval(md1->general->data_type); lines = MIN(md1->general->line_count, md2->general->line_count); if (lines < md1->general->line_count) { asfPrintWarning("File2 has fewer lines than File1 (%d v. %d).\n" "Only the first %d lines will be utilized for PSNR calculation\n", md2->general->line_count, md1->general->line_count, lines); } if (lines < md2->general->line_count) { asfPrintWarning("File1 has fewer lines than File2 (%d v. %d).\n" "Only the first %d lines will be utilized for PSNR calculation\n", md1->general->line_count, md2->general->line_count, lines); } samples = MIN(md1->general->sample_count, md2->general->sample_count); if (samples < md1->general->sample_count) { asfPrintWarning("File2 has fewer samples per line than File1 (%d v. " "%d).\nOnly the first %d samples within each line of " "data will be utilized for PSNR calculation\n", md2->general->sample_count, md1->general->sample_count, samples); } if (samples < md2->general->sample_count) { asfPrintWarning("File1 has fewer samples per line than File2 (%d v. " "%d).\nOnly the first %d samples within each line of " "data will be utilized for PSNR calculation\n", md1->general->sample_count, md2->general->sample_count, samples); } for (ii=0; ii<lines; ++ii) { asfPercentMeter((double)ii/(double)lines); get_float_line(fp1, md1, ii + offset1, data1); get_float_line(fp2, md2, ii + offset2, data2); for (jj=0; jj<samples; ++jj) { sse += (data1[jj] - data2[jj]) * (data1[jj] - data2[jj]); pixel_count++; } } asfPercentMeter(1.0); if (fp1) FCLOSE(fp1); if (fp2) FCLOSE(fp2); if (pixel_count > 0 && max_val > 0) { rmse = sqrt(sse/pixel_count); psnr->psnr = 10.0 * log10(max_val/(rmse+.00000000000001)); psnr->psnr_good = 1; } else { psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; } } else { psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; } } } else { psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; } // Cleanup and begone if (f1 != NULL) FREE(f1); if (f2 != NULL) FREE(f2); if (band_names1 != NULL && md1 != NULL) { for (ii=0; ii<md1->general->band_count; ii++) { if (band_names1[ii] != NULL) FREE(band_names1[ii]); } FREE(band_names1); } if (band_names2 != NULL && md2 != NULL) { for (ii=0; ii<md2->general->band_count; ii++) { if (band_names2[ii] != NULL) FREE(band_names2[ii]); } FREE(band_names2); } if (data1 != NULL) FREE(data1); if (data2 != NULL) FREE(data2); if (md1 != NULL) meta_free(md1); if (md2 != NULL) meta_free(md2); } void calc_jpeg_stats_2files(char *inFile1, char *inFile2, char *outfile, stats_t *inFile1_stats, stats_t *inFile2_stats, psnr_t *psnr, int band) { stats_t *s1 = inFile1_stats; stats_t *s2 = inFile2_stats; // Init stats s1->stats_good = s2->stats_good = 0; s1->min = s2->min = 0.0; s1->max = s2->max = 0.0; s1->mean = s2->mean = 0.0; s1->sdev = s2->sdev = 0.0; s1->rmse = s2->rmse = 0.0; s1->hist = s2->hist = NULL; s1->hist_pdf = s2->hist_pdf = NULL; psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; jpeg_image_band_statistics_from_file(inFile1, outfile, band, &s1->stats_good, &s1->min, &s1->max, &s1->mean, &s1->sdev, &s1->rmse, 0, UINT8_IMAGE_DEFAULT_MASK); jpeg_image_band_statistics_from_file(inFile2, outfile, band, &s2->stats_good, &s2->min, &s2->max, &s2->mean, &s2->sdev, &s2->rmse, 0, UINT8_IMAGE_DEFAULT_MASK); jpeg_image_band_psnr_from_files(inFile1, inFile2, outfile, band, band, psnr); } void calc_ppm_pgm_stats_2files(char *inFile1, char *inFile2, char *outfile, stats_t *inFile1_stats, stats_t *inFile2_stats, psnr_t *psnr, int band) { stats_t *s1 = inFile1_stats; stats_t *s2 = inFile2_stats; // Init stats s1->stats_good = s2->stats_good = 0; s1->min = s2->min = 0.0; s1->max = s2->max = 0.0; s1->mean = s2->mean = 0.0; s1->sdev = s2->sdev = 0.0; s1->rmse = s2->rmse = 0.0; s1->hist = s2->hist = NULL; s1->hist_pdf = s2->hist_pdf = NULL; psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; ppm_pgm_image_band_statistics_from_file(inFile1, outfile, band, &s1->stats_good, &s1->min, &s1->max, &s1->mean, &s1->sdev, &s1->rmse, 0, UINT8_IMAGE_DEFAULT_MASK); ppm_pgm_image_band_statistics_from_file(inFile2, outfile, band, &s2->stats_good, &s2->min, &s2->max, &s2->mean, &s2->sdev, &s2->rmse, 0, UINT8_IMAGE_DEFAULT_MASK); ppm_pgm_image_band_psnr_from_files(inFile1, inFile2, outfile, band, band, psnr); } void calc_tiff_stats_2files(char *inFile1, char *inFile2, stats_t *inFile1_stats, stats_t *inFile2_stats, psnr_t *psnr, int band) { stats_t *s1 = inFile1_stats; stats_t *s2 = inFile2_stats; // Init stats s1->stats_good = s2->stats_good = 0; s1->min = s2->min = 0.0; s1->max = s2->max = 0.0; s1->mean = s2->mean = 0.0; s1->sdev = s2->sdev = 0.0; s1->rmse = s2->rmse = 0.0; s1->hist = s2->hist = NULL; s1->hist_pdf = s2->hist_pdf = NULL; psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; tiff_image_band_statistics_from_file(inFile1, band, &s1->stats_good, &s1->min, &s1->max, &s1->mean, &s1->sdev, &s1->rmse, 0, FLOAT_IMAGE_DEFAULT_MASK); tiff_image_band_statistics_from_file(inFile2, band, &s2->stats_good, &s2->min, &s2->max, &s2->mean, &s2->sdev, &s2->rmse, 0, FLOAT_IMAGE_DEFAULT_MASK); tiff_image_band_psnr_from_files(inFile1, inFile2, band, band, psnr); } float get_maxval(data_type_t data_type) { float ret; // Only non-complex types with 32 bits or less are supported switch (data_type) { case BYTE: ret = pow(2, sizeof(unsigned char) * 8.0) - 1; break; case COMPLEX_BYTE: // HACK ALERT! This assumes that COMPLEX_BYTE is // from raw data off a satellite and has only 5-bit // resolution... Probably a safe assumption for diffimage ret = pow(2, 5) - 1; break; case INTEGER16: case COMPLEX_INTEGER16: ret = pow(2, sizeof(short int) * 8.0) - 1; break; case INTEGER32: case COMPLEX_INTEGER32: ret = pow(2, sizeof(int) * 8.0) - 1; break; case REAL32: case COMPLEX_REAL32: ret = MAXREAL; break; default: ret = 0.0; break; } return ret; } void print_stats_results(char *filename1, char *filename2, char *band_str1, char *band_str2, stats_t *s1, stats_t *s2, psnr_t psnr) { asfPrintStatus("\nStatistics for %s%s\n" " min: %f\n" " max: %f\n" " mean: %f\n" " sdev: %f\n" " rmse: %f\n" "result: %s\n", band_str1, filename1, s1->min, s1->max, s1->mean, s1->sdev, s1->rmse, s1->stats_good ? "GOOD STATS" : "UNRELIABLE STATS"); asfPrintStatus("\nStatistics for %s%s\n" " min: %f\n" " max: %f\n" " mean: %f\n" " sdev: %f\n" " rmse: %f\n" "result: %s\n", band_str2, filename2, s2->min, s2->max, s2->mean, s2->sdev, s2->rmse, s2->stats_good ? "GOOD STATS" : "UNRELIABLE STATS"); asfPrintStatus("\nPSNR between files: %f\n\n", psnr.psnr); } void diff_check_stats(char *outputFile, char *inFile1, char *inFile2, stats_t *stats1, stats_t *stats2, psnr_t *psnr, int strict, data_type_t data_type, int num_bands) { char msg[1024]; int band; double baseline_range1; double baseline_range2; double min_tol; double max_tol; double mean_tol; double sdev_tol; // double rmse_tol; double psnr_tol; double min_diff; double max_diff; double mean_diff; double sdev_diff; // double rmse_diff; int num_extracted_bands1=0, num_extracted_bands2=0; FILE *outputFP = NULL; int output_file_exists = 0; if (outputFile && strlen(outputFile) > 0) { outputFP = (FILE*)FOPEN(outputFile, "a"); if (outputFP) { output_file_exists = 1; } else { outputFP = stderr; output_file_exists = 0; } } else { outputFP = stderr; output_file_exists = 0; } // Get or produce band names for intelligent output... char **band_names1 = NULL; char **band_names2 = NULL; get_band_names(inFile1, outputFP, &band_names1, &num_extracted_bands1); get_band_names(inFile2, outputFP, &band_names2, &num_extracted_bands2); // Check each band for differences char band_str1[64]; char band_str2[64]; for (band=0; band<num_bands; band++) { // If differences exist, then produce an output file with content, else // produce an empty output file (handy for scripts that check for file // existence AND file size greater than zero) // Compare statistics // Assume 6-sigma range (99.999999%) is full range of data baseline_range1 = fabs(stats1[band].sdev) * 6.0; // Assume 6-sigma range (99.999999%) is full range of dat baseline_range2 = fabs(stats2[band].sdev) * 6.0; min_tol = (MIN_DIFF_TOL/100.0)*baseline_range1; max_tol = (MAX_DIFF_TOL/100.0)*baseline_range1; mean_tol = (MEAN_DIFF_TOL/100.0)*baseline_range1; sdev_tol = (SDEV_DIFF_TOL/100.0)*baseline_range1; // FIXME: Rather than use data_type, use the baseline range to develop // a suitable PSNR tolerance switch (data_type) { case BYTE: psnr_tol = BYTE_PSNR_TOL; break; case INTEGER16: psnr_tol = INTEGER16_PSNR_TOL; break; case INTEGER32: psnr_tol = INTEGER32_PSNR_TOL; break; case REAL32: default: psnr_tol = REAL32_PSNR_TOL; break; } min_diff = fabs(stats2[band].min - stats1[band].min); max_diff = fabs(stats2[band].max - stats1[band].max); mean_diff = fabs(stats2[band].mean - stats1[band].mean); sdev_diff = fabs(baseline_range2 - baseline_range1); if (strict && (stats1[band].stats_good && stats2[band].stats_good) && (min_diff > min_tol || max_diff > max_tol || mean_diff > mean_tol || sdev_diff > sdev_tol || psnr[band].psnr < psnr_tol)) { // Strict comparison utilizes all values fprintf(outputFP, "\n-----------------------------------------------\n"); if (num_bands > 1) { sprintf(band_str1, "Band %s in ", band_names1[band]); sprintf(band_str2, "Band %s in ", band_names2[band]); } else { strcpy(band_str1, ""); strcpy(band_str2, ""); } sprintf(msg, "FAIL: Comparing\n %s%s\nto\n %s%s\n\n", band_str1, inFile1, band_str2, inFile2); fprintf(outputFP, msg); sprintf(msg, "[%s] [min] File1: %12f, File2: %12f, Tolerance: %11f " "(%3f Percent)\n", min_diff > min_tol ? "FAIL" : "PASS", stats1[band].min, stats2[band].min, min_tol, MIN_DIFF_TOL); fprintf(outputFP, msg); sprintf(msg, "[%s] [max] File1: %12f, File2: %12f, Tolerance: %11f " "(%3f Percent)\n", max_diff > max_tol ? "FAIL" : "PASS", stats1[band].max, stats2[band].max, max_tol, MAX_DIFF_TOL); fprintf(outputFP, msg); sprintf(msg, "[%s] [mean] File1: %12f, File2: %12f, Tolerance: %11f " "(%3f Percent)\n", mean_diff > mean_tol ? "FAIL" : "PASS", stats1[band].mean, stats2[band].mean, mean_tol, MEAN_DIFF_TOL); fprintf(outputFP, msg); sprintf(msg, "[%s] [sdev] File1: %12f, File2: %12f, Tolerance: %11f " "(%3f Percent)\n", sdev_diff > sdev_tol ? "FAIL" : "PASS", stats1[band].sdev, stats2[band].sdev, sdev_tol/6.0, SDEV_DIFF_TOL); fprintf(outputFP, msg); if (psnr[band].psnr_good) { sprintf(msg, "[%s] [PSNR] PSNR: %12f, " "PSNR Minimum: %11f (higher == better)\n", psnr[band].psnr < psnr_tol ? "FAIL" : "PASS", psnr[band].psnr, psnr_tol); } else { sprintf(msg, "[FAIL] [PSNR] PSNR: MISSING, " "PSNR Minimum: %11f (higher == better)\n", psnr_tol); } fprintf(outputFP, msg); fprintf(outputFP, "-----------------------------------------------\n\n"); } else if (!strict && (stats1[band].stats_good && stats2[band].stats_good) && (mean_diff > mean_tol || sdev_diff > sdev_tol || psnr[band].psnr < psnr_tol)) { // If not doing strict checking, skip comparing min and max values fprintf(outputFP, "\n-----------------------------------------------\n"); char msg[1024]; if (num_bands > 1) { sprintf(band_str1, "Band %s in ", band_names1[band]); sprintf(band_str2, "Band %s in ", band_names2[band]); } else { strcpy(band_str1, ""); strcpy(band_str2, ""); } sprintf(msg, "FAIL: Comparing\n %s%s\nto\n %s%s\n\n", band_str1, inFile1, band_str2, inFile2); fprintf(outputFP, msg); sprintf(msg, "[%s] [mean] File1: %12f, File2: %12f, Tolerance: %11f " "(%3f Percent)\n", mean_diff > mean_tol ? "FAIL" : "PASS", stats1[band].mean, stats2[band].mean, mean_tol, MEAN_DIFF_TOL); fprintf(outputFP, msg); sprintf(msg, "[%s] [sdev] File1: %12f, File2: %12f, Tolerance: %11f " "(%3f Percent)\n", sdev_diff > sdev_tol ? "FAIL" : "PASS", stats1[band].sdev, stats2[band].sdev, sdev_tol/6.0, SDEV_DIFF_TOL); fprintf(outputFP, msg); if (psnr[band].psnr_good) { sprintf(msg, "[%s] [PSNR] PSNR: %12f, " "PSNR Minimum: %11f (higher == better)\n", psnr[band].psnr < psnr_tol ? "FAIL" : "PASS", psnr[band].psnr, psnr_tol); } else { sprintf(msg, "[FAIL] [PSNR] PSNR: MISSING, " "PSNR Minimum: %11f (higher == better)\n", psnr_tol); } fprintf(outputFP, msg); fprintf(outputFP, "-----------------------------------------------\n\n"); } else if (stats1[band].stats_good && stats2[band].stats_good) { if (num_bands > 1) { sprintf(band_str1, "Band %s in ", band_names1[band]); sprintf(band_str2, "Band %s in ", band_names2[band]); } else { strcpy(band_str1, ""); strcpy(band_str2, ""); } asfPrintStatus("\nNo differences found in Image Statistics when " "comparing\n %s%s to\n %s%s\n\n", band_str1, inFile1, band_str2, inFile2); print_stats_results(inFile1, inFile2, band_str1, band_str2, &stats1[band], &stats2[band], psnr[band]); } if (!stats1[band].stats_good || !stats2[band].stats_good) { char msg[1024]; fprintf(outputFP, "\n-----------------------------------------------\n"); if (num_bands > 1) { sprintf(band_str1, "Band %s in ", band_names1[band]); sprintf(band_str2, "Band %s in ", band_names2[band]); } else { strcpy(band_str1, ""); strcpy(band_str2, ""); } if (!stats1[band].stats_good) { sprintf(msg, "FAIL: %s%s image statistics missing.\n", band_str1, inFile1); fprintf(outputFP, msg); } if (!stats2[band].stats_good) { sprintf(msg, "FAIL: %s%s image statistics missing.\n", band_str2, inFile2); fprintf(outputFP, msg); } fprintf(outputFP, "-----------------------------------------------\n\n"); } } // For each band if (output_file_exists && outputFP) FCLOSE(outputFP); free_band_names(&band_names1, num_extracted_bands1); free_band_names(&band_names2, num_extracted_bands2); } void diffErrOut(char *outputFile, char *err_msg) { char msg[1024]; FILE *outputFP = NULL; if (outputFile != NULL && strlen(outputFile) > 0) { outputFP = FOPEN(outputFile, "a"); fprintf(outputFP, "\n-----------------------------------------------\n"); sprintf(msg, "FAIL: %s\n", err_msg); fprintf(outputFP, msg); fprintf(outputFP, "-----------------------------------------------\n\n"); if (outputFP) FCLOSE(outputFP); } else { fprintf(stderr, "\n-----------------------------------------------\n"); sprintf(msg, "FAIL: %s\n", err_msg); fprintf(stderr, msg); fprintf(stderr, "-----------------------------------------------\n\n"); } } void get_tiff_info_from_file(char *file, tiff_data_t *t) { TIFF *tif; t->sample_format = MISSING_TIFF_DATA; t->bits_per_sample = MISSING_TIFF_DATA; t->planar_config = MISSING_TIFF_DATA; t->data_type = 0; t->num_bands = 0; t->is_scanline_format = 0; t->height = 0; t->width = 0; tif = XTIFFOpen(file, "rb"); if (tif != NULL) { get_tiff_info(tif, t); } XTIFFClose(tif); } void get_tiff_info(TIFF *tif, tiff_data_t *t) { get_tiff_data_config(tif, &t->sample_format, &t->bits_per_sample, &t->planar_config, &t->data_type, &t->num_bands, &t->is_scanline_format, &t->is_palette_color_tiff, REPORT_LEVEL_WARNING); TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &t->height); TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &t->width); if (t->planar_config != PLANARCONFIG_CONTIG && t->planar_config != PLANARCONFIG_SEPARATE && t->num_bands == 1) { t->planar_config = PLANARCONFIG_CONTIG; } } void get_geotiff_keys(char *file, geotiff_data_t *g) { TIFF *tif = XTIFFOpen(file, "rb"); GTIF *gtif = NULL; // Init values to 'missing' g->gtif_data_exists = 0; g->GTcitation = NULL; // Should be unallocated g->PCScitation = NULL; // Should be unallocated // Read geotiff info if (tif != NULL) { gtif = GTIFNew(tif); if (gtif != NULL) { int count, read_count; int citation_length; int typeSize; tagtype_t citation_type; // Get citations citation_length = GTIFKeyInfo(gtif, GTCitationGeoKey, &typeSize, &citation_type); if (citation_length > 0) { g->GTcitation = (char*)MALLOC(citation_length * typeSize); GTIFKeyGet(gtif, GTCitationGeoKey, g->GTcitation, 0, citation_length); } else { g->GTcitation = NULL; } citation_length = GTIFKeyInfo(gtif, PCSCitationGeoKey, &typeSize, &citation_type); if (citation_length > 0) { g->PCScitation = (char*)MALLOC(citation_length * typeSize); GTIFKeyGet(gtif, PCSCitationGeoKey, g->PCScitation, 0, citation_length); } else { g->PCScitation = NULL; } if ((g->GTcitation != NULL && strlen(g->GTcitation) > 0) || (g->PCScitation != NULL && strlen(g->PCScitation) > 0)) { g->gtif_data_exists = 1; } // Get tie points and pixel scale (gtif->gt_methods.get) (gtif->gt_tif, GTIFF_TIEPOINTS, &count, &g->tie_point); if (count >= 6) { g->gtif_data_exists = 1; g->tie_point_elements = count; g->num_tie_points = count / 6; } (gtif->gt_methods.get) (gtif->gt_tif, GTIFF_PIXELSCALE, &count, &g->pixel_scale); if (count >= 3) { g->gtif_data_exists = 1; g->pixel_scale_elements = count; g->num_pixel_scales = count / 3; } // Get model type, raster type, and linear units read_count = GTIFKeyGet (gtif, GTModelTypeGeoKey, &g->model_type, 0, 1); if (read_count >= 1) g->gtif_data_exists = 1; read_count = GTIFKeyGet (gtif, GTRasterTypeGeoKey, &g->raster_type, 0, 0); if (read_count >= 1) g->gtif_data_exists = 1; read_count = GTIFKeyGet (gtif, ProjLinearUnitsGeoKey, &g->linear_units, 0, 1); if (read_count >= 1) g->gtif_data_exists = 1; // Get UTM related info if it exists read_count = GTIFKeyGet(gtif, ProjectedCSTypeGeoKey, &g->pcs, 0, 1); if (read_count == 1 && PCS_2_UTM(g->pcs, &g->hemisphere, &g->datum, &g->pro_zone)) { g->gtif_data_exists = 1; } else { read_count = GTIFKeyGet(gtif, ProjectionGeoKey, &g->pcs, 0, 1); if (read_count == 1 && PCS_2_UTM(g->pcs, &g->hemisphere, &g->datum, &g->pro_zone)) { g->gtif_data_exists = 1; } else { g->hemisphere = '\0'; g->datum = UNKNOWN_DATUM; g->pro_zone = MISSING_GTIF_DATA; } } // Get projection type (ProjCoordTransGeoKey) and other projection parameters read_count = GTIFKeyGet(gtif, ProjCoordTransGeoKey, &g->proj_coords_trans, 0, 1); if (read_count >= 1) g->gtif_data_exists = 1; else g->proj_coords_trans = MISSING_GTIF_DATA; read_count = GTIFKeyGet(gtif, GeographicTypeGeoKey, &g->geographic_datum, 0, 1); if (read_count >= 1) g->gtif_data_exists = 1; else g->geographic_datum = MISSING_GTIF_DATA; read_count = GTIFKeyGet(gtif, GeogGeodeticDatumGeoKey, &g->geodetic_datum, 0, 1); if (read_count >= 1) g->gtif_data_exists = 1; else g->geodetic_datum = MISSING_GTIF_DATA; read_count = GTIFKeyGet(gtif, ProjScaleAtNatOriginGeoKey, &g->scale_factor, 0, 1); if (read_count >= 1) g->gtif_data_exists = 1; else g->scale_factor = MISSING_GTIF_DATA; // Get generic projection parameters (Note: projection type is defined by // the g->proj_coords_trans value) read_count = GTIFKeyGet (gtif, ProjFalseEastingGeoKey, &g->false_easting, 0, 1); if (read_count >= 1) g->gtif_data_exists = 1; else g->false_easting = MISSING_GTIF_DATA; read_count = GTIFKeyGet (gtif, ProjFalseNorthingGeoKey, &g->false_northing, 0, 1); if (read_count >= 1) g->gtif_data_exists = 1; else g->false_northing = MISSING_GTIF_DATA; read_count = GTIFKeyGet (gtif, ProjNatOriginLongGeoKey, &g->natLonOrigin, 0, 1); if (read_count >= 1) g->gtif_data_exists = 1; else g->natLonOrigin = MISSING_GTIF_DATA; read_count = GTIFKeyGet (gtif, ProjNatOriginLatGeoKey, &g->natLatOrigin, 0, 1); if (read_count >= 1) g->gtif_data_exists = 1; else g->natLatOrigin = MISSING_GTIF_DATA; read_count = GTIFKeyGet (gtif, ProjStdParallel1GeoKey, &g->stdParallel1, 0, 1); if (read_count >= 1) g->gtif_data_exists = 1; else g->stdParallel1 = MISSING_GTIF_DATA; read_count = GTIFKeyGet (gtif, ProjStdParallel2GeoKey, &g->stdParallel2, 0, 1); if (read_count >= 1) g->gtif_data_exists = 1; else g->stdParallel2 = MISSING_GTIF_DATA; read_count = GTIFKeyGet (gtif, ProjCenterLongGeoKey, &g->lonCenter, 0, 1); if (read_count >= 1) g->gtif_data_exists = 1; else g->lonCenter = MISSING_GTIF_DATA; read_count = GTIFKeyGet (gtif, ProjCenterLatGeoKey, &g->latCenter, 0, 1); if (read_count >= 1) g->gtif_data_exists = 1; else g->latCenter = MISSING_GTIF_DATA; read_count = GTIFKeyGet (gtif, ProjFalseOriginLongGeoKey, &g->falseOriginLon, 0, 1); if (read_count >= 1) g->gtif_data_exists = 1; else g->falseOriginLon = MISSING_GTIF_DATA; read_count = GTIFKeyGet (gtif, ProjFalseOriginLatGeoKey, &g->falseOriginLat, 0, 1); if (read_count >= 1) g->gtif_data_exists = 1; else g->falseOriginLat = MISSING_GTIF_DATA; read_count = GTIFKeyGet (gtif, ProjStraightVertPoleLongGeoKey, &g->lonPole, 0, 1); if (read_count >= 1) g->gtif_data_exists = 1; else g->lonPole = MISSING_GTIF_DATA; } } } void diff_check_geotiff(char *outfile, geotiff_data_t *g1, geotiff_data_t *g2) { int failed=0; int i; int num_tie_points, num_pixel_scales; char dummy_hem; datum_type_t dummy_datum; unsigned long dummy_zone; projection_type_t projection_type1, projection_type2; FILE *outputFP = NULL; // FIXME: This stuff needs to be projection type-specific since I have to use // lat/lon together with latLon2utm() and check geolocations in meters // (due to longitude convergence at the poles) // Determine projection types if (PCS_2_UTM(g1->pcs, &dummy_hem, &dummy_datum, &dummy_zone)) { projection_type1 = UNIVERSAL_TRANSVERSE_MERCATOR; } else { switch(g1->proj_coords_trans) { case CT_TransverseMercator: case CT_TransvMercator_Modified_Alaska: case CT_TransvMercator_SouthOriented: projection_type1 = UNIVERSAL_TRANSVERSE_MERCATOR; break; case CT_AlbersEqualArea: projection_type1 = ALBERS_EQUAL_AREA; break; case CT_LambertConfConic_1SP: case CT_LambertConfConic_2SP: projection_type1 = LAMBERT_CONFORMAL_CONIC; break; case CT_PolarStereographic: projection_type1 = POLAR_STEREOGRAPHIC; break; case CT_LambertAzimEqualArea: projection_type1 = LAMBERT_AZIMUTHAL_EQUAL_AREA; break; default: projection_type1 = MISSING_GTIF_DATA; break; } } if (PCS_2_UTM(g2->pcs, &dummy_hem, &dummy_datum, &dummy_zone)) { projection_type2 = UNIVERSAL_TRANSVERSE_MERCATOR; } else { switch(g2->proj_coords_trans) { case CT_TransverseMercator: case CT_TransvMercator_Modified_Alaska: case CT_TransvMercator_SouthOriented: projection_type2 = UNIVERSAL_TRANSVERSE_MERCATOR; break; case CT_AlbersEqualArea: projection_type2 = ALBERS_EQUAL_AREA; break; case CT_LambertConfConic_1SP: case CT_LambertConfConic_2SP: projection_type2 = LAMBERT_CONFORMAL_CONIC; break; case CT_PolarStereographic: projection_type2 = POLAR_STEREOGRAPHIC; break; case CT_LambertAzimEqualArea: projection_type2 = LAMBERT_AZIMUTHAL_EQUAL_AREA; break; default: projection_type2 = MISSING_GTIF_DATA; break; } } ///////////////// Check for failures ///////////////// //// // Check tie points and pixel scale if (g1->tie_point_elements != g2->tie_point_elements || g1->num_tie_points != g2->num_tie_points || g1->pixel_scale_elements != g2->pixel_scale_elements || g1->num_pixel_scales != g2->num_pixel_scales) { failed = 1; } num_tie_points = MIN(g1->num_tie_points, g2->num_tie_points); num_pixel_scales = MIN(g1->num_pixel_scales, g2->num_pixel_scales); for (i=0; i<num_tie_points; i++) { if (g1->tie_point[i] - g2->tie_point[i] > PROJ_LOC_DIFF_TOL_m) failed = 1; } for (i=0; i<num_pixel_scales; i++) { if (g1->pixel_scale[i] != g2->pixel_scale[i]) failed = 1; } // Perform comparison based on projection type if (!(g1->gtif_data_exists && g2->gtif_data_exists)) { failed=1; } switch (projection_type1) { case UNIVERSAL_TRANSVERSE_MERCATOR: if (g1->pcs != g2->pcs || projection_type1 != projection_type2 || g1->scale_factor != g2->scale_factor) failed = 1; break; case ALBERS_EQUAL_AREA: if (g1->proj_coords_trans != g2->proj_coords_trans || g1->stdParallel1 != g2->stdParallel1 || g1->stdParallel2 != g2->stdParallel2 || g1->false_easting != g2->false_easting || g1->false_northing != g2->false_northing || g1->natLonOrigin != g2->natLonOrigin || g1->lonCenter != g2->lonCenter || g1->natLatOrigin != g2->natLatOrigin) failed=1; break; case LAMBERT_CONFORMAL_CONIC: if (g1->proj_coords_trans != g2->proj_coords_trans || g1->stdParallel1 != g2->stdParallel1 || g1->stdParallel2 != g2->stdParallel2 || g1->false_easting != g2->false_easting || g1->false_northing != g2->false_northing || g1->natLonOrigin != g2->natLonOrigin || g1->natLatOrigin != g2->natLatOrigin || g1->falseOriginLon != g2->falseOriginLon || g1->falseOriginLat != g2->falseOriginLat || g1->scale_factor != g2->scale_factor) failed=1; break; case POLAR_STEREOGRAPHIC: if (g1->proj_coords_trans != g2->proj_coords_trans || g1->natLatOrigin != g2->natLatOrigin || g1->lonPole != g2->lonPole || g1->false_easting != g2->false_easting || g1->false_northing != g2->false_northing) failed=1; break; case LAMBERT_AZIMUTHAL_EQUAL_AREA: if (g1->proj_coords_trans != g2->proj_coords_trans || g1->false_easting != g2->false_easting || g1->false_northing != g2->false_northing || g1->lonCenter != g2->lonCenter || g1->latCenter != g2->latCenter) failed=1; break; case LAT_LONG_PSEUDO_PROJECTION: break; default: failed=1; break; } ///////////////// Report failures ///////////////// //// // Report results if the comparisons failed int out_file_exists = 0; if (outfile && strlen(outfile) > 0) { outputFP = fopen(outfile, "a"); if (outputFP == NULL) { // Failed to open output file asfPrintWarning("Cannot open output file for reporting geotiff file " "differences. Output\n" "will be directed to stderr (only)\n"); } else { out_file_exists = 1; } } else { outputFP = stderr; out_file_exists = 0; } if (failed) { char msg[1024]; fprintf(outputFP, "\n-----------------------------------------------\n"); // Report results based on projection type if (!g1->gtif_data_exists) { sprintf(msg, "ERROR: GeoTIFF data not found in File1\n"); fprintf(outputFP, msg); } if (!g2->gtif_data_exists) { sprintf(msg, "ERROR: GeoTIFF data not found in File2\n"); fprintf(outputFP, msg); } if (projection_type1 != projection_type2) { char type_str1[256], type_str2[256]; projection_type_2_str(projection_type1, type_str1); projection_type_2_str(projection_type2, type_str2); sprintf(msg, "Projection type found in File1\n %s\nnot equal to " "projection type in File2\n %s\n", type_str1, type_str2); fprintf(outputFP, msg); } if (g1->tie_point_elements != g2->tie_point_elements || g1->tie_point_elements % 6 != 0 || g2->tie_point_elements % 6 != 0) { sprintf(msg,"Input files have differing or invalid numbers of tie point " "elements:\n" " File1: %d tie point elements\n" " File2: %d tie point elements\n", g1->tie_point_elements, g2->tie_point_elements); fprintf(outputFP, msg); } if (g1->num_tie_points != g2->num_tie_points) { sprintf(msg,"Input files have differing numbers of tie points:\n" " File1: %d tie points\n" " File2: %d tie points\n", g1->num_tie_points, g2->num_tie_points); fprintf(outputFP, msg); } for (i=0; i<num_tie_points; i++) { if (g1->tie_point[i] - g2->tie_point[i] > PROJ_LOC_DIFF_TOL_m) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->tie_point[i]); sprintf(tmp2,"%f", g2->tie_point[i]); sprintf(msg, " Tie point element #%d differs:\n" " File1: %s\n" " File2: %s\n", i, g1->tie_point[i] != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->tie_point[i] != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } } if (g1->pixel_scale_elements != g2->pixel_scale_elements || g1->pixel_scale_elements % 3 != 0 || g2->pixel_scale_elements % 3 != 0) { sprintf(msg,"Input files have differing or invalid numbers of pixel " "scale elements:\n" " File1: %d pixel scale elements\n" " File2: %d pixel scale elements\n", g1->pixel_scale_elements, g2->pixel_scale_elements); fprintf(outputFP, msg); } if (g1->num_pixel_scales != g2->num_pixel_scales) { sprintf(msg,"Input files have differing numbers of pixel scales:\n" " File1: %d pixel scales\n" " File2: %d pixel scales\n", g1->num_pixel_scales, g2->num_pixel_scales); fprintf(outputFP, msg); } for (i=0; i<num_pixel_scales; i++) { if (g1->pixel_scale[i] - g2->pixel_scale[i] > PROJ_LOC_DIFF_TOL_m) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->pixel_scale[i]); sprintf(tmp2,"%f", g2->pixel_scale[i]); sprintf(msg, " Pixel scale element #%d differs:\n" " File1: %s\n" " File2: %s\n", i, g1->pixel_scale[i] != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->pixel_scale[i] != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } } if (g1->gtif_data_exists && g2->gtif_data_exists && projection_type1 == projection_type2) { switch (projection_type1) { case UNIVERSAL_TRANSVERSE_MERCATOR: if (g1->pcs != g2->pcs || g1->scale_factor != g2->scale_factor) { sprintf(msg, "UTM Projections with differences found: \n\n"); fprintf(outputFP, msg); } if (g1->pcs != g2->pcs) { char tmp1[16], tmp2[16], *tmp3, *tmp4; sprintf(tmp1,"%d", g1->pcs); sprintf(tmp2,"%d", g2->pcs); tmp3 = pcs2description(g1->pcs); tmp4 = pcs2description(g2->pcs); sprintf(msg, " PCS value from ProjectedCSTypeGeoKey or " "ProjectionGeoKey differ:\n" " File1: %s (%s)\n" " File2: %s (%s)\n", g1->pcs != MISSING_GTIF_DATA ? tmp1 : "MISSING", tmp3, g2->pcs != MISSING_GTIF_DATA ? tmp2 : "MISSING", tmp4); FREE(tmp3); FREE(tmp4); fprintf(outputFP, msg); } if (g1->scale_factor != g2->scale_factor) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->scale_factor); sprintf(tmp2,"%f", g2->scale_factor); sprintf(msg, " UTM scale factors differ:\n" " File1: %s\n" " File2: %s\n", g1->scale_factor != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->scale_factor != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } break; case ALBERS_EQUAL_AREA: if (g1->proj_coords_trans != g2->proj_coords_trans || g1->stdParallel1 != g2->stdParallel1 || g1->stdParallel2 != g2->stdParallel2 || g1->false_easting != g2->false_easting || g1->false_northing != g2->false_northing || g1->natLonOrigin != g2->natLonOrigin || g1->lonCenter != g2->lonCenter || g1->natLatOrigin != g2->natLatOrigin) { sprintf(msg, "Albers Equal Area Projections with differences found:" "\n\n"); fprintf(outputFP, msg); if (g1->proj_coords_trans != g2->proj_coords_trans) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%d", g1->proj_coords_trans); sprintf(tmp2,"%d", g2->proj_coords_trans); sprintf(msg, " Projection type code from ProjCoordTransGeoKey " "differ:\n" " File1: %s\n" " File2: %s\n", g1->proj_coords_trans != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->proj_coords_trans != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->stdParallel1 != g2->stdParallel1) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->stdParallel1); sprintf(tmp2,"%f", g2->stdParallel1); sprintf(msg, " First standard parallels differ:\n" " File1: %s\n" " File2: %s\n", g1->stdParallel1 != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->stdParallel1 != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->stdParallel2 != g2->stdParallel2) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->stdParallel2); sprintf(tmp2,"%f", g2->stdParallel2); sprintf(msg, " Second standard parallels differ:\n" " File1: %s\n" " File2: %s\n", g1->stdParallel2 != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->stdParallel2 != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->false_easting != g2->false_easting) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->false_easting); sprintf(tmp2,"%f", g2->false_easting); sprintf(msg, " False eastings differ:\n" " File1: %s\n" " File2: %s\n", g1->false_easting != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->false_easting != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->false_northing != g2->false_northing) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->false_northing); sprintf(tmp2,"%f", g2->false_northing); sprintf(msg, " False northings differ:\n" " File1: %s\n" " File2: %s\n", g1->false_northing != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->false_northing != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->natLonOrigin != g2->natLonOrigin) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->natLonOrigin); sprintf(tmp2,"%f", g2->natLonOrigin); sprintf(msg, " Central meridians (from ProjNatOriginLongGeoKey) " "differ:\n" " File1: %s\n" " File2: %s\n", g1->natLonOrigin != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->natLonOrigin != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->lonCenter != g2->lonCenter) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->lonCenter); sprintf(tmp2,"%f", g2->lonCenter); sprintf(msg, " Central meridians (from ProjCenterLongGeoKey) " "differ:\n" " File1: %s\n" " File2: %s\n", g1->lonCenter != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->lonCenter != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->natLatOrigin != g2->natLatOrigin) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->natLatOrigin); sprintf(tmp2,"%f", g2->natLatOrigin); sprintf(msg, " Latitudes of Origin (from ProjNatOriginLatGeoKey)" " differ:\n" " File1: %s\n" " File2: %s\n", g1->natLatOrigin != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->natLatOrigin != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } } break; case LAMBERT_CONFORMAL_CONIC: if (g1->proj_coords_trans != g2->proj_coords_trans || g1->stdParallel1 != g2->stdParallel1 || g1->stdParallel2 != g2->stdParallel2 || g1->false_easting != g2->false_easting || g1->false_northing != g2->false_northing || g1->natLonOrigin != g2->natLonOrigin || g1->natLatOrigin != g2->natLatOrigin || g1->falseOriginLon != g2->falseOriginLon || g1->falseOriginLat != g2->falseOriginLat || g1->scale_factor != g2->scale_factor) { sprintf(msg, "Lambert Conformal Conic Projections with differences " "found: \n\n"); fprintf(outputFP, msg); if (g1->proj_coords_trans != g2->proj_coords_trans) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%d", g1->proj_coords_trans); sprintf(tmp2,"%d", g2->proj_coords_trans); sprintf(msg, " Projection type code from ProjCoordTransGeoKey " "differ:\n" " File1: %s\n" " File2: %s\n", g1->proj_coords_trans != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->proj_coords_trans != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->stdParallel1 != g2->stdParallel1) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->stdParallel1); sprintf(tmp2,"%f", g2->stdParallel1); sprintf(msg, " First standard parallels differ:\n" " File1: %s\n" " File2: %s\n", g1->stdParallel1 != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->stdParallel1 != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->stdParallel2 != g2->stdParallel2) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->stdParallel2); sprintf(tmp2,"%f", g2->stdParallel2); sprintf(msg, " Second standard parallels differ:\n" " File1: %s\n" " File2: %s\n", g1->stdParallel2 != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->stdParallel2 != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->false_easting != g2->false_easting) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->false_easting); sprintf(tmp2,"%f", g2->false_easting); sprintf(msg, " False eastings differ:\n" " File1: %s\n" " File2: %s\n", g1->false_easting != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->false_easting != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->false_northing != g2->false_northing) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->false_northing); sprintf(tmp2,"%f", g2->false_northing); sprintf(msg, " False northings differ:\n" " File1: %s\n" " File2: %s\n", g1->false_northing != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->false_northing != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->natLonOrigin != g2->natLonOrigin) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->natLonOrigin); sprintf(tmp2,"%f", g2->natLonOrigin); sprintf(msg, " Longitudes of Origin (from ProjNatOriginLongGeoKey)" " differ:\n" " File1: %s\n" " File2: %s\n", g1->natLonOrigin != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->natLonOrigin != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->natLatOrigin != g2->natLatOrigin) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->natLatOrigin); sprintf(tmp2,"%f", g2->natLatOrigin); sprintf(msg, " Latitudes of Origin (from ProjNatOriginLatGeoKey) " "differ:\n" " File1: %s\n" " File2: %s\n", g1->natLatOrigin != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->natLatOrigin != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->falseOriginLon != g2->falseOriginLon) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->falseOriginLon); sprintf(tmp2,"%f", g2->falseOriginLon); sprintf(msg, " Longitudes of Origin (from " "ProjFalseOriginLongGeoKey) differ:\n" " File1: %s\n" " File2: %s\n", g1->falseOriginLon != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->falseOriginLon != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->falseOriginLat != g2->falseOriginLat) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->falseOriginLat); sprintf(tmp2,"%f", g2->falseOriginLat); sprintf(msg, " Latitudes of Origin (from ProjFalseOriginLatGeoKey)" " differ:\n" " File1: %s\n" " File2: %s\n", g1->falseOriginLat != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->falseOriginLat != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } } break; case POLAR_STEREOGRAPHIC: if (g1->proj_coords_trans != g2->proj_coords_trans || g1->natLatOrigin != g2->natLatOrigin || g1->lonPole != g2->lonPole || g1->false_easting != g2->false_easting || g1->false_northing != g2->false_northing) { sprintf(msg, "Polar Stereographic Projections with differences found:" " \n\n"); fprintf(outputFP, msg); if (g1->proj_coords_trans != g2->proj_coords_trans) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%d", g1->proj_coords_trans); sprintf(tmp2,"%d", g2->proj_coords_trans); sprintf(msg, " Projection type code from ProjCoordTransGeoKey " "differ:\n" " File1: %s\n" " File2: %s\n", g1->proj_coords_trans != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->proj_coords_trans != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->natLatOrigin != g2->natLatOrigin) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->natLatOrigin); sprintf(tmp2,"%f", g2->natLatOrigin); sprintf(msg, " Latitudes of Origin (from ProjNatOriginLatGeoKey) " "differ:\n" " File1: %s\n" " File2: %s\n", g1->natLatOrigin != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->natLatOrigin != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->lonPole != g2->lonPole) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->lonPole); sprintf(tmp2,"%f", g2->lonPole); sprintf(msg, " Longitudes of Straight Vertical Pole (from " "ProjStraightVertPoleLongGeoKey) differ:\n" " File1: %s\n" " File2: %s\n", g1->lonPole != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->lonPole != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->false_easting != g2->false_easting) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->false_easting); sprintf(tmp2,"%f", g2->false_easting); sprintf(msg, " False eastings differ:\n" " File1: %s\n" " File2: %s\n", g1->false_easting != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->false_easting != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->false_northing != g2->false_northing) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->false_northing); sprintf(tmp2,"%f", g2->false_northing); sprintf(msg, " False northings differ:\n" " File1: %s\n" " File2: %s\n", g1->false_northing != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->false_northing != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } } break; case LAMBERT_AZIMUTHAL_EQUAL_AREA: if (g1->proj_coords_trans != g2->proj_coords_trans || g1->false_easting != g2->false_easting || g1->false_northing != g2->false_northing || g1->lonCenter != g2->lonCenter || g1->latCenter != g2->latCenter) { failed=1; sprintf(msg, "Lambert Azimuthal Equal Area Projections with " "differences found: \n\n"); fprintf(outputFP, msg); if (g1->proj_coords_trans != g2->proj_coords_trans) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%d", g1->proj_coords_trans); sprintf(tmp2,"%d", g2->proj_coords_trans); sprintf(msg, " Projection type code from ProjCoordTransGeoKey " "differ:\n" " File1: %s\n" " File2: %s\n", g1->proj_coords_trans != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->proj_coords_trans != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->false_easting != g2->false_easting) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->false_easting); sprintf(tmp2,"%f", g2->false_easting); sprintf(msg, " False eastings differ:\n" " File1: %s\n" " File2: %s\n", g1->false_easting != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->false_easting != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->false_northing != g2->false_northing) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->false_northing); sprintf(tmp2,"%f", g2->false_northing); sprintf(msg, " False northings differ:\n" " File1: %s\n" " File2: %s\n", g1->false_northing != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->false_northing != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->lonCenter != g2->lonCenter) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->lonCenter); sprintf(tmp2,"%f", g2->lonCenter); sprintf(msg, " Central meridians (from ProjCenterLongGeoKey) " "differ:\n" " File1: %s\n" " File2: %s\n", g1->lonCenter != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->lonCenter != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } if (g1->latCenter != g2->latCenter) { char tmp1[16], tmp2[16]; sprintf(tmp1,"%f", g1->latCenter); sprintf(tmp2,"%f", g2->latCenter); sprintf(msg, " Latitudes of Origin (from ProjCenterLatGeoKey) " "differ:\n" " File1: %s\n" " File2: %s\n", g1->latCenter != MISSING_GTIF_DATA ? tmp1 : "MISSING", g2->latCenter != MISSING_GTIF_DATA ? tmp2 : "MISSING"); fprintf(outputFP, msg); } } break; case LAT_LONG_PSEUDO_PROJECTION: break; default: // Should never reach this code sprintf(msg, "Found unsupported or missing projection type\n\n"); fprintf(outputFP, msg); break; } } fprintf(outputFP, "-----------------------------------------------\n\n"); } if (failed && out_file_exists && outputFP != NULL) { FCLOSE(outputFP); } } void projection_type_2_str(projection_type_t proj, char *proj_str) { switch (proj) { case UNIVERSAL_TRANSVERSE_MERCATOR: strcpy(proj_str, "UTM"); break; case ALBERS_EQUAL_AREA: strcpy(proj_str, "Albers Equal Area"); break; case LAMBERT_CONFORMAL_CONIC: strcpy(proj_str, "Lambert Conformal Conic"); break; case POLAR_STEREOGRAPHIC: strcpy(proj_str, "Polar Stereographic"); break; case LAMBERT_AZIMUTHAL_EQUAL_AREA: strcpy(proj_str, "Lambert Azimuthal Equal Area"); break; case LAT_LONG_PSEUDO_PROJECTION: strcpy(proj_str, "Geographic"); break; default: strcpy(proj_str, "Unknown"); break; } } int tiff_image_band_statistics_from_file(char *inFile, int band_no, int *stats_exist, double *min, double *max, double *mean, double *sdev, double *rmse, int use_mask_value, float mask_value) { tiff_data_t t; tsize_t scanlineSize; *stats_exist = 1; // Innocent until presumed guilty... get_tiff_info_from_file(inFile, &t); // Note: For single-plane (greyscale) images, planar_config will remain // unset so we can't use it as a guide for checking TIFF validity... if (t.sample_format == MISSING_TIFF_DATA || t.bits_per_sample == MISSING_TIFF_DATA || t.data_type == 0 || t.num_bands == MISSING_TIFF_DATA || t.is_scanline_format == MISSING_TIFF_DATA || t.height == 0 || t.width == 0) { *stats_exist = 0; return 1; } // Minimum and maximum sample values as integers. double fmin = FLT_MAX; double fmax = -FLT_MAX; double cs; // Current sample value *mean = 0.0; double s = 0.0; uint32 sample_count = 0; // Samples considered so far. uint32 ii, jj; TIFF *tif = XTIFFOpen(inFile, "rb"); if (tif == NULL) { *stats_exist = 0; return 1; } scanlineSize = TIFFScanlineSize(tif); if (scanlineSize <= 0) { if (tif) XTIFFClose(tif); *stats_exist = 0; return 1; } if (t.num_bands > 1 && t.planar_config != PLANARCONFIG_CONTIG && t.planar_config != PLANARCONFIG_SEPARATE) { if (tif) XTIFFClose(tif); *stats_exist = 0; return 1; } float *buf = (float*)MALLOC(t.width * sizeof(float)); // If there is a mask value we are supposed to ignore, if ( use_mask_value ) { // iterate over all rows in the TIFF for ( ii = 0; ii < t.height; ii++ ) { // Planar configuration is chunky, e.g. interlaced pixels, rgb rgb etc. asfPercentMeter((double)ii/(double)t.height); tiff_get_float_line(tif, buf, ii, band_no); for (jj = 0 ; jj < t.width; jj++ ) { // iterate over each pixel sample in the scanline cs = buf[jj]; if ( !isnan(mask_value) && (gsl_fcmp (cs, mask_value, 0.00000000001) == 0 ) ) { continue; } if ( G_UNLIKELY (cs < fmin) ) { fmin = cs; } if ( G_UNLIKELY (cs > fmax) ) { fmax = cs; } double old_mean = *mean; *mean += (cs - *mean) / (sample_count + 1); s += (cs - old_mean) * (cs - *mean); sample_count++; } } asfPercentMeter(1.0); } else { // There is no mask value to ignore, so we do the same as the // above loop, but without the possible continue statement. for ( ii = 0; ii < t.height; ii++ ) { asfPercentMeter((double)ii/(double)t.height); tiff_get_float_line(tif, buf, ii, band_no); for (jj = 0 ; jj < t.width; jj++ ) { // iterate over each pixel sample in the scanline cs = buf[jj]; if ( G_UNLIKELY (cs < fmin) ) { fmin = cs; } if ( G_UNLIKELY (cs > fmax) ) { fmax = cs; } double old_mean = *mean; *mean += (cs - *mean) / (sample_count + 1); s += (cs - old_mean) * (cs - *mean); sample_count++; } } asfPercentMeter(1.0); } // Verify the new extrema have been found. //if (fmin == FLT_MAX || fmax == -FLT_MAX) if (gsl_fcmp (fmin, FLT_MAX, 0.00000000001) == 0 || gsl_fcmp (fmax, -FLT_MAX, 0.00000000001) == 0) { if (buf) free(buf); if (tif) XTIFFClose(tif); *stats_exist = 0; return 1; } *min = fmin; *max = fmax; *sdev = sqrt (s / (sample_count - 1)); // This assumes the sample count is large enough to ensure that the sample // standard deviation is very very similar to the population standard // deviation. *rmse = *sdev; // The new extrema had better be in the range supported range if (fabs(*mean) > FLT_MAX || fabs(*sdev) > FLT_MAX) { if (buf) free(buf); if (tif) XTIFFClose(tif); *stats_exist = 0; return 1; } if (buf) free(buf); if (tif) XTIFFClose(tif); return 0; } void tiff_image_band_psnr_from_files(char *inFile1, char *inFile2, int band1, int band2, psnr_t *psnr) { double cs1, cs2; tiff_data_t t1, t2; tsize_t scanlineSize1, scanlineSize2; get_tiff_info_from_file(inFile1, &t1); if (t1.sample_format == MISSING_TIFF_DATA || t1.bits_per_sample == MISSING_TIFF_DATA || t1.planar_config == MISSING_TIFF_DATA || t1.data_type == 0 || t1.num_bands == MISSING_TIFF_DATA || t1.is_scanline_format == MISSING_TIFF_DATA || t1.height == 0 || t1.width == 0) { asfPrintWarning("Missing TIFF header values in %s\n", inFile1); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } get_tiff_info_from_file(inFile2, &t2); if (t2.sample_format == MISSING_TIFF_DATA || t2.bits_per_sample == MISSING_TIFF_DATA || t2.planar_config == MISSING_TIFF_DATA || t2.data_type == 0 || t2.num_bands == MISSING_TIFF_DATA || t2.is_scanline_format == MISSING_TIFF_DATA || t2.height == 0 || t2.width == 0) { asfPrintWarning("Missing TIFF header values in %s\n", inFile2); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } // Calculate the peak signal to noise ratio (PSNR) between the two images double sse; double rmse; int ii, jj; long height = MIN(t1.height, t2.height); long width = MIN(t1.width, t2.width); long pixel_count = 0; float max_val; char **band_names1, **band_names2; int num_extracted_names1=0; int num_extracted_names2=0; if (band1 < 0 || band1 > t1.num_bands - 1 || band2 < 0 || band2 > t2.num_bands - 1) { asfPrintWarning("Invalid band number for file1 (%d v. %d) or file2 (%d v. " "%d)\n", band1, t1.num_bands, band2, t2.num_bands); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } if (t1.height != t2.height) { asfPrintWarning("File1 and File2 have a differing numbers of rows (%d v. " "%d).\nPSNR calculation will only use the first %d rows " "from each file.\n", t1.height, t2.height, height); } if (t1.width != t2.width) { asfPrintWarning("File1 and File2 have a different number of pixels per row " "(%d v. %d).\nPSNR calculation will only use the first %d " "pixels from each row of data.\n", t1.width, t2.width, width); } if (t1.data_type != t2.data_type) { asfPrintWarning("TIFF files have different data types.\n"); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } get_band_names(inFile1, NULL, &band_names1, &num_extracted_names1); get_band_names(inFile2, NULL, &band_names2, &num_extracted_names2); asfPrintStatus("\nCalculating PSNR between\n Band %s in %s and\n Band %s " "in %s\n", band_names1[band1], inFile1, band_names2[band2], inFile2); TIFF *tif1 = XTIFFOpen(inFile1, "rb"); if (tif1 == NULL) { asfPrintWarning("Cannot open %s\n", inFile1); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } scanlineSize1 = TIFFScanlineSize(tif1); if (scanlineSize1 <= 0) { asfPrintWarning("Invalid scanline size (%d)\n", scanlineSize1); if (tif1) XTIFFClose(tif1); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } if (t1.num_bands > 1 && t1.planar_config != PLANARCONFIG_CONTIG && t1.planar_config != PLANARCONFIG_SEPARATE) { asfPrintWarning("Invalid planar configuration in %s\n", inFile1); if (tif1) XTIFFClose(tif1); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } TIFF *tif2 = XTIFFOpen(inFile2, "rb"); if (tif2 == NULL) { asfPrintWarning("Cannot open %s\n", inFile2); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } scanlineSize2 = TIFFScanlineSize(tif2); if (scanlineSize2 <= 0) { asfPrintWarning("Invalid scanline size (%d)\n", scanlineSize2); if (tif2) XTIFFClose(tif2); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } if (t2.num_bands > 1 && t2.planar_config != PLANARCONFIG_CONTIG && t2.planar_config != PLANARCONFIG_SEPARATE) { asfPrintWarning("Invalid planar configuration in %s\n", inFile2); if (tif2) XTIFFClose(tif2); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } float *buf1 = (float*)CALLOC(t1.width, sizeof(float)); float *buf2 = (float*)CALLOC(t2.width, sizeof(float)); if (buf1 == NULL || buf2 == NULL) { asfPrintWarning("Cannot allocate memory for TIFF data buffers.\n"); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; if (buf1) FREE(buf1); if (buf2) FREE(buf2); return; } sse = 0.0; // Since both file's data types are the same, this is OK max_val = get_maxval(t1.data_type); for (ii=0; ii<height; ++ii) { asfPercentMeter((double)ii/(double)height); tiff_get_float_line(tif1, buf1, ii, band1); tiff_get_float_line(tif2, buf2, ii, band2); for (jj=0; jj<width; ++jj) { cs1 = buf1[jj]; cs2 = buf2[jj]; sse += (cs1 - cs2) * (cs1 - cs2); pixel_count++; } } asfPercentMeter(1.0); if (pixel_count > 0 && max_val > 0) { rmse = sqrt(sse/pixel_count); psnr->psnr = 10.0 * log10(max_val/(rmse+.00000000000001)); psnr->psnr_good = 1; } else { psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; } free_band_names(&band_names1, num_extracted_names1); free_band_names(&band_names2, num_extracted_names2); XTIFFClose(tif1); XTIFFClose(tif2); if (buf1) FREE(buf1); if (buf2) FREE(buf2); } void tiff_get_float_line(TIFF *tif, float *buf, int row, int band_no) { tiff_data_t t; get_tiff_info(tif, &t); // Note: For single-plane (greyscale) images, planar_config may remain unset // so we can't use it as a guide for checking TIFF validity... if (t.sample_format == MISSING_TIFF_DATA || t.bits_per_sample == MISSING_TIFF_DATA || t.data_type == 0 || t.num_bands == MISSING_TIFF_DATA || t.is_scanline_format == MISSING_TIFF_DATA || t.height == 0 || t.width == 0) { asfPrintError("Cannot read tif file\n"); } // Read a scanline tsize_t scanlineSize = TIFFScanlineSize(tif); tdata_t *tif_buf = _TIFFmalloc(scanlineSize); if (t.planar_config == PLANARCONFIG_CONTIG || t.num_bands == 1) { TIFFReadScanline(tif, tif_buf, row, 0); } else { // Planar configuration is band-sequential TIFFReadScanline(tif, tif_buf, row, band_no); } int col; for (col=0; col<t.width; col++) { switch(t.bits_per_sample) { case 8: switch(t.sample_format) { case SAMPLEFORMAT_UINT: if (t.planar_config == PLANARCONFIG_CONTIG && t.num_bands > 1) { // Current sample. buf[col] = (float)(((uint8*)(tif_buf))[(col*t.num_bands)+band_no]); } else { // Planar configuration is band-sequential or single-banded buf[col] = (float)(((uint8*)(tif_buf))[col]); } break; case SAMPLEFORMAT_INT: if (t.planar_config == PLANARCONFIG_CONTIG && t.num_bands > 1) { // Current sample. buf[col] = (float)(((int8*)(tif_buf))[(col*t.num_bands)+band_no]); } else { // Planar configuration is band-sequential or single-banded buf[col] = (float)(((int8*)(tif_buf))[col]); // Current sample. } break; default: // There is no such thing as an IEEE 8-bit floating point if (tif_buf) _TIFFfree(tif_buf); if (tif) XTIFFClose(tif); asfPrintError("tiff_get_float_line(): Unexpected data type in TIFF " "file.\n"); break; } break; case 16: switch(t.sample_format) { case SAMPLEFORMAT_UINT: if (t.planar_config == PLANARCONFIG_CONTIG && t.num_bands > 1) { // Current sample. buf[col] = (float)(((uint16*)(tif_buf))[(col*t.num_bands)+band_no]); } else { // Planar configuration is band-sequential or single-banded buf[col] = (float)(((uint16*)(tif_buf))[col]); // Current sample. } break; case SAMPLEFORMAT_INT: if (t.planar_config == PLANARCONFIG_CONTIG && t.num_bands > 1) { // Current sample. buf[col] = (float)(((int16*)(tif_buf))[(col*t.num_bands)+band_no]); } else { // Planar configuration is band-sequential or single-banded buf[col] = (float)(((uint16*)(tif_buf))[col]); // Current sample. } break; default: // There is no such thing as an IEEE 16-bit floating point if (tif_buf) _TIFFfree(tif_buf); if (tif) XTIFFClose(tif); asfPrintError("tiff_get_float_line(): Unexpected data type in TIFF " "file.\n"); break; } break; case 32: switch(t.sample_format) { case SAMPLEFORMAT_UINT: if (t.planar_config == PLANARCONFIG_CONTIG && t.num_bands > 1) { // Current sample. buf[col] = (float)(((uint32*)(tif_buf))[(col*t.num_bands)+band_no]); } else { // Planar configuration is band-sequential or single-banded buf[col] = (float)(((uint32*)(tif_buf))[col]); // Current sample. } break; case SAMPLEFORMAT_INT: if (t.planar_config == PLANARCONFIG_CONTIG && t.num_bands > 1) { // Current sample. buf[col] = (float)(((long*)(tif_buf))[(col*t.num_bands)+band_no]); } else { // Planar configuration is band-sequential or single-banded buf[col] = (float)(((long*)(tif_buf))[col]); // Current sample. } break; case SAMPLEFORMAT_IEEEFP: if (t.planar_config == PLANARCONFIG_CONTIG && t.num_bands > 1) { // Current sample. buf[col] = (float)(((float*)(tif_buf))[(col*t.num_bands)+band_no]); } else { // Planar configuration is band-sequential or single-banded buf[col] = (float)(((float*)(tif_buf))[col]); // Current sample. } break; default: if (tif_buf) _TIFFfree(tif_buf); if (tif) XTIFFClose(tif); asfPrintError("tiff_get_float_line(): Unexpected data type in TIFF " "file.\n"); break; } break; default: if (tif_buf) _TIFFfree(tif_buf); if (tif) XTIFFClose(tif); asfPrintError("tiff_get_float_line(): Unexpected data type in TIFF " "file.\n"); break; } } if (tif_buf) { _TIFFfree(tif_buf); } } float tiff_image_get_float_pixel(TIFF *tif, int row, int col, int band_no) { tiff_data_t t; float cs; get_tiff_info(tif, &t); // Note: For single-plane (greyscale) images, planar_config may remain unset // so we can't use it as a guide for checking TIFF validity... if (t.sample_format == MISSING_TIFF_DATA || t.bits_per_sample == MISSING_TIFF_DATA || t.data_type == 0 || t.num_bands == MISSING_TIFF_DATA || t.is_scanline_format == MISSING_TIFF_DATA || t.height == 0 || t.width == 0) { asfPrintError("Cannot read tif file\n"); } // Get a float line from the file float *buf = (float*)MALLOC(t.width*sizeof(float)); tiff_get_float_line(tif, buf, row, band_no); cs = buf[col]; FREE(buf); // Return as float return cs; } void get_png_info_hdr_from_file(char *inFile, png_info_t *ihdr, char *outfile) { png_structp png_ptr; png_infop info_ptr; png_uint_32 width, height; int bit_depth, color_type, nbands, interlace_type, compression_type; int filter_type; unsigned char sig[8]; char msg[1024]; FILE *pngFP, *outputFP; // Init stuff int output_file_exists = 0; pngFP = (FILE*)FOPEN(inFile,"rb"); if (outfile && strlen(outfile) > 0) { outputFP = (FILE*)FOPEN(outfile, "a"); if (outputFP) { output_file_exists = 1; } else { outputFP = stderr; output_file_exists = 0; } } else { outputFP = stderr; output_file_exists = 0; } ihdr->width = 0; ihdr->height = 0; ihdr->bit_depth = MISSING_PNG_DATA; ihdr->color_type = MISSING_PNG_DATA; strcpy(ihdr->color_type_str, "UNKNOWN"); ihdr->interlace_type = MISSING_PNG_DATA; ihdr->compression_type = MISSING_PNG_DATA; ihdr->filter_type = MISSING_PNG_DATA; ihdr->data_type = 0; ihdr->num_bands = 0; // Initialize PNG file for read if (png_access_version_number() < 10000 || png_access_version_number() > 20000) { sprintf(msg, "Invalid PNG file version (%0.4f) found. Only version " "1.xxxx is supported\n", (float)png_access_version_number()/10000.0); fprintf(outputFP, msg); if (pngFP) FCLOSE(pngFP); if (output_file_exists && outputFP) FCLOSE(outputFP); asfPrintError(msg); } // Important: Leaves file pointer offset into file by 8 bytes for png lib fread(sig, 1, 8, pngFP); if (!png_check_sig(sig, 8)) { // Bad PNG magic number (signature) sprintf(msg, "Invalid PNG file (%s)\n", "file type header bytes invalid"); fprintf(outputFP, msg); if (pngFP) FCLOSE(pngFP); if (output_file_exists && outputFP) FCLOSE(outputFP); asfPrintError(msg); } png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { sprintf(msg, "Cannot allocate PNG read struct (out of memory?)\n"); fprintf(outputFP, msg); if (pngFP) FCLOSE(pngFP); if (output_file_exists && outputFP) FCLOSE(outputFP); asfPrintError(msg); } info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, NULL, NULL); sprintf(msg, "Cannot allocate PNG info struct (out of memory?)\n"); fprintf(outputFP, msg); if (pngFP) FCLOSE(pngFP); if (output_file_exists && outputFP) FCLOSE(outputFP); asfPrintError(msg); } if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); sprintf(msg, "PNG library error occurred (invalid PNG file?)\n"); if (outputFP != NULL) fprintf(outputFP, msg); if (pngFP) FCLOSE(pngFP); if (output_file_exists && outputFP) FCLOSE(outputFP); asfPrintError(msg); } png_init_io(png_ptr, pngFP); // Because of the sig-reading offset ...must do this for PNG lib png_set_sig_bytes(png_ptr, 8); // Read info and IHDR png_read_info(png_ptr, info_ptr); png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_type); nbands = (int)png_get_channels(png_ptr, info_ptr); // Preliminary error checking on returned values (make sure results are valid) if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 && bit_depth != 8 && bit_depth != 16) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); sprintf(msg, "Invalid PNG file bit depth found (%d).\n" "Must be 1, 2, 4, 8, or 16.\n", bit_depth); if (outputFP != NULL) fprintf(outputFP, msg); if (pngFP) FCLOSE(pngFP); if (output_file_exists && outputFP) FCLOSE(outputFP); asfPrintError(msg); } if (color_type != PNG_COLOR_TYPE_GRAY && color_type != PNG_COLOR_TYPE_GRAY_ALPHA && color_type != PNG_COLOR_TYPE_PALETTE && color_type != PNG_COLOR_TYPE_RGB && color_type != PNG_COLOR_TYPE_RGB_ALPHA && color_type != PNG_COLOR_MASK_PALETTE && color_type != PNG_COLOR_MASK_COLOR && color_type != PNG_COLOR_MASK_ALPHA) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); sprintf(msg, "Invalid PNG file color type found.\n"); if (outputFP != NULL) fprintf(outputFP, msg); if (pngFP) FCLOSE(pngFP); if (output_file_exists && outputFP) FCLOSE(outputFP); asfPrintError(msg); } if (filter_type != PNG_FILTER_TYPE_BASE && filter_type != PNG_INTRAPIXEL_DIFFERENCING) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); sprintf(msg, "Invalid PNG file filter type found.\n"); if (outputFP != NULL) fprintf(outputFP, msg); if (pngFP) FCLOSE(pngFP); if (output_file_exists && outputFP) FCLOSE(outputFP); asfPrintError(msg); } if (compression_type != PNG_COMPRESSION_TYPE_BASE) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); sprintf(msg, "Invalid PNG file compression type found.\n"); if (outputFP != NULL) fprintf(outputFP, msg); if (pngFP) FCLOSE(pngFP); if (output_file_exists && outputFP) FCLOSE(outputFP); asfPrintError(msg); } if (interlace_type != PNG_INTERLACE_NONE && interlace_type != PNG_INTERLACE_ADAM7) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); sprintf(msg, "Invalid PNG file interlace type found.\n"); if (outputFP != NULL) fprintf(outputFP, msg); if (pngFP) FCLOSE(pngFP); if (output_file_exists && outputFP) FCLOSE(outputFP); asfPrintError(msg); } // Populate return struct ihdr->width = (uint32)width; ihdr->height = (uint32)height; ihdr->bit_depth = bit_depth; ihdr->color_type = color_type; strcpy(ihdr->color_type_str, color_type == PNG_COLOR_TYPE_GRAY ? "GRAY" : color_type == PNG_COLOR_TYPE_GRAY_ALPHA ? "GRAY+A" : color_type == PNG_COLOR_TYPE_PALETTE ? "PALETTE" : color_type == PNG_COLOR_TYPE_RGB ? "RGB" : color_type == PNG_COLOR_TYPE_RGB_ALPHA ? "RGBA" : color_type == PNG_COLOR_MASK_PALETTE ? "COLOR PALETTE MASK" : color_type == PNG_COLOR_MASK_COLOR ? "COLOR MASK" : color_type == PNG_COLOR_MASK_ALPHA ? "ALPHA MASK" : "UNKNOWN"); ihdr->interlace_type = interlace_type; ihdr->compression_type = compression_type; ihdr->filter_type = filter_type; switch (bit_depth) { case 1: case 2: case 4: ihdr->data_type=0; // UNKNOWN TYPE break; case 8: ihdr->data_type=BYTE; break; case 16: ihdr->data_type=INTEGER16; break; default: ihdr->data_type=0; // UNKNOWN TYPE break; } ihdr->num_bands = nbands; // Clean up and return png_destroy_read_struct(&png_ptr, &info_ptr, NULL); if (pngFP) FCLOSE(pngFP); if (output_file_exists && outputFP) FCLOSE(outputFP); } void calc_png_stats_2files(char *inFile1, char *inFile2, char *outfile, stats_t *inFile1_stats, stats_t *inFile2_stats, psnr_t *psnr, int band) { stats_t *s1 = inFile1_stats; stats_t *s2 = inFile2_stats; // Init stats s1->stats_good = s2->stats_good = 0; s1->min = s2->min = 0.0; s1->max = s2->max = 0.0; s1->mean = s2->mean = 0.0; s1->sdev = s2->sdev = 0.0; s1->rmse = s2->rmse = 0.0; s1->hist = s2->hist = NULL; s1->hist_pdf = s2->hist_pdf = NULL; psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; png_image_band_statistics_from_file(inFile1, outfile, band, &s1->stats_good, &s1->min, &s1->max, &s1->mean, &s1->sdev, &s1->rmse, 0, UINT8_IMAGE_DEFAULT_MASK); png_image_band_statistics_from_file(inFile2, outfile, band, &s2->stats_good, &s2->min, &s2->max, &s2->mean, &s2->sdev, &s2->rmse, 0, UINT8_IMAGE_DEFAULT_MASK); png_image_band_psnr_from_files(inFile1, inFile2, outfile, band, band, psnr); } int png_image_band_statistics_from_file(char *inFile, char *outfile, int band_no, int *stats_exist, double *min, double *max, double *mean, double *sdev, double *rmse, int use_mask_value, float mask_value) { png_structp png_ptr; png_infop info_ptr; png_uint_32 width, height; int bit_depth, color_type, interlace_type, compression_type, filter_type; unsigned char sig[8]; char msg[1024]; FILE *pngFP, *outputFP; png_info_t ihdr; *stats_exist = 1; // Innocent until presumed guilty... get_png_info_hdr_from_file(inFile, &ihdr, outfile); if (ihdr.bit_depth == MISSING_PNG_DATA || ihdr.color_type == MISSING_PNG_DATA || (ihdr.color_type_str == NULL || strlen(ihdr.color_type_str) <= 0) || ihdr.interlace_type == MISSING_PNG_DATA || ihdr.compression_type == MISSING_PNG_DATA || ihdr.filter_type == MISSING_PNG_DATA || ihdr.data_type == 0 || ihdr.num_bands == MISSING_PNG_DATA || ihdr.height == 0 || ihdr.width == 0) { *stats_exist = 0; return 1; } // Initialize PNG file for read int output_file_exists = 0; pngFP = (FILE*)FOPEN(inFile,"rb"); if (outfile && strlen(outfile) > 0) { outputFP = (FILE*)FOPEN(outfile, "a"); if (outputFP) { output_file_exists = 1; } else { outputFP = stderr; output_file_exists = 0; } } else { outputFP = stderr; output_file_exists = 0; } // Important: Leaves file pointer offset into file by 8 bytes for png lib fread(sig, 1, 8, pngFP); if (!png_check_sig(sig, 8)) { // Bad PNG magic number (signature) sprintf(msg, "Invalid PNG file (%s)\n", "file type header bytes invalid"); fprintf(outputFP, msg); if (pngFP) FCLOSE(pngFP); if (output_file_exists && outputFP) FCLOSE(outputFP); asfPrintError(msg); } png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { sprintf(msg, "Cannot allocate PNG read struct (out of memory?)\n"); fprintf(outputFP, msg); if (pngFP) FCLOSE(pngFP); if (output_file_exists && outputFP) FCLOSE(outputFP); asfPrintError(msg); } info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, NULL, NULL); sprintf(msg, "Cannot allocate PNG info struct (out of memory?)\n"); fprintf(outputFP, msg); if (pngFP) FCLOSE(pngFP); if (output_file_exists && outputFP) FCLOSE(outputFP); asfPrintError(msg); } if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); sprintf(msg, "PNG library error occurred (invalid PNG file?)\n"); if (outputFP != NULL) fprintf(outputFP, msg); if (pngFP) FCLOSE(pngFP); if (output_file_exists && outputFP) FCLOSE(outputFP); asfPrintError(msg); } png_init_io(png_ptr, pngFP); // Because of the sig-reading offset ...must do this for PNG lib png_set_sig_bytes(png_ptr, 8); // Read info and IHDR png_read_info(png_ptr, info_ptr); png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_type); // Minimum and maximum sample values as integers. double fmin = FLT_MAX; double fmax = -FLT_MAX; double cs; // Current sample value *mean = 0.0; double s = 0.0; uint32 sample_count = 0; // Samples considered so far. uint32 ii, jj; float *buf = (float*)MALLOC(ihdr.width * sizeof(float)); // If there is a mask value we are supposed to ignore, if ( use_mask_value ) { // iterate over all rows in the TIFF for ( ii = 0; ii < ihdr.height; ii++ ) { // Planar configuration is chunky, e.g. interlaced pixels, rgb rgb etc. asfPercentMeter((double)ii/(double)ihdr.height); png_sequential_get_float_line(png_ptr, info_ptr, buf, band_no); for (jj = 0 ; jj < ihdr.width; jj++ ) { // iterate over each pixel sample in the scanline cs = buf[jj]; if (!isnan(mask_value) && (gsl_fcmp (cs, mask_value, 0.00000000001) == 0 ) ) { continue; } if ( G_UNLIKELY (cs < fmin) ) { fmin = cs; } if ( G_UNLIKELY (cs > fmax) ) { fmax = cs; } double old_mean = *mean; *mean += (cs - *mean) / (sample_count + 1); s += (cs - old_mean) * (cs - *mean); sample_count++; } } asfPercentMeter(1.0); } else { // There is no mask value to ignore, so we do the same as the // above loop, but without the possible continue statement. for ( ii = 0; ii < ihdr.height; ii++ ) { asfPercentMeter((double)ii/(double)ihdr.height); png_sequential_get_float_line(png_ptr, info_ptr, buf, band_no); for (jj = 0 ; jj < ihdr.width; jj++ ) { // iterate over each pixel sample in the scanline cs = buf[jj]; if ( G_UNLIKELY (cs < fmin) ) { fmin = cs; } if ( G_UNLIKELY (cs > fmax) ) { fmax = cs; } double old_mean = *mean; *mean += (cs - *mean) / (sample_count + 1); s += (cs - old_mean) * (cs - *mean); sample_count++; } } asfPercentMeter(1.0); } // Verify the new extrema have been found. //if (fmin == FLT_MAX || fmax == -FLT_MAX) if (gsl_fcmp (fmin, FLT_MAX, 0.00000000001) == 0 || gsl_fcmp (fmax, -FLT_MAX, 0.00000000001) == 0) { if (buf) free(buf); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); sprintf(msg, "PNG library error occurred (invalid PNG file?)\n"); if (outputFP != NULL) fprintf(outputFP, msg); if (pngFP) FCLOSE(pngFP); if (output_file_exists && outputFP) FCLOSE(outputFP); *stats_exist = 0; return 1; } *min = fmin; *max = fmax; *sdev = sqrt (s / (sample_count - 1)); // This assumes the sample count is large enough to ensure that the sample // standard deviation is very very similar to the population standard // deviation. *rmse = *sdev; // The new extrema had better be in the range supported range if (fabs(*mean) > FLT_MAX || fabs(*sdev) > FLT_MAX) { if (buf) free(buf); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); sprintf(msg, "PNG library error occurred (invalid PNG file?)\n"); if (outputFP != NULL) fprintf(outputFP, msg); if (pngFP) FCLOSE(pngFP); if (output_file_exists && outputFP) FCLOSE(outputFP); *stats_exist = 0; return 1; } png_destroy_read_struct(&png_ptr, &info_ptr, NULL); if (buf) free(buf); if (output_file_exists && outputFP) FCLOSE(outputFP); if (pngFP) FCLOSE(pngFP); return 0; } void png_image_band_psnr_from_files(char *inFile1, char *inFile2, char *outfile, int band1, int band2, psnr_t *psnr) { double cs1, cs2; png_structp png_ptr1 = NULL, png_ptr2 = NULL; png_infop info_ptr1 = NULL, info_ptr2 = NULL; png_uint_32 png_width, png_height; int bit_depth, color_type, interlace_type, compression_type, filter_type; int num_names_extracted1=0, num_names_extracted2=0; unsigned char sig[8]; char msg[1024]; FILE *pngFP1, *pngFP2, *outputFP; png_info_t ihdr1, ihdr2; int output_file_exists = 0; if (outfile && strlen(outfile) > 0) { outputFP = (FILE*)FOPEN(outfile, "a"); if (outputFP) { output_file_exists = 1; } else { outputFP = stderr; output_file_exists = 0; } } else { outputFP = stderr; output_file_exists = 0; } get_png_info_hdr_from_file(inFile1, &ihdr1, outfile); if (ihdr1.bit_depth == MISSING_PNG_DATA || ihdr1.color_type == MISSING_PNG_DATA || (ihdr1.color_type_str == NULL || strlen(ihdr1.color_type_str) <= 0) || ihdr1.interlace_type == MISSING_PNG_DATA || ihdr1.compression_type == MISSING_PNG_DATA || ihdr1.filter_type == MISSING_PNG_DATA || ihdr1.data_type == 0 || ihdr1.num_bands == MISSING_PNG_DATA || ihdr1.height == 0 || ihdr1.width == 0) { sprintf(msg, "Cannot read PNG file header in file1\n %s\n", inFile1); if (outputFP) fprintf(outputFP, msg); if (output_file_exists && outputFP) FCLOSE(outputFP); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } get_png_info_hdr_from_file(inFile2, &ihdr2, outfile); if (ihdr2.bit_depth == MISSING_PNG_DATA || ihdr2.color_type == MISSING_PNG_DATA || (ihdr2.color_type_str == NULL || strlen(ihdr2.color_type_str) <= 0) || ihdr2.interlace_type == MISSING_PNG_DATA || ihdr2.compression_type == MISSING_PNG_DATA || ihdr2.filter_type == MISSING_PNG_DATA || ihdr2.data_type == 0 || ihdr2.num_bands == MISSING_PNG_DATA || ihdr2.height == 0 || ihdr2.width == 0) { sprintf(msg, "Cannot read PNG file header in file2\n %s\n", inFile2); if (outputFP) fprintf(outputFP, msg); if (output_file_exists && outputFP) FCLOSE(outputFP); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } // Initialize PNG file for read pngFP1 = (FILE*)FOPEN(inFile1,"rb"); // Important: Leaves file pointer offset into file by 8 bytes for png lib fread(sig, 1, 8, pngFP1); if (!png_check_sig(sig, 8)) { // Bad PNG magic number (signature) sprintf(msg, "Invalid PNG file (%s)\n %s\n", "file type header bytes " "invalid", inFile1); fprintf(outputFP, msg); if (pngFP1) FCLOSE(pngFP1); if (output_file_exists && outputFP) FCLOSE(outputFP); asfPrintError(msg); } pngFP2 = (FILE*)FOPEN(inFile2,"rb"); // Important: Leaves file pointer offset into file by 8 bytes for png lib fread(sig, 1, 8, pngFP2); if (!png_check_sig(sig, 8)) { // Bad PNG magic number (signature) sprintf(msg, "Invalid PNG file (%s)\n %s\n", "file type header bytes " "invalid", inFile2); fprintf(outputFP, msg); if (pngFP2) FCLOSE(pngFP2); if (output_file_exists && outputFP) FCLOSE(outputFP); asfPrintError(msg); } png_ptr1 = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr1) { sprintf(msg, "Cannot allocate PNG read struct (out of memory?)\n"); fprintf(outputFP, msg); if (pngFP1) FCLOSE(pngFP1); if (output_file_exists && outputFP) FCLOSE(outputFP); asfPrintError(msg); } info_ptr1 = png_create_info_struct(png_ptr1); if (!info_ptr1) { png_destroy_read_struct(&png_ptr1, NULL, NULL); sprintf(msg, "Cannot allocate PNG info struct (out of memory?)\n"); fprintf(outputFP, msg); if (pngFP1) FCLOSE(pngFP1); if (output_file_exists && outputFP) FCLOSE(outputFP); asfPrintError(msg); } png_ptr2 = png_create_read_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr2) { sprintf(msg, "Cannot allocate PNG read struct (out of memory?)\n"); fprintf(outputFP, msg); if (pngFP2) FCLOSE(pngFP2); if (output_file_exists && outputFP) FCLOSE(outputFP); asfPrintError(msg); } info_ptr2 = png_create_info_struct(png_ptr2); if (!info_ptr2) { png_destroy_read_struct(&png_ptr2, NULL, NULL); sprintf(msg, "Cannot allocate PNG info struct (out of memory?)\n"); fprintf(outputFP, msg); if (pngFP2) FCLOSE(pngFP2); if (output_file_exists && outputFP) FCLOSE(outputFP); asfPrintError(msg); } if (setjmp(png_jmpbuf(png_ptr1))) { if (png_ptr1) png_destroy_read_struct(&png_ptr1, &info_ptr1, NULL); if (png_ptr2) png_destroy_read_struct(&png_ptr2, &info_ptr2, NULL); sprintf(msg, "PNG library error occurred (invalid PNG file?)\n"); if (outputFP != NULL) fprintf(outputFP, msg); if (pngFP1) FCLOSE(pngFP1); if (pngFP2) FCLOSE(pngFP2); if (output_file_exists && outputFP) FCLOSE(outputFP); asfPrintError(msg); } png_init_io(png_ptr1, pngFP1); // Because of the sig-reading offset ...must do this for PNG lib png_set_sig_bytes(png_ptr1, 8); png_init_io(png_ptr2, pngFP2); // Because of the sig-reading offset ...must do this for PNG lib png_set_sig_bytes(png_ptr2, 8); // Read info and IHDR png_read_info(png_ptr1, info_ptr1); png_get_IHDR(png_ptr1, info_ptr1, &png_width, &png_height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_type); png_read_info(png_ptr2, info_ptr2); png_get_IHDR(png_ptr2, info_ptr2, &png_width, &png_height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_type); // Calculate the peak signal to noise ratio (PSNR) between the two images double sse; double rmse; int ii, jj; long height = MIN(ihdr1.height, ihdr2.height); long width = MIN(ihdr1.width, ihdr2.width); long pixel_count = 0; float max_val; if (band1 < 0 || band1 > ihdr1.num_bands - 1 || band2 < 0 || band2 > ihdr2.num_bands - 1) { sprintf(msg,"Invalid band number for file1 (%d v. %d) or file2 (%d v. %d)" "\n", band1, ihdr1.num_bands, band2, ihdr2.num_bands); asfPrintWarning(msg); if (png_ptr1) png_destroy_read_struct(&png_ptr1, &info_ptr1, NULL); if (png_ptr2) png_destroy_read_struct(&png_ptr2, &info_ptr2, NULL); if (outputFP != NULL) fprintf(outputFP, msg); if (pngFP1) FCLOSE(pngFP1); if (pngFP2) FCLOSE(pngFP2); if (output_file_exists && outputFP) FCLOSE(outputFP); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } if (ihdr1.height != ihdr2.height) { asfPrintWarning("File1 and File2 have a differing numbers of rows (%d v. " "%d).\nPSNR calculation will only use the first %d rows " "from each file.\n", ihdr1.height, ihdr2.height, height); } if (ihdr1.width != ihdr2.width) { asfPrintWarning("File1 and File2 have a different number of pixels per row " "(%d v. %d).\nPSNR calculation will only use the first %d " "pixels from each row of data.\n", ihdr1.width, ihdr2.width, width); } if (ihdr1.data_type != ihdr2.data_type) { sprintf(msg,"PNG files have differing data types.\n"); asfPrintWarning(msg); if (png_ptr1) png_destroy_read_struct(&png_ptr1, &info_ptr1, NULL); if (png_ptr2) png_destroy_read_struct(&png_ptr2, &info_ptr2, NULL); if (outputFP != NULL) fprintf(outputFP, msg); if (pngFP1) FCLOSE(pngFP1); if (pngFP2) FCLOSE(pngFP2); if (output_file_exists && outputFP) FCLOSE(outputFP); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } char **band_names1, **band_names2; get_band_names(inFile1, NULL, &band_names1, &num_names_extracted1); get_band_names(inFile2, NULL, &band_names2, &num_names_extracted2); asfPrintStatus("\nCalculating PSNR between\n Band %s in %s and\n Band %s in" " %s\n", band_names1[band1], inFile1, band_names2[band2], inFile2); float *buf1 = (float*)CALLOC(ihdr1.width, sizeof(float)); float *buf2 = (float*)CALLOC(ihdr2.width, sizeof(float)); if (buf1 == NULL || buf2 == NULL) { asfPrintWarning("Cannot allocate memory for PNG data buffers.\n"); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; if (buf1) FREE(buf1); if (buf2) FREE(buf2); if (png_ptr1) png_destroy_read_struct(&png_ptr1, &info_ptr1, NULL); if (png_ptr2) png_destroy_read_struct(&png_ptr2, &info_ptr2, NULL); if (outputFP != NULL) fprintf(outputFP, msg); if (pngFP1) FCLOSE(pngFP1); if (pngFP2) FCLOSE(pngFP2); if (output_file_exists && outputFP) FCLOSE(outputFP); return; } sse = 0.0; // Since both file's data types are the same, this is OK max_val = get_maxval(ihdr1.data_type); for (ii=0; ii<height; ++ii) { asfPercentMeter((double)ii/(double)height); png_sequential_get_float_line(png_ptr1, info_ptr1, buf1, band1); png_sequential_get_float_line(png_ptr2, info_ptr2, buf2, band2); for (jj=0; jj<width; ++jj) { cs1 = buf1[jj]; cs2 = buf2[jj]; sse += (cs1 - cs2) * (cs1 - cs2); pixel_count++; } } asfPercentMeter(1.0); if (pixel_count > 0 && max_val > 0) { rmse = sqrt(sse/pixel_count); psnr->psnr = 10.0 * log10(max_val/(rmse+.00000000000001)); psnr->psnr_good = 1; } else { psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; } free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); if (png_ptr1) png_destroy_read_struct(&png_ptr1, &info_ptr1, NULL); if (png_ptr2) png_destroy_read_struct(&png_ptr2, &info_ptr2, NULL); if (pngFP1) FCLOSE(pngFP1); if (pngFP2) FCLOSE(pngFP2); if (output_file_exists && outputFP) FCLOSE(outputFP); if (buf1) FREE(buf1); if (buf2) FREE(buf2); } // NOTE: No row offset provided because png_ptr acts like a file pointer ... // just read all the rows in sequence. void png_sequential_get_float_line(png_structp png_ptr, png_infop info_ptr, float *buf, int band) { int num_bands = (int)png_get_channels(png_ptr, info_ptr); if (band < 0 || band > num_bands - 1) { asfPrintError("png_get_float_line(): bad band number (band %d, bands %d " "through %d available)\n", band, 0, num_bands - 1); } png_uint_32 width, height; int bit_depth, color_type; png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, NULL, NULL, NULL); if (bit_depth != 8) { asfPrintError("png_get_float_line(): PNG image has unsupported bit depth " "(%d). Bit depth of 8-bits supported.\n", bit_depth); } if (color_type != PNG_COLOR_TYPE_GRAY && color_type != PNG_COLOR_TYPE_RGB) { asfPrintError("png_get_float_line(): PNG image must be RGB or greyscale. " "Alpha band, palette-color,\nand mask-type images not " "supported.\n"); } int rgb = color_type == PNG_COLOR_TYPE_RGB ? 1 : 0; png_bytep png_buf = (png_bytep)MALLOC(width*sizeof(png_byte)*(rgb ? 3 : 1)); int col; // Read current row png_read_row(png_ptr, png_buf, NULL); for (col=0; col<width; col++) { if (rgb) buf[col] = (float)png_buf[col*3+band]; else buf[col] = (float)png_buf[col]; } } void get_ppm_pgm_info_hdr_from_file(char *inFile, ppm_pgm_info_t *pgm, char *outfile) { int ch, i; unsigned char tmp[1024]; // For reading width, height, max_val only // Length of tmp for loop termination when reading sequential uchars int max_chars = 1024; FILE *fp = (FILE*)FOPEN(inFile, "rb"); strcpy(pgm->magic,""); pgm->width=MISSING_PPM_PGM_DATA; pgm->height=MISSING_PPM_PGM_DATA; pgm->max_val=MISSING_PPM_PGM_DATA; // Default to unsupported type ...ASCII data separated by whitespace pgm->ascii_data=1; pgm->img_offset = MISSING_PSNR; // Will result in a failed fseek() pgm->bit_depth=0; pgm->data_type=0; pgm->num_bands=0; //// Read magic number that identifies FREAD(pgm->magic, sizeof(unsigned char), 2, fp); if (pgm->magic[0] == 'P' && (pgm->magic[1] == '5' || pgm->magic[1] == '6')) { pgm->ascii_data = 0; pgm->img_offset = 2; // Just past magic number } else { // Shouldn't be possible to be here, but what the hey... FILE *outFP=NULL; if (outfile && strlen(outfile) > 0) outFP=(FILE*)FOPEN(outfile,"a"); char msg[1024]; sprintf(msg, "get_ppm_pgm_info_hdr_from_file(): Found invalid or " "unsupported (ASCII data?)\nPPM/PGM file header.\n"); if (outFP) fprintf(outFP, msg); else fprintf(stderr, msg); if (outFP) FCLOSE(outFP); if (fp) FCLOSE(fp); asfPrintError(msg); } // Determine number of channels (3 for rgb, 1 for gray) if (pgm->magic[1] == '6') { pgm->num_bands = 3; // RGB PPM file } else if (pgm->magic[1] == '5') { pgm->num_bands = 1; // Grayscale PGM file } else { // Shouldn't be able to reach this code FILE *outFP=NULL; if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); char msg[1024]; sprintf(msg, "get_ppm_pgm_info_hdr_from_file(): Found invalid or " "unsupported\n(ASCII data?) PPM/PGM file header...\n"); if (outFP) fprintf(outFP, msg); else fprintf(stderr, msg); if (outFP) FCLOSE(outFP); if (fp) FCLOSE(fp); asfPrintError(msg); } // Read image width (in pixels) // Move past white space ch = fgetc(fp); pgm->img_offset++; while (isspace(ch) && ch != EOF) { ch = fgetc(fp); // Move past white space pgm->img_offset++; } i = 0; while (!isspace(ch) && i < max_chars && ch != EOF) { tmp[i++] = ch; ch = fgetc(fp); pgm->img_offset++; } tmp[i]='\0'; if (i == max_chars || ch == EOF) { FILE *outFP = NULL; if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); char msg[1024]; sprintf(msg, "get_ppm_pgm_info_hdr_from_file(): '%s' field in file header " "too long.\n", "width"); if (outFP) fprintf(outFP, msg); else fprintf(stderr, msg); if (outFP) FCLOSE(outFP); if (fp) FCLOSE(fp); asfPrintError(msg); } pgm->width = atoi((char *)tmp); //// Read image height (in rows) while (isspace(ch) && ch != EOF) { ch = fgetc(fp); // Move past white space pgm->img_offset++; } i = 0; while (!isspace(ch) && i < max_chars && ch != EOF) { tmp[i++] = ch; ch = fgetc(fp); pgm->img_offset++; } tmp[i]='\0'; if (i == max_chars || ch == EOF) { FILE *outFP = NULL; if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); char msg[1024]; sprintf(msg, "get_ppm_pgm_info_hdr_from_file(): '%s' field in file header " "too long.\n", "height"); if (outFP) fprintf(outFP, msg); else fprintf(stderr, msg); if (outFP) FCLOSE(outFP); if (fp) FCLOSE(fp); asfPrintError(msg); } pgm->height = atoi((char *)tmp); // Read max-allowed pixel value while (isspace(ch) && ch != EOF) { ch = fgetc(fp); // Move past white space pgm->img_offset++; } i = 0; while (!isspace(ch) && i < max_chars && ch != EOF) { tmp[i++] = ch; ch = fgetc(fp); pgm->img_offset++; } tmp[i]='\0'; if (i == max_chars || ch == EOF) { FILE *outFP = NULL; if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); char msg[1024]; sprintf(msg, "get_ppm_pgm_info_hdr_from_file(): '%s' field in file header " "too long.\n", "max. pixel value"); if (outFP) fprintf(outFP, msg); else fprintf(stderr, msg); if (outFP) FCLOSE(outFP); if (fp) FCLOSE(fp); asfPrintError(msg); } pgm->max_val = atoi((char *)tmp); // Move past white space to beginning of image data to set pgm->img_offset // for an fseek() while (isspace(ch) && ch != EOF) { ch = fgetc(fp); // Move past white space pgm->img_offset++; } pgm->img_offset--; if (ch == EOF) { FILE *outFP = NULL; if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); char msg[1024]; sprintf(msg, "No image data found in PNG file\n %s\n", inFile); if (outFP) fprintf(outFP, msg); else fprintf(stderr, msg); if (outFP) FCLOSE(outFP); if (fp) FCLOSE(fp); asfPrintError(msg); } // Determine byte-boundary bit-depth and ASF data type for holding // the PPM/PGM file's image data if ((float)pow(20, 32) > pgm->max_val) { pgm->bit_depth = 8; pgm->data_type = BYTE; } else if ((float)pow(2, 16) > pgm->max_val) { pgm->bit_depth = 16; pgm->data_type = INTEGER16; } else if ((float)pow(2, 8) > pgm->max_val) { pgm->bit_depth = 32; pgm->data_type = INTEGER32; } else { FILE *outFP = NULL; if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); char msg[1024]; sprintf(msg, "Invalid max. pixel value found in PNG file (%d)\n %s\n", pgm->max_val, inFile); if (outFP) fprintf(outFP, msg); else fprintf(stderr, msg); if (outFP) FCLOSE(outFP); if (fp) FCLOSE(fp); asfPrintError(msg); } if (fp) FCLOSE(fp); } void get_band_names(char *inFile, FILE *outputFP, char ***band_names, int *num_extracted_bands) { char msg[1024]; char type_str[255]; graphics_file_t type = getGraphicsFileType(inFile); graphicsFileType_toStr(type, type_str); if (type == ASF_IMG) { // Grab band names from the metadata meta_parameters *md; int band_count=1; char *f, *c; char inFile_meta[1024]; if (inFile != NULL && strlen(inFile) > 0) { f = STRDUP(inFile); c = findExt(f); *c = '\0'; sprintf(inFile_meta, "%s.meta", f); if (fileExists(inFile_meta)) { md = meta_read(inFile_meta); } FREE(f); } band_count = (md != NULL) ? md->general->band_count : 1; *num_extracted_bands = band_count; if (band_count > 0 && md != NULL) { *band_names = extract_band_names(md->general->bands, md->general->band_count); if (*band_names == NULL) { // free_band_names() will assume MAX_BANDS have been made available if // no bands have been extracted otherwise, so ...sigh, allocate // MAX_BANDS here ...they'll be freed unused. *num_extracted_bands=0; *band_names = (char**)MALLOC(MAX_BANDS*sizeof(char*)); if (*band_names != NULL) { int i; for (i=0; i<MAX_BANDS; i++) { (*band_names)[i] = (char*)CALLOC(64, sizeof(char)); if ((*band_names)[i] == NULL) { sprintf(msg, "Cannot allocate memory for band name array.\n"); if (outputFP != NULL) fprintf(outputFP, msg); asfPrintError(msg); } } } else { sprintf(msg, "Cannot allocate memory for band name array.\n"); if (outputFP != NULL) fprintf(outputFP, msg); asfPrintError(msg); } } } } else { // Other file types... // // Allocate memory for the band names *band_names = (char**)MALLOC(MAX_BANDS*sizeof(char*)); if (*band_names != NULL) { int i; for (i=0; i<MAX_BANDS; i++) { (*band_names)[i] = (char*)CALLOC(64, sizeof(char)); if ((*band_names)[i] == NULL) { sprintf(msg, "Cannot allocate memory for band name array.\n"); if (outputFP != NULL) fprintf(outputFP, msg); asfPrintError(msg); } } } else { sprintf(msg, "Cannot allocate memory for band name array.\n"); if (outputFP != NULL) fprintf(outputFP, msg); asfPrintError(msg); } if (type == GEO_TIFF_IMG) { // If band names are embedded in the GeoTIFF, then grab them. Otherwise // assign numeric band names geotiff_data_t g; int *empty = (int*)CALLOC(MAX_BANDS, sizeof(int)); char *band_str = (char*)CALLOC(25, sizeof(char)); if (band_str == NULL) { sprintf(msg, "Cannot allocate memory for band name string.\n"); if (outputFP != NULL) fprintf(outputFP, msg); asfPrintError(msg); } get_geotiff_keys(inFile, &g); if (g.gtif_data_exists && g.GTcitation != NULL && strlen(g.GTcitation) > 0) { char *tmp_citation = STRDUP(g.GTcitation); get_bands_from_citation(num_extracted_bands, &band_str, empty, tmp_citation, 0); FREE(tmp_citation); } else if (g.gtif_data_exists && g.PCScitation != NULL && strlen(g.PCScitation) > 0) { char *tmp_citation = STRDUP(g.PCScitation); get_bands_from_citation(num_extracted_bands, &band_str, empty, tmp_citation, 0); FREE(tmp_citation); } if (*num_extracted_bands <= 0) { // Could not find band strings in the citations, so assign numeric // band IDs int i; for (i=0; i<MAX_BANDS; i++) { sprintf((*band_names)[i], "%02d", i); } } else { // Extract the band names from the band names string // // extract_band_names() allocated memory, so better free it first... int i; for (i=0; i<MAX_BANDS; i++) { FREE((*band_names)[i]); } FREE(*band_names); *band_names = extract_band_names(band_str, *num_extracted_bands); } FREE(empty); FREE(band_str); if (g.GTcitation)FREE(g.GTcitation); if (g.PCScitation)FREE(g.PCScitation); } else { // For non ASF IMG and GeoTIFF images, just use numeric band id's int i; for (i=0; i<MAX_BANDS; i++) { sprintf((*band_names)[i], "%02d", i); } } } } void ppm_pgm_get_float_line(FILE *fp, float *buf, int row, ppm_pgm_info_t *pgm, int band_no) { if (band_no < 0 || band_no > pgm->num_bands - 1) { asfPrintError("Invalid band number (%d). Valid: 0 through %d (only)\n", band_no, pgm->num_bands - 1); } unsigned char *pgm_buf = (unsigned char*)MALLOC(pgm->num_bands * pgm->width * sizeof(unsigned char)); if (pgm_buf == NULL) { asfPrintError("Cannot allocate memory for PPM/PGM scanline buffer\n"); } FREAD(pgm_buf, sizeof(unsigned char), pgm->width * pgm->num_bands, fp); int col; for (col=0; col<pgm->width; col++) { buf[col] = (float)(((unsigned char*)pgm_buf)[(col*pgm->num_bands)+band_no]); } if (pgm_buf)FREE(pgm_buf); } int ppm_pgm_image_band_statistics_from_file(char *inFile, char *outfile, int band_no, int *stats_exist, double *min, double *max, double *mean, double *sdev, double *rmse, int use_mask_value, float mask_value) { ppm_pgm_info_t pgm; *stats_exist = 1; // Innocent until presumed guilty... get_ppm_pgm_info_hdr_from_file(inFile, &pgm, outfile); if (pgm.magic == NULL || strlen(pgm.magic) == 0 || pgm.width <= 0 || pgm.height <= 0 || pgm.max_val <= 0 || pgm.img_offset < 0 || pgm.bit_depth != 8 || pgm.data_type != BYTE || pgm.num_bands <= 0) { *stats_exist = 0; return 1; } // Minimum and maximum sample values as integers. double fmin = FLT_MAX; double fmax = -FLT_MAX; double cs; // Current sample value *mean = 0.0; double s = 0.0; uint32 sample_count = 0; // Samples considered so far. uint32 ii, jj; FILE *fp = FOPEN(inFile, "rb"); if (fp == NULL) { *stats_exist = 0; return 1; } float *buf = (float*)MALLOC(pgm.width * sizeof(float)); if (buf == NULL) { *stats_exist = 0; return 1; } // If there is a mask value we are supposed to ignore, FSEEK64(fp, (long long)pgm.img_offset, SEEK_SET); if ( use_mask_value ) { // iterate over all rows in the PPM or PGM file for ( ii = 0; ii < pgm.height; ii++ ) { asfPercentMeter((double)ii/(double)pgm.height); ppm_pgm_get_float_line(fp, buf, ii, &pgm, band_no); for (jj = 0 ; jj < pgm.width; jj++ ) { // iterate over each pixel sample in the scanline cs = buf[jj]; if ( !isnan(mask_value) && (gsl_fcmp (cs, mask_value, 0.00000000001) == 0 ) ) { continue; } if ( G_UNLIKELY (cs < fmin) ) { fmin = cs; } if ( G_UNLIKELY (cs > fmax) ) { fmax = cs; } double old_mean = *mean; *mean += (cs - *mean) / (sample_count + 1); s += (cs - old_mean) * (cs - *mean); sample_count++; } } asfPercentMeter(1.0); } else { // There is no mask value to ignore, so we do the same as the // above loop, but without the possible continue statement. for ( ii = 0; ii < pgm.height; ii++ ) { asfPercentMeter((double)ii/(double)pgm.height); ppm_pgm_get_float_line(fp, buf, ii, &pgm, band_no); for (jj = 0 ; jj < pgm.width; jj++ ) { // iterate over each pixel sample in the scanline cs = buf[jj]; if ( G_UNLIKELY (cs < fmin) ) { fmin = cs; } if ( G_UNLIKELY (cs > fmax) ) { fmax = cs; } double old_mean = *mean; *mean += (cs - *mean) / (sample_count + 1); s += (cs - old_mean) * (cs - *mean); sample_count++; } } asfPercentMeter(1.0); } // Verify the new extrema have been found. //if (fmin == FLT_MAX || fmax == -FLT_MAX) if (gsl_fcmp (fmin, FLT_MAX, 0.00000000001) == 0 || gsl_fcmp (fmax, -FLT_MAX, 0.00000000001) == 0) { if (buf) free(buf); if (fp) FCLOSE(fp); *stats_exist = 0; return 1; } *min = fmin; *max = fmax; *sdev = sqrt (s / (sample_count - 1)); // This assumes the sample count is large enough to ensure that the sample // standard deviation is very very similar to the population standard // deviation. *rmse = *sdev; // The new extrema had better be in the range supported range if (fabs(*mean) > FLT_MAX || fabs(*sdev) > FLT_MAX) { if (buf) free(buf); if (fp) FCLOSE(fp); *stats_exist = 0; return 1; } if (buf) free(buf); if (fp) FCLOSE(fp); return 0; } void ppm_pgm_image_band_psnr_from_files(char *inFile1, char *inFile2, char *outfile, int band1, int band2, psnr_t *psnr) { ppm_pgm_info_t pgm1, pgm2; // Header info double cs1, cs2; char msg[1024]; FILE *fp1, *fp2, *outputFP = NULL; if (outfile && strlen(outfile) > 0) { outputFP = (FILE*)FOPEN(outfile, "a"); } else { outputFP = NULL; } // Get header info and fseek() to beginning of image data get_ppm_pgm_info_hdr_from_file(inFile1, &pgm1, outfile); if (pgm1.magic == NULL || strlen(pgm1.magic) == 0 || pgm1.width <= 0 || pgm1.height <= 0 || pgm1.max_val <= 0 || pgm1.img_offset < 0 || pgm1.bit_depth != 8 || pgm1.data_type != BYTE || pgm1.num_bands <= 0) { sprintf(msg, "Cannot read PPM/PNG file header in file1\n %s\n", inFile1); if (outputFP) fprintf(outputFP, msg); else fprintf(stderr, msg); if (outputFP) FCLOSE(outputFP); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } get_ppm_pgm_info_hdr_from_file(inFile2, &pgm2, outfile); if (pgm2.magic == NULL || strlen(pgm2.magic) == 0 || pgm2.width <= 0 || pgm2.height <= 0 || pgm2.max_val <= 0 || pgm2.img_offset < 0 || pgm2.bit_depth != 8 || pgm2.data_type != BYTE || pgm2.num_bands <= 0) { sprintf(msg, "Cannot read PPM/PNG file header in file2\n %s\n", inFile2); if (outputFP) fprintf(outputFP, msg); else fprintf(stderr, msg); if (outputFP) FCLOSE(outputFP); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } // Calculate the peak signal to noise ratio (PSNR) between the two images double sse; double rmse; int ii, jj; long height = MIN(pgm1.height, pgm2.height); long width = MIN(pgm1.width, pgm2.width); long pixel_count = 0; float max_val; if (band1 < 0 || band1 > pgm1.num_bands - 1 || band2 < 0 || band2 > pgm2.num_bands - 1) { sprintf(msg,"Invalid band number for file1 (%d v. %d) or file2 (%d v. %d)" "\n", band1, pgm1.num_bands, band2, pgm2.num_bands); asfPrintWarning(msg); if (outputFP != NULL) fprintf(outputFP, msg); if (fp1) FCLOSE(fp1); if (fp2) FCLOSE(fp2); if (outputFP) FCLOSE(outputFP); else fprintf(stderr, msg); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } if (pgm1.height != pgm2.height) { asfPrintWarning("File1 and File2 have a differing numbers of rows (%d v. " "%d).\nPSNR calculation will only use the first %d rows " "from each file.\n", pgm1.height, pgm2.height, height); } if (pgm1.width != pgm2.width) { asfPrintWarning("File1 and File2 have a different number of pixels per row " "(%d v. %d).\nPSNR calculation will only use the first %d " "pixels from each row of data.\n", pgm1.width, pgm2.width, width); } if (pgm1.data_type != pgm2.data_type) { sprintf(msg,"PPM/PGM files have differing data types.\n"); asfPrintWarning(msg); if (outputFP != NULL) fprintf(outputFP, msg); if (fp1) FCLOSE(fp1); if (fp2) FCLOSE(fp2); if (outputFP) FCLOSE(outputFP); else fprintf(stderr, msg); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } char **band_names1, **band_names2; int num_names_extracted1=0, num_names_extracted2=0; get_band_names(inFile1, NULL, &band_names1, &num_names_extracted1); get_band_names(inFile2, NULL, &band_names2, &num_names_extracted2); asfPrintStatus("\nCalculating PSNR between\n Band %s in %s and\n Band %s " "in %s\n", band_names1[band1], inFile1, band_names2[band2], inFile2); float *buf1 = (float*)CALLOC(pgm1.width, sizeof(float)); float *buf2 = (float*)CALLOC(pgm2.width, sizeof(float)); if (buf1 == NULL || buf2 == NULL) { asfPrintWarning("Cannot allocate memory for PNG data buffers.\n"); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; if (buf1) FREE(buf1); if (buf2) FREE(buf2); if (outputFP) fprintf(outputFP, msg); else fprintf(stderr, msg); if (fp1) FCLOSE(fp1); if (fp2) FCLOSE(fp2); if (outputFP) FCLOSE(outputFP); return; } sse = 0.0; // Since both file's data types are the same, this is OK max_val = get_maxval(pgm1.data_type); fp1 = (FILE*)FOPEN(inFile1, "rb"); fp2 = (FILE*)FOPEN(inFile2, "rb"); FSEEK64(fp1, (long long)pgm1.img_offset, SEEK_SET); FSEEK64(fp2, (long long)pgm2.img_offset, SEEK_SET); for (ii=0; ii<height; ++ii) { asfPercentMeter((double)ii/(double)height); // Get float lines ppm_pgm_get_float_line(fp1, buf1, ii, &pgm1, band1); ppm_pgm_get_float_line(fp2, buf2, ii, &pgm2, band2); for (jj=0; jj<width; ++jj) { cs1 = buf1[jj]; cs2 = buf2[jj]; sse += (cs1 - cs2) * (cs1 - cs2); pixel_count++; } } asfPercentMeter(1.0); if (pixel_count > 0 && max_val > 0) { rmse = sqrt(sse/pixel_count); psnr->psnr = 10.0 * log10(max_val/(rmse+.00000000000001)); psnr->psnr_good = 1; } else { psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; } if (fp1) FCLOSE(fp1); if (fp2) FCLOSE(fp2); if (outputFP) FCLOSE(outputFP); if (buf1) FREE(buf1); if (buf2) FREE(buf2); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); } void free_band_names(char ***band_names, int num_extracted_bands) { if (*band_names != NULL) { int i; if (num_extracted_bands > 0) { for (i=0; i<num_extracted_bands; i++) { if ((*band_names)[i] != NULL) FREE((*band_names)[i]); } } else { for (i=0; i<MAX_BANDS; i++) { if ((*band_names)[i] != NULL) FREE((*band_names)[i]); } } FREE(*band_names); } } METHODDEF(void) jpeg_err_exit(j_common_ptr cinfo) { jpeg_err_hdlr jpeg_err = (jpeg_err_hdlr) cinfo->err; (*cinfo->err->output_message) (cinfo); longjmp (jpeg_err->setjmp_buffer, 1); } GLOBAL(void) get_jpeg_info_hdr_from_file(char *inFile, jpeg_info_t *jpg, char *outputFile) { char msg[1024]; struct jpeg_decompress_struct cinfo; jpeg_error_hdlr_t jerr; FILE *fp, *outFP = NULL; // Init jpg->width = 0; jpg->height = 0; jpg->data_type = 0; jpg->num_bands = 0; // Try file open fp = (FILE*)FOPEN(inFile, "rb"); if (fp == NULL) { sprintf(msg,"Cannot open JPEG file:\n %s\n", inFile); if (outputFile && strlen(outputFile) > 0) outFP = (FILE*)FOPEN(outputFile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); else fprintf(stderr, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } // Setup jpeg lib error handler cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpeg_err_exit; // Error hook to catch jpeg lib errors if (setjmp(jerr.setjmp_buffer)) { // JPEG lib error occurred jpeg_destroy_decompress (&cinfo); if (fp) FCLOSE(fp); sprintf(msg,"JPEG library critical error ...Aborting\n"); if (outputFile && strlen(outputFile) > 0) outFP = (FILE*)FOPEN(outputFile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); else fprintf(stderr, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } // Init jpeg lib to read jpeg_create_decompress(&cinfo); // Init decompression object jpeg_stdio_src(&cinfo, fp); // Set input to open inFile // Read jpeg file header jpeg_read_header(&cinfo, TRUE); // Populate the header struct jpg->width = cinfo.image_width; jpg->byte_width = cinfo.image_width * cinfo.num_components; jpg->height = cinfo.image_height; jpg->data_type = BYTE; jpg->num_bands = cinfo.num_components; // Finish up jpeg_destroy_decompress(&cinfo); if (fp) FCLOSE(fp); } GLOBAL(void) jpeg_image_band_statistics_from_file(char *inFile, char *outfile, int band_no, int *stats_exist, double *min, double *max, double *mean, double *sdev, double *rmse, int use_mask_value, float mask_value) { jpeg_info_t jpg; char msg[1024]; struct jpeg_decompress_struct cinfo; FILE *outFP = NULL; jpeg_error_hdlr_t jerr; JSAMPARRAY jpg_buf; *stats_exist = 1; // Innocent until presumed guilty... get_jpeg_info_hdr_from_file(inFile, &jpg, outfile); if (jpg.width <= 0 || jpg.height <= 0 || jpg.data_type != BYTE || jpg.num_bands <= 0) { *stats_exist = 0; return; } // Minimum and maximum sample values as integers. double fmin = FLT_MAX; double fmax = -FLT_MAX; double cs; // Current sample value *mean = 0.0; double s = 0.0; uint32 sample_count = 0; // Samples considered so far. uint32 jj; FILE *fp = FOPEN(inFile, "rb"); if (fp == NULL) { *stats_exist = 0; return; } // Setup jpeg lib error handler cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpeg_err_exit; // Error hook to catch jpeg lib errors if (setjmp(jerr.setjmp_buffer)) { // JPEG lib error occurred jpeg_destroy_decompress (&cinfo); if (fp) FCLOSE(fp); sprintf(msg,"JPEG library critical error ...Aborting\n"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); else fprintf(stderr, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } // Init jpeg lib to read jpeg_create_decompress(&cinfo); // Init decompression object jpeg_stdio_src(&cinfo, fp); // Set input to open inFile // Read jpeg file header jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); // Allocate buffer for reading jpeg jpg_buf = (*cinfo.mem->alloc_sarray) ((j_common_ptr)&cinfo, JPOOL_IMAGE, jpg.byte_width, 1); // If there is a mask value we are supposed to ignore, if ( use_mask_value ) { // iterate over all rows in the PPM or PGM file while (cinfo.output_scanline < cinfo.image_height) { asfPercentMeter((double)cinfo.output_scanline/(double)jpg.height); jpeg_read_scanlines(&cinfo, jpg_buf, 1); // Reads one scanline for (jj = 0 ; jj < jpg.width; jj++ ) { // iterate over each pixel sample in the scanline if (jpg.num_bands == 1) { cs = (float)jpg_buf[0][jj]; } else if (jpg.num_bands == 3) { cs = (float)jpg_buf[0][jj*3+band_no]; } else { // Shouldn't get here... *stats_exist = 0; return; } if ( !isnan(mask_value) && (gsl_fcmp (cs, mask_value, 0.00000000001) == 0 ) ) { continue; } if ( G_UNLIKELY (cs < fmin) ) { fmin = cs; } if ( G_UNLIKELY (cs > fmax) ) { fmax = cs; } double old_mean = *mean; *mean += (cs - *mean) / (sample_count + 1); s += (cs - old_mean) * (cs - *mean); sample_count++; } } asfPercentMeter(1.0); } else { // There is no mask value to ignore, so we do the same as the // above loop, but without the possible continue statement. while (cinfo.output_scanline < cinfo.image_height) { asfPercentMeter((double)cinfo.output_scanline/(double)jpg.height); jpeg_read_scanlines(&cinfo, jpg_buf, 1); // Reads one scanline for (jj = 0 ; jj < jpg.width; jj++ ) { // iterate over each pixel sample in the scanline if (jpg.num_bands == 1) { cs = (float)jpg_buf[0][jj]; } else if (jpg.num_bands == 3) { cs = (float)jpg_buf[0][jj*3+band_no]; } else { // Shouldn't get here... *stats_exist = 0; return; } if ( G_UNLIKELY (cs < fmin) ) { fmin = cs; } if ( G_UNLIKELY (cs > fmax) ) { fmax = cs; } double old_mean = *mean; *mean += (cs - *mean) / (sample_count + 1); s += (cs - old_mean) * (cs - *mean); sample_count++; } } asfPercentMeter(1.0); } // Verify the new extrema have been found. if (gsl_fcmp (fmin, FLT_MAX, 0.00000000001) == 0 || gsl_fcmp (fmax, -FLT_MAX, 0.00000000001) == 0) { if (fp) FCLOSE(fp); *stats_exist = 0; return; } *min = fmin; *max = fmax; *sdev = sqrt (s / (sample_count - 1)); *rmse = *sdev; // This assumes the sample count is large enough to ensure that the sample // standard deviation is very very similar to the population standard // deviation. // The new extrema had better be in the range supported range if (fabs(*mean) > FLT_MAX || fabs(*sdev) > FLT_MAX) { if (fp) FCLOSE(fp); *stats_exist = 0; return; } // Finish up jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); if (fp) FCLOSE(fp); if (outFP) FCLOSE(outFP); return; } GLOBAL(void) jpeg_image_band_psnr_from_files(char *inFile1, char *inFile2, char *outfile, int band1, int band2, psnr_t *psnr) { jpeg_info_t jpg1, jpg2; char msg[1024]; struct jpeg_decompress_struct cinfo1, cinfo2; FILE *outFP=NULL, *fp1=NULL, *fp2=NULL; jpeg_error_hdlr_t jerr1, jerr2; JSAMPARRAY jpg_buf1, jpg_buf2; float cs1, cs2; fp1 = (FILE*)FOPEN(inFile1, "rb"); fp2 = (FILE*)FOPEN(inFile2, "rb"); if (fp1 == NULL) { if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, "Cannot open file: %s\n", inFile1); else fprintf(stderr, "Cannot open file: %s\n", inFile1); if (outFP) FCLOSE(outFP); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } if (fp2 == NULL) { if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, "Cannot open file: %s\n", inFile2); else fprintf(stderr, "Cannot open file: %s\n", inFile2); if (outFP) FCLOSE(outFP); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } get_jpeg_info_hdr_from_file(inFile1, &jpg1, outfile); if (jpg1.width <= 0 || jpg1.height <= 0 || jpg1.data_type != BYTE || jpg1.num_bands <= 0) { psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } get_jpeg_info_hdr_from_file(inFile2, &jpg2, outfile); if (jpg2.width <= 0 || jpg2.height <= 0 || jpg2.data_type != BYTE || jpg2.num_bands <= 0) { psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } // Setup jpeg lib error handlers cinfo1.err = jpeg_std_error(&jerr1.pub); jerr1.pub.error_exit = jpeg_err_exit; // Error hook to catch jpeg lib errors if (setjmp(jerr1.setjmp_buffer)) { // JPEG lib error occurred jpeg_destroy_decompress (&cinfo1); jpeg_destroy_decompress (&cinfo2); if (fp1) FCLOSE(fp1); if (fp2) FCLOSE(fp2); sprintf(msg,"JPEG library critical error ...Aborting\n"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); else fprintf(stderr, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } cinfo2.err = jpeg_std_error(&jerr2.pub); jerr2.pub.error_exit = jpeg_err_exit; // Error hook to catch jpeg lib errors if (setjmp(jerr2.setjmp_buffer)) { // JPEG lib error occurred jpeg_destroy_decompress (&cinfo1); jpeg_destroy_decompress (&cinfo2); if (fp1) FCLOSE(fp1); if (fp2) FCLOSE(fp2); sprintf(msg,"JPEG library critical error ...Aborting\n"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); else fprintf(stderr, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } // Init jpeg lib to read files jpeg_create_decompress(&cinfo1); // Init decompression object jpeg_stdio_src(&cinfo1, fp1); // Set input to open inFile jpeg_create_decompress(&cinfo2); // Init decompression object jpeg_stdio_src(&cinfo2, fp2); // Set input to open inFile // Read jpeg file headers jpeg_read_header(&cinfo1, TRUE); jpeg_start_decompress(&cinfo1); jpeg_read_header(&cinfo2, TRUE); jpeg_start_decompress(&cinfo2); // Allocate buffers for reading jpeg jpg_buf1 = (*cinfo1.mem->alloc_sarray) ((j_common_ptr)&cinfo1, JPOOL_IMAGE, jpg1.byte_width, 1); jpg_buf2 = (*cinfo2.mem->alloc_sarray) ((j_common_ptr)&cinfo2, JPOOL_IMAGE, jpg2.byte_width, 1); // Calculate the peak signal to noise ratio (PSNR) between the two images double sse; double rmse; int jj; long height = MIN(jpg1.height, jpg2.height); long width = MIN(jpg1.width, jpg2.width); long pixel_count = 0; float max_val; if (band1 < 0 || band1 > jpg1.num_bands - 1 || band2 < 0 || band2 > jpg2.num_bands - 1) { sprintf(msg,"Invalid band number for file1 (%d v. %d) or file2 (%d v. %d)" "\n", band1, jpg1.num_bands, band2, jpg2.num_bands); asfPrintWarning(msg); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); else fprintf(stderr, msg); if (outFP) FCLOSE(outFP); if (fp1) FCLOSE(fp1); if (fp2) FCLOSE(fp2); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } if (jpg1.height != jpg2.height) { asfPrintWarning("File1 and File2 have a differing numbers of rows (%d v. " "%d).\nPSNR calculation will only use the first %d rows " "from each file.\n", jpg1.height, jpg2.height, height); } if (jpg1.width != jpg2.width) { asfPrintWarning("File1 and File2 have a different number of pixels per row " "(%d v. %d).\nPSNR calculation will only use the first %d " "pixels from each row of data.\n", jpg1.width, jpg2.width, width); } if (jpg1.data_type != jpg2.data_type) { sprintf(msg,"Input JPEG files have differing data types.\n"); asfPrintWarning(msg); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); else fprintf(stderr, msg); if (outFP) FCLOSE(outFP); if (fp1) FCLOSE(fp1); if (fp2) FCLOSE(fp2); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } if (jpg1.num_bands != jpg2.num_bands) { sprintf(msg,"Input JPEG files have a different number of bands (%d v. %d)" "\n", jpg1.num_bands, jpg2.num_bands); asfPrintWarning(msg); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); else fprintf(stderr, msg); if (outFP) FCLOSE(outFP); if (fp1) FCLOSE(fp1); if (fp2) FCLOSE(fp2); psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; return; } char **band_names1, **band_names2; int num_names_extracted1=0, num_names_extracted2=0; get_band_names(inFile1, NULL, &band_names1, &num_names_extracted1); get_band_names(inFile2, NULL, &band_names2, &num_names_extracted2); asfPrintStatus("\nCalculating PSNR between\n Band %s in %s and\n Band %s " "in %s\n", band_names1[band1], inFile1, band_names2[band2], inFile2); sse = 0.0; // Since both file's data types are the same, this is OK max_val = get_maxval(jpg1.data_type); while (cinfo1.output_scanline < height && cinfo2.output_scanline < height) { asfPercentMeter((double)cinfo1.output_scanline/(double)jpg1.height); jpeg_read_scanlines(&cinfo1, jpg_buf1, 1); // Reads one scanline jpeg_read_scanlines(&cinfo2, jpg_buf2, 1); // Reads one scanline for (jj=0; jj<width; ++jj) { cs1 = (float)jpg_buf1[0][jj]; cs2 = (float)jpg_buf2[0][jj]; sse += (cs1 - cs2) * (cs1 - cs2); pixel_count++; } } asfPercentMeter(1.0); // Read any unread lines so the jpeg library won't complain when // jpeg_finish_decompress() and jpeg_destroy_decompress() are called... while (cinfo1.output_scanline < jpg1.height) { jpeg_read_scanlines(&cinfo1, jpg_buf1, 1); } while (cinfo2.output_scanline < jpg2.height) { jpeg_read_scanlines(&cinfo2, jpg_buf2, 1); } if (pixel_count > 0 && max_val > 0) { rmse = sqrt(sse/pixel_count); psnr->psnr = 10.0 * log10(max_val/(rmse+.00000000000001)); psnr->psnr_good = 1; } else { psnr->psnr = MISSING_PSNR; psnr->psnr_good = 0; } jpeg_finish_decompress(&cinfo1); jpeg_destroy_decompress(&cinfo1); jpeg_finish_decompress(&cinfo2); jpeg_destroy_decompress(&cinfo2); if (fp1) FCLOSE(fp1); if (fp2) FCLOSE(fp2); if (outFP) FCLOSE(outFP); free_band_names(&band_names1, num_names_extracted1); free_band_names(&band_names2, num_names_extracted2); } // Creates and writes VERY simple metadata file to coax the fftMatch() functions // to work. The only requirements are that the number of lines and samples, and // data type, are required. The rest of the metadata is ignored. void make_generic_meta(char *file, uint32 height, uint32 width, data_type_t data_type) { char file_meta[1024]; char *c; char *f = STRDUP(file); meta_parameters *md; c = findExt(f); *c = '\0'; sprintf(file_meta, "%s.meta", f); md = raw_init(); md->general->line_count = height; md->general->sample_count = width; md->general->data_type = data_type; // This just quiets the fftMatch warnings during meta_read() md->general->image_data_type = AMPLITUDE_IMAGE; meta_write(md, file_meta); meta_free(md); } void diff_check_geolocation(char *outputFile, char *inFile1, char *inFile2, int num_bands, shift_data_t *shift, stats_t *stats1, stats_t *stats2) { char msg[1024]; int band; int low_certainty, empty_band1, empty_band2; float shift_tol = PROJ_LOC_DIFF_TOL_m; float radial_shift_diff = 0.0; int num_extracted_bands1=0, num_extracted_bands2=0; FILE *outputFP = NULL; shift_data_t *s = shift; stats_t *s1 = stats1; stats_t *s2 = stats2; int have_out_file = 0; if (outputFile && strlen(outputFile) > 0) { outputFP = fopen(outputFile, "a"); have_out_file = (outputFP) ? 1 : 0; } else { outputFP = stderr; have_out_file = 0; } // Get or produce band names for intelligent output... char **band_names1 = NULL; char **band_names2 = NULL; get_band_names(inFile1, outputFP, &band_names1, &num_extracted_bands1); get_band_names(inFile2, outputFP, &band_names2, &num_extracted_bands2); // Check each band for differences char band_str1[64]; char band_str2[64]; for (band=0; band<num_bands; band++) { s[band].cert_good = TRUE; s[band].dxdy_good = TRUE; radial_shift_diff = sqrt(s[band].dx * s[band].dx + s[band].dy * s[band].dy); low_certainty = ISNAN(s[band].cert) ? 1 : !ISNAN(s[band].cert) && s[band].cert < MIN_MATCH_CERTAINTY ? 1 : 0; empty_band1 = (FLOAT_EQUIVALENT2(s1[band].mean, 0.0) && FLOAT_EQUIVALENT2(s1[band].sdev, 0.0)) ? 1 : 0; empty_band2 = (FLOAT_EQUIVALENT2(s2[band].mean, 0.0) && FLOAT_EQUIVALENT2(s2[band].sdev, 0.0)) ? 1 : 0; if (!empty_band1 || !empty_band2) { // One or more images have a non-empty band for the current band number, // so check it. if (low_certainty) { fprintf(outputFP, "\n---------------------------------------------\n"); if (num_bands > 1) { sprintf(band_str1, "Band %s in ", band_names1[band]); sprintf(band_str2, "Band %s in ", band_names2[band]); } else { strcpy(band_str1, ""); strcpy(band_str2, ""); } sprintf(msg, "FAIL: diff_check_geolocation() - Correlation match " "between images failed\nwhen trying to find shift in " "geolocation between non-blank\nimages. Comparing\n %s%s " "and\n %s%s\nCertainty = %0.6f\n\n", band_str1, inFile1, band_str2, inFile2, s[band].cert); fprintf(outputFP, msg); s[band].cert_good = FALSE; fprintf(outputFP, "---------------------------------------------\n\n"); } else if (fabs(s[band].dx) > shift_tol || fabs(s[band].dy) > shift_tol || radial_shift_diff > shift_tol) { // The certainty value was OK but the shifts were out of tolerance fprintf(outputFP, "\n----------------------------------------------\n"); if (num_bands > 1) { sprintf(band_str1, "Band %s in ", band_names1[band]); sprintf(band_str2, "Band %s in ", band_names2[band]); } else { strcpy(band_str1, ""); strcpy(band_str2, ""); } sprintf(msg, "FAIL: Comparing geolocations of\n %s%s and\n %s%s\n" "Shifts: dx = %0.3f pixels, dy = %0.3f pixels\n\n", band_str1, inFile1, band_str2, inFile2, s[band].dx, s[band].dy); fprintf(outputFP, msg); s[band].dxdy_good = FALSE; if (s[band].dx > shift_tol) { sprintf(msg, "[%s] [x-loc] File1: %12f, File2: %12f, Tolerance: " "%11f (Certainty: %f%%)\n", s[band].dx > shift_tol ? "FAIL" : "PASS", 0.0, s[band].dx, shift_tol, 100.0 * s[band].cert); fprintf(outputFP, msg); } if (s[band].dy > shift_tol) { sprintf(msg, "[%s] [y-loc] File1: %12f, File2: %12f, Tolerance: " "%11f (Certainty: %f%%)\n", s[band].dy > shift_tol ? "FAIL" : "PASS", 0.0, s[band].dy, shift_tol, 100.0 * s[band].cert); fprintf(outputFP, msg); } if (radial_shift_diff > shift_tol) { sprintf(msg, "[%s] [radial dist] File1: %12f, File2: %12f, " "Tolerance: %11f\n", radial_shift_diff > shift_tol ? "FAIL" : "PASS", 0.0, radial_shift_diff, shift_tol); fprintf(outputFP, msg); } fprintf(outputFP, "---------------------------------------------\n\n"); } else { asfPrintStatus("\nNo differences found in geolocations\n\n"); s[band].cert_good = TRUE; s[band].dxdy_good = TRUE; } } else { if (empty_band1) { asfPrintStatus("Band %s (%02d) in %s is empty ...not checking " "geolocation\n\n", band_names1[band], band, inFile1); } if (empty_band2) { asfPrintStatus("Band %s (%02d) in %s is empty ...not checking " "geolocation\n\n", band_names2[band], band, inFile2); } } } // For each band if (have_out_file && outputFP) FCLOSE(outputFP); free_band_names(&band_names1, num_extracted_bands1); free_band_names(&band_names2, num_extracted_bands2); } void fftShiftCheck(char *file1, char *file2, char *corr_file, shift_data_t *shifts) { fftMatch(file1, file2, NULL/*corr_file*/, &shifts->dx, &shifts->dy, &shifts->cert); // shifts->dx = shifts->dy = 0.0; // shifts->cert = 1.0; } void export_jpeg_to_asf_img(char *inFile, char *outfile, char *fft_file, char *fft_meta_file, uint32 height, uint32 width, data_type_t data_type, int band_no) { meta_parameters *md; float *buf; jpeg_info_t jpg; char msg[1024]; struct jpeg_decompress_struct cinfo; FILE *outFP=NULL, *imgFP=NULL; jpeg_error_hdlr_t jerr; JSAMPARRAY jpg_buf; get_jpeg_info_hdr_from_file(inFile, &jpg, outfile); if (jpg.width <= 0 || jpg.height <= 0 || jpg.data_type != BYTE || jpg.num_bands <= 0) { sprintf(msg,"Invalid JPEG found...Aborting\n"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); else fprintf(stderr, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } // Write out the (very very simple) metadata file ... // only contains line_count, sample_count, and data_type make_generic_meta(fft_meta_file, jpg.height, jpg.width, jpg.data_type); md = meta_read(fft_meta_file); buf = (float*)MALLOC(jpg.width * sizeof(float)); if (buf == NULL) { sprintf(msg,"Cannot allocate float buffer...Aborting\n"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); else fprintf(stderr, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } uint32 jj; FILE *fp = FOPEN(inFile, "rb"); if (fp == NULL) { sprintf(msg,"Cannot open JPEG file for read...Aborting\n"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); else fprintf(stderr, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } // Setup jpeg lib error handler cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpeg_err_exit; // Error hook to catch jpeg lib errors if (setjmp(jerr.setjmp_buffer)) { // JPEG lib error occurred jpeg_destroy_decompress (&cinfo); if (fp) FCLOSE(fp); sprintf(msg,"JPEG library critical error ...Aborting\n"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } // Init jpeg lib to read jpeg_create_decompress(&cinfo); // Init decompression object jpeg_stdio_src(&cinfo, fp); // Set input to open inFile // Read jpeg file header jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); // Allocate buffer for reading jpeg jpg_buf = (*cinfo.mem->alloc_sarray) ( (j_common_ptr)&cinfo, JPOOL_IMAGE, jpg.byte_width, 1); asfPrintStatus("Converting JPEG to ASF Internal Format .img file...\n"); imgFP = (FILE*)FOPEN(fft_file, "wb"); if (imgFP == NULL) { sprintf(msg,"Cannot open IMG file for write...Aborting\n"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } int row=0; while (cinfo.output_scanline < cinfo.image_height) { asfPercentMeter((double)cinfo.output_scanline/(double)jpg.height); jpeg_read_scanlines(&cinfo, jpg_buf, 1); // Reads one scanline for (jj = 0 ; jj < jpg.width; jj++ ) { if (jpg.num_bands == 1) { buf[jj] = (float)jpg_buf[0][jj]; } else if (jpg.num_bands == 3) { buf[jj] = (float)jpg_buf[0][jj*3+band_no]; } else { // Shouldn't get here... sprintf(msg,"Invalid number of bands in JPEG file ...Aborting\n"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } } put_float_line(imgFP, md, row, buf); row++; } asfPercentMeter(1.0); // Finish up jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); if (fp) FCLOSE(fp); if (outFP) FCLOSE(outFP); if (imgFP) FCLOSE(imgFP); if (buf) FREE(buf); meta_free(md); } void export_ppm_pgm_to_asf_img(char *inFile, char *outfile, char *fft_file, char *fft_meta_file, uint32 height, uint32 width, data_type_t data_type, int band_no) { meta_parameters *md; uint32 ii; float *buf; FILE *imgFP=NULL; ppm_pgm_info_t pgm; char msg[1024]; FILE *outFP=NULL; make_generic_meta(fft_meta_file, height, width, data_type); md = meta_read(fft_meta_file); get_ppm_pgm_info_hdr_from_file(inFile, &pgm, outfile); if (pgm.magic == NULL || strlen(pgm.magic) == 0 || pgm.width <= 0 || pgm.height <= 0 || pgm.max_val <= 0 || pgm.img_offset < 0 || pgm.bit_depth != 8 || pgm.data_type != BYTE || pgm.num_bands <= 0) { sprintf(msg,"Invalid PPM/PGM file found...Aborting\n"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } FILE *fp = FOPEN(inFile, "rb"); if (fp == NULL) { sprintf(msg,"Cannot open PPM/PGM file for read ...Aborting\n"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } imgFP = FOPEN(fft_file, "wb"); if (imgFP == NULL) { sprintf(msg,"Cannot open IMG file for write ...Aborting\n"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } buf = (float*)MALLOC(pgm.width * sizeof(float)); if (buf == NULL) { sprintf(msg,"Cannot allocate memory ...Aborting\n"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } asfPrintStatus("\nConverting PPM/PGM file to IMG format...\n"); FSEEK64(fp, (long long)pgm.img_offset, SEEK_SET); for ( ii = 0; ii < pgm.height; ii++ ) { asfPercentMeter((double)ii/(double)pgm.height); ppm_pgm_get_float_line(fp, buf, ii, &pgm, band_no); put_float_line(imgFP, md, ii, buf); } asfPercentMeter(1.0); if (buf) free(buf); if (fp) FCLOSE(fp); if (outFP) FCLOSE(outFP); if (imgFP) FCLOSE(imgFP); meta_free(md); } void export_tiff_to_asf_img(char *inFile, char *outfile, char *fft_file, char *fft_meta_file, uint32 height, uint32 width, data_type_t data_type, int band_no) { meta_parameters *md; FILE *imgFP=NULL, *outFP=NULL; char msg[1024]; make_generic_meta(fft_meta_file, height, width, data_type); md = meta_read(fft_meta_file); tiff_data_t t; tsize_t scanlineSize; get_tiff_info_from_file(inFile, &t); if (t.sample_format == MISSING_TIFF_DATA || t.bits_per_sample == MISSING_TIFF_DATA || t.data_type == 0 || t.num_bands == MISSING_TIFF_DATA || t.is_scanline_format == MISSING_TIFF_DATA || t.height == 0 || t.width == 0) { sprintf(msg,"Invalid TIFF file found ...Aborting\n"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } uint32 ii; TIFF *tif = XTIFFOpen(inFile, "rb"); if (tif == NULL) { sprintf(msg,"Cannot open TIFF file for read ...Aborting\n"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } imgFP = (FILE*)FOPEN(fft_file, "wb"); if (tif == NULL) { if (tif) XTIFFClose(tif); sprintf(msg,"Cannot open IMG file for write ...Aborting\n"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } scanlineSize = TIFFScanlineSize(tif); if (scanlineSize <= 0) { if (tif) XTIFFClose(tif); sprintf(msg,"Invalid scan line size in TIFF file ...Aborting\n"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } if (t.num_bands > 1 && t.planar_config != PLANARCONFIG_CONTIG && t.planar_config != PLANARCONFIG_SEPARATE) { if (tif) XTIFFClose(tif); sprintf(msg,"Invalid planar configuration found in TIFF file ..." "Aborting\n"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } float *buf = (float*)MALLOC(t.width * sizeof(float)); asfPrintStatus("Converting TIFF file to IMG file..\n"); for ( ii = 0; ii < t.height; ii++ ) { asfPercentMeter((double)ii/(double)t.height); tiff_get_float_line(tif, buf, ii, band_no); put_float_line(imgFP, md, ii, buf); } asfPercentMeter(1.0); if (buf) free(buf); if (tif) XTIFFClose(tif); if (imgFP) FCLOSE(imgFP); if (outFP) FCLOSE(outFP); meta_free(md); } void export_png_to_asf_img(char *inFile, char *outfile, char *fft_file, char *fft_meta_file, uint32 img_height, uint32 img_width, data_type_t img_data_type, int band_no) { meta_parameters *md; FILE *imgFP=NULL, *outFP=NULL; make_generic_meta(fft_meta_file, img_height, img_width, img_data_type); md = meta_read(fft_meta_file); png_structp png_ptr; png_infop info_ptr; png_uint_32 width, height; int bit_depth, color_type, interlace_type, compression_type, filter_type; unsigned char sig[8]; char msg[1024]; FILE *pngFP; png_info_t ihdr; get_png_info_hdr_from_file(inFile, &ihdr, outfile); if (ihdr.bit_depth == MISSING_PNG_DATA || ihdr.color_type == MISSING_PNG_DATA || (ihdr.color_type_str == NULL || strlen(ihdr.color_type_str) <= 0) || ihdr.interlace_type == MISSING_PNG_DATA || ihdr.compression_type == MISSING_PNG_DATA || ihdr.filter_type == MISSING_PNG_DATA || ihdr.data_type == 0 || ihdr.num_bands == MISSING_PNG_DATA || ihdr.height == 0 || ihdr.width == 0) { sprintf(msg,"Invalid PNG file found ...Aborting\n"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } imgFP = (FILE*)FOPEN(fft_file,"wb"); if (imgFP == NULL) { sprintf(msg,"Cannot open IMG file ...Aborting\n"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } // Initialize PNG file for read pngFP = (FILE*)FOPEN(inFile,"rb"); if (pngFP == NULL) { sprintf(msg,"Cannot open PNG file ...Aborting\n"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } // Important: Leaves file pointer offset into file by 8 bytes for png lib fread(sig, 1, 8, pngFP); if (!png_check_sig(sig, 8)) { // Bad PNG magic number (signature) if (pngFP) FCLOSE(pngFP); sprintf(msg, "Invalid PNG file (%s)\n", "file type header bytes invalid"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } png_ptr = png_create_read_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { if (pngFP) FCLOSE(pngFP); sprintf(msg, "Cannot allocate PNG read struct ...Aborting"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, NULL, NULL); if (pngFP) FCLOSE(pngFP); sprintf(msg, "Cannot allocate PNG info struct ...Aborting"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } if (setjmp(png_jmpbuf(png_ptr))) { if (pngFP) FCLOSE(pngFP); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); sprintf(msg, "PNG library error occurred ...Aborting"); if (outfile && strlen(outfile) > 0) outFP = (FILE*)FOPEN(outfile,"a"); else outFP = NULL; if (outFP) fprintf(outFP, msg); if (outFP) FCLOSE(outFP); asfPrintError(msg); } png_init_io(png_ptr, pngFP); // Because of the sig-reading offset ...must do this for PNG lib png_set_sig_bytes(png_ptr, 8); // Read info and IHDR png_read_info(png_ptr, info_ptr); png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_type); uint32 ii; float *buf = (float*)MALLOC(ihdr.width * sizeof(float)); for ( ii = 0; ii < ihdr.height; ii++ ) { asfPercentMeter((double)ii/(double)ihdr.height); png_sequential_get_float_line(png_ptr, info_ptr, buf, band_no); put_float_line(imgFP, md, ii, buf); } asfPercentMeter(1.0); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); if (buf) free(buf); if (outFP) FCLOSE(outFP); if (pngFP) FCLOSE(pngFP); if (imgFP) FCLOSE(imgFP); meta_free(md); } // Calling code must free the returned string char *pcs2description(int pcs) { char *pcs_description = (char*)MALLOC(512*sizeof(char)); int pcs_datum = pcs/100; int pcs_zone = pcs - (pcs_datum * 100); char pcs_hem = (pcs_datum == 323) ? 'S' : (pcs_datum == 327) ? 'S' : (pcs_datum == 269) ? 'N' : (pcs_datum == 267) ? 'N' : (pcs_datum == 322) ? 'N' : (pcs_datum == 326) ? 'N' : '?'; sprintf(pcs_description, "UTM Zone %02d, %c hemisphere", pcs_zone, pcs_hem); switch(pcs_datum) { case 269: strcat(pcs_description, ", NAD_83 datum"); break; case 267: strcat(pcs_description, ", NAD_27 datum"); break; case 322: case 323: strcat(pcs_description, ", WGS_72 datum"); break; case 326: case 327: strcat(pcs_description, ", WGS_84 datum"); break; default: strcat(pcs_description, ", UNKNOWN or UNRECOGNIZED datum"); break; } return pcs_description; } void calc_complex_stats_rmse_from_file(const char *inFile, const char *band, double mask, double *i_min, double *i_max, double *i_mean, double *i_stdDev, double *i_rmse, gsl_histogram **i_histogram, double *q_min, double *q_max, double *q_mean, double *q_stdDev, double *q_rmse, gsl_histogram **q_histogram) { double i_se, q_se; int ii,jj; *i_min = 999999; *i_max = -999999; *i_mean = 0.0; *q_min = 999999; *q_max = -999999; *q_mean = 0.0; meta_parameters *meta = meta_read(inFile); int band_number = (!band || strlen(band) == 0 || strcmp(band, "???") == 0) ? 0 : get_band_number(meta->general->bands, meta->general->band_count, band); long offset = meta->general->line_count * band_number; complexFloat *cdata = CALLOC(meta->general->sample_count, sizeof(complexFloat)); // pass 1 -- calculate mean, min & max FILE *fp = FOPEN(inFile, "rb"); long long i_pixel_count=0; long long q_pixel_count=0; asfPrintStatus("\nCalculating min, max, and mean...\n"); for (ii=0; ii<meta->general->line_count; ++ii) { asfPercentMeter(((double)ii/(double)meta->general->line_count)); get_complexFloat_line(fp, meta, ii + offset, cdata); for (jj=0; jj<meta->general->sample_count; ++jj) { if (ISNAN(mask) || !FLOAT_EQUIVALENT2(cdata[jj].imag, mask)) { if (cdata[jj].imag < *i_min) *i_min = cdata[jj].imag; if (cdata[jj].imag > *i_max) *i_max = cdata[jj].imag; *i_mean += cdata[jj].imag; ++i_pixel_count; } if (ISNAN(mask) || !FLOAT_EQUIVALENT2(cdata[jj].real, mask)) { if (cdata[jj].real < *q_min) *q_min = cdata[jj].real; if (cdata[jj].real > *q_max) *q_max = cdata[jj].real; *q_mean += cdata[jj].real; ++q_pixel_count; } } } asfPercentMeter(1.0); FCLOSE(fp); *i_mean /= i_pixel_count; *q_mean /= q_pixel_count; // Guard against weird data if(!(*i_min<*i_max)) *i_max = *i_min + 1; if(!(*q_min<*q_max)) *q_max = *q_min + 1; // Initialize the histogram. const int num_bins = 256; gsl_histogram *i_hist = gsl_histogram_alloc (num_bins); gsl_histogram_set_ranges_uniform (i_hist, *i_min, *i_max); *i_stdDev = 0.0; gsl_histogram *q_hist = gsl_histogram_alloc (num_bins); gsl_histogram_set_ranges_uniform (q_hist, *q_min, *q_max); *q_stdDev = 0.0; // pass 2 -- update histogram, calculate standard deviation fp = FOPEN(inFile, "rb"); asfPrintStatus("\nCalculating standard deviation, rmse, and histogram...\n"); i_se = q_se = 0.0; for (ii=0; ii<meta->general->line_count; ++ii) { asfPercentMeter(((double)ii/(double)meta->general->line_count)); get_complexFloat_line(fp, meta, ii + offset, cdata); for (jj=0; jj<meta->general->sample_count; ++jj) { if (ISNAN(mask) || !FLOAT_EQUIVALENT2(cdata[jj].imag, mask)) { *i_stdDev += (cdata[jj].imag - *i_mean) * (cdata[jj].imag - *i_mean); gsl_histogram_increment (i_hist, cdata[jj].imag); i_se += (cdata[jj].imag - *i_mean) * (cdata[jj].imag - *i_mean); } if (ISNAN(mask) || !FLOAT_EQUIVALENT2(cdata[jj].real, mask)) { *q_stdDev += (cdata[jj].real - *q_mean) * (cdata[jj].real - *q_mean); gsl_histogram_increment (q_hist, cdata[jj].real); q_se += (cdata[jj].real - *q_mean) * (cdata[jj].real - *q_mean); } } } asfPercentMeter(1.0); FCLOSE(fp); *i_stdDev = sqrt(*i_stdDev/(i_pixel_count - 1)); *i_rmse = sqrt(i_se/(i_pixel_count - 1)); *q_stdDev = sqrt(*q_stdDev/(q_pixel_count - 1)); *q_rmse = sqrt(q_se/(q_pixel_count - 1)); FREE(cdata); *i_histogram = i_hist; *q_histogram = q_hist; } void diff_check_complex_stats(char *outputFile, char *inFile1, char *inFile2, complex_stats_t *cstats1, complex_stats_t *cstats2, complex_psnr_t *cpsnr, int strict, data_type_t data_type, int num_bands) { char msg[1024]; int band; double baseline_range1; double baseline_range2; double min_tol; double max_tol; double mean_tol; double sdev_tol; // double rmse_tol; double psnr_tol; double min_diff; double max_diff; double mean_diff; double sdev_diff; // double rmse_diff; stats_t *stats1 = NULL; stats_t *stats2 = NULL; psnr_t *psnr = NULL; int num_extracted_bands1=0, num_extracted_bands2=0; FILE *outputFP = NULL; int output_file_exists = 0; if (outputFile && strlen(outputFile) > 0) { outputFP = (FILE*)FOPEN(outputFile, "a"); if (outputFP) { output_file_exists = 1; } else { outputFP = stderr; output_file_exists = 0; } } else { outputFP = stderr; output_file_exists = 0; } // Get or produce band names for intelligent output... char **band_names1 = NULL; char **band_names2 = NULL; get_band_names(inFile1, outputFP, &band_names1, &num_extracted_bands1); get_band_names(inFile2, outputFP, &band_names2, &num_extracted_bands2); // Check each band for differences char band_str1[64]; char band_str2[64]; for (band=0; band<num_bands; band++) { int i; for (i=0; i<2; i++) { char val_name[16]; // Loops twice ...once to diff check the stats on the i values, once to // diff check the stats on the q values stats1 = i ? &cstats1[band].i : &cstats1[band].q; stats2 = i ? &cstats2[band].i : &cstats2[band].q; psnr = i ? &cpsnr[band].i : &cpsnr[band].q; strcpy(val_name, i ? "i-values" : "q-values"); // If differences exist, then produce an output file with content, else // produce an empty output file (handy for scripts that check for file // existence AND file size greater than zero) // // Compare statistics // Assume 6-sigma range (99.999999%) is full range of data baseline_range1 = fabs(stats1->sdev) * 6.0; // Assume 6-sigma range (99.999999%) is full range of data baseline_range2 = fabs(stats2->sdev) * 6.0; min_tol = (MIN_DIFF_TOL/100.0)*baseline_range1; max_tol = (MAX_DIFF_TOL/100.0)*baseline_range1; mean_tol = (MEAN_DIFF_TOL/100.0)*baseline_range1; sdev_tol = (SDEV_DIFF_TOL/100.0)*baseline_range1; // FIXME: Rather than use data_type, use the baseline range to develop // a suitable PSNR tolerance switch (data_type) { case BYTE: case COMPLEX_BYTE: psnr_tol = BYTE_PSNR_TOL; break; case INTEGER16: case COMPLEX_INTEGER16: psnr_tol = INTEGER16_PSNR_TOL; break; case INTEGER32: case COMPLEX_INTEGER32: psnr_tol = INTEGER32_PSNR_TOL; break; case REAL32: case COMPLEX_REAL32: default: psnr_tol = REAL32_PSNR_TOL; break; } min_diff = fabs(stats2->min - stats1->min); max_diff = fabs(stats2->max - stats1->max); mean_diff = fabs(stats2->mean - stats1->mean); sdev_diff = fabs(baseline_range2 - baseline_range1); if (strict && (stats1->stats_good && stats2->stats_good) && (min_diff > min_tol || max_diff > max_tol || mean_diff > mean_tol || sdev_diff > sdev_tol || psnr->psnr < psnr_tol)) { // Strict comparison utilizes all values fprintf(outputFP, "\n---------------------------------------------\n"); fprintf(outputFP, "Files contain COMPLEX values.\n"); if (num_bands > 1) { sprintf(band_str1, "Band %s in ", band_names1[band]); sprintf(band_str2, "Band %s in ", band_names2[band]); } else { strcpy(band_str1, ""); strcpy(band_str2, ""); } sprintf(msg, "Comparing %s...\nFAIL: Comparing\n %s%s\nto\n %s%s\n\n", val_name, band_str1, inFile1, band_str2, inFile2); fprintf(outputFP, msg); sprintf(msg, "[%s] [min] File1: %12f, File2: %12f, Tolerance: %11f " "(%3f Percent)\n", min_diff > min_tol ? "FAIL" : "PASS", stats1->min, stats2->min, min_tol, MIN_DIFF_TOL); fprintf(outputFP, msg); sprintf(msg, "[%s] [max] File1: %12f, File2: %12f, Tolerance: %11f " "(%3f Percent)\n", max_diff > max_tol ? "FAIL" : "PASS", stats1->max, stats2->max, max_tol, MAX_DIFF_TOL); fprintf(outputFP, msg); sprintf(msg, "[%s] [mean] File1: %12f, File2: %12f, Tolerance: %11f " "(%3f Percent)\n", mean_diff > mean_tol ? "FAIL" : "PASS", stats1->mean, stats2->mean, mean_tol, MEAN_DIFF_TOL); fprintf(outputFP, msg); sprintf(msg, "[%s] [sdev] File1: %12f, File2: %12f, Tolerance: %11f " "(%3f Percent)\n", sdev_diff > sdev_tol ? "FAIL" : "PASS", stats1->sdev, stats2->sdev, sdev_tol/6.0, SDEV_DIFF_TOL); fprintf(outputFP, msg); if (psnr[band].psnr_good) { sprintf(msg, "[%s] [PSNR] PSNR: %12f, PSNR " "Minimum: %11f (higher == better)\n", psnr->psnr < psnr_tol ? "FAIL" : "PASS", psnr->psnr, psnr_tol); } else { sprintf(msg, "[FAIL] [PSNR] PSNR: MISSING, " "PSNR Minimum: %11f (higher == better)\n", psnr_tol); } fprintf(outputFP, msg); fprintf(outputFP, "---------------------------------------------\n\n"); } else if (!strict && (stats1->stats_good && stats2->stats_good) && (mean_diff > mean_tol || sdev_diff > sdev_tol || psnr->psnr < psnr_tol)) { // If not doing strict checking, skip comparing min and max values fprintf(outputFP, "\n--------------------------------------------\n"); fprintf(outputFP, "Files contain COMPLEX values.\n"); char msg[1024]; if (num_bands > 1) { sprintf(band_str1, "Band %s in ", band_names1[band]); sprintf(band_str2, "Band %s in ", band_names2[band]); } else { strcpy(band_str1, ""); strcpy(band_str2, ""); } sprintf(msg, "Comparing %s...\nFAIL: Comparing\n %s%s\nto\n %s%s" "\n\n", val_name, band_str1, inFile1, band_str2, inFile2); fprintf(outputFP, msg); sprintf(msg, "[%s] [mean] File1: %12f, File2: %12f, Tolerance: " "%11f (%3f Percent)\n", mean_diff > mean_tol ? "FAIL" : "PASS", stats1->mean, stats2->mean, mean_tol, MEAN_DIFF_TOL); fprintf(outputFP, msg); sprintf(msg, "[%s] [sdev] File1: %12f, File2: %12f, Tolerance: " "%11f (%3f Percent)\n", sdev_diff > sdev_tol ? "FAIL" : "PASS", stats1->sdev, stats2->sdev, sdev_tol/6.0, SDEV_DIFF_TOL); fprintf(outputFP, msg); if (psnr[band].psnr_good) { sprintf(msg, "[%s] [PSNR] PSNR: %12f, PSNR " "Minimum: %11f (higher == better)\n", psnr->psnr < psnr_tol ? "FAIL" : "PASS", psnr->psnr, psnr_tol); } else { sprintf(msg, "[FAIL] [PSNR] PSNR: MISSING, " " PSNR Minimum: %11f (higher == better)\n", psnr_tol); } fprintf(outputFP, msg); fprintf(outputFP, "--------------------------------------------\n\n"); } else if (stats1->stats_good && stats2->stats_good) { if (num_bands > 1) { sprintf(band_str1, "Band %s in ", band_names1[band]); sprintf(band_str2, "Band %s in ", band_names2[band]); } else { strcpy(band_str1, ""); strcpy(band_str2, ""); } asfPrintStatus("\nThe files contain COMPLEX data... Comparing %s\n", val_name); asfPrintStatus("PASS: No differences found in Image Statistics when " "comparing\n %s%s to\n %s%s\n\n", band_str1, inFile1, band_str2, inFile2); print_stats_results(inFile1, inFile2, band_str1, band_str2, stats1, stats2, i ? cpsnr[band].i : cpsnr[band].q); } if (!stats1->stats_good || !stats2->stats_good) { char msg[1024]; fprintf(outputFP, "\n---------------------------------------------\n"); fprintf(outputFP, "Files contain COMPLEX values... Comparing %s\n", val_name); if (num_bands > 1) { sprintf(band_str1, "Band %s in ", band_names1[band]); sprintf(band_str2, "Band %s in ", band_names2[band]); } else { strcpy(band_str1, ""); strcpy(band_str2, ""); } if (!stats1->stats_good) { sprintf(msg, "FAIL: %s%s image statistics missing.\n", band_str1, inFile1); fprintf(outputFP, msg); } if (!stats2->stats_good) { sprintf(msg, "FAIL: %s%s image statistics missing.\n", band_str2, inFile2); fprintf(outputFP, msg); } fprintf(outputFP, "---------------------------------------------\n\n"); } } // For i value stats and q value stats } // For each band if (output_file_exists && outputFP) FCLOSE(outputFP); free_band_names(&band_names1, num_extracted_bands1); free_band_names(&band_names2, num_extracted_bands2); }
{ "alphanum_fraction": 0.595153186, "avg_line_length": 35.2807852469, "ext": "c", "hexsha": "ca9215154f5bc7818bf051ffb5fc49bb39ee7b30", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_path": "src/libasf_raster/diffimage.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "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": "glshort/MapReady", "max_issues_repo_path": "src/libasf_raster/diffimage.c", "max_line_length": 92, "max_stars_count": 3, "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_path": "src/libasf_raster/diffimage.c", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "num_tokens": 70814, "size": 237228 }
/* # File : condat_l1ballproj.c # # Version History : 1.0, Aug. 15, 2014 # # Author : Laurent Condat, PhD, CNRS research fellow in France. # # Description : This file contains an implementation in the C language # of algorithms described in the research paper: # # L. Condat, "Fast Projection onto the Simplex and the # l1 Ball", preprint Hal-01056171, 2014. # # This implementation comes with no warranty: due to the # limited number of tests performed, there may remain # bugs. In case the functions would not do what they are # supposed to do, please email the author (contact info # to be found on the web). # # If you use this code or parts of it for any purpose, # the author asks you to cite the paper above or, in # that event, its published version. Please email him if # the proposed algorithms were useful for one of your # projects, or for any comment or suggestion. # # Usage rights : Copyright Laurent Condat. # This file is distributed under the terms of the CeCILL # licence (compatible with the GNU GPL), which can be # found at the URL "http://www.cecill.info". # # This software is governed by the CeCILL license under French law and # abiding by the rules of distribution of free software. You can use, # modify and or redistribute the software under the terms of the CeCILL # license as circulated by CEA, CNRS and INRIA at the following URL : # "http://www.cecill.info". # # As a counterpart to the access to the source code and rights to copy, # modify and redistribute granted by the license, users are provided only # with a limited warranty and the software's author, the holder of the # economic rights, and the successive licensors have only limited # liability. # # In this respect, the user's attention is drawn to the risks associated # with loading, using, modifying and/or developing or reproducing the # software by the user in light of its specific status of free software, # that may mean that it is complicated to manipulate, and that also # therefore means that it is reserved for developers and experienced # professionals having in-depth computer knowledge. Users are therefore # encouraged to load and test the software's suitability as regards their # requirements in conditions enabling the security of their systems and/or # data to be ensured and, more generally, to use and operate it in the # same conditions as regards security. # # The fact that you are presently reading this means that you have had # knowledge of the CeCILL license and that you accept its terms. */ /* This code was compiled using gcc -march=native -O2 condat_l1ballproj.c -o main -I/usr/local/include/ -lm -lgsl -L/usr/local/lib/ On my machine, gcc is actually a link to the compiler Apple LLVM version 5.1 (clang-503.0.40) */ /* The following functions are implemented: l1ballproj_IBIS l1ballproj_Condat (proposed algorithm) These functions take the same parameters. They project the vector y onto the closest vector x of same length (parameter N in the paper) with sum_{n=0}^{N-1}|x[n]|<=a. We must have length>=1. For l1ballproj_Condat only: we can have x==y (projection done in place). If x!=y, the arrays x and y must not overlap, as x is used for temporary calculations before y is accessed. */ #include <stdlib.h> #include <stdio.h> #include <time.h> #include <math.h> #include <string.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #define datatype double /* type of the elements in y */ /* Proposed algorithm */ static void l1ballproj_Condat(datatype* y, datatype* x, const unsigned int length, const double a) { if (a<=0.0) { if (a==0.0) memset(x,0,length*sizeof(datatype)); return; } datatype* aux = (x==y ? (datatype*)malloc(length*sizeof(datatype)) : x); int auxlength=1; int auxlengthold=-1; double tau=(*aux=(*y>=0.0 ? *y : -*y))-a; int i=1; for (; i<length; i++) if (y[i]>0.0) { if (y[i]>tau) { if ((tau+=((aux[auxlength]=y[i])-tau)/(auxlength-auxlengthold)) <=y[i]-a) { tau=y[i]-a; auxlengthold=auxlength-1; } auxlength++; } } else if (y[i]!=0.0) { if (-y[i]>tau) { if ((tau+=((aux[auxlength]=-y[i])-tau)/(auxlength-auxlengthold)) <=aux[auxlength]-a) { tau=aux[auxlength]-a; auxlengthold=auxlength-1; } auxlength++; } } if (tau<=0) { /* y is in the l1 ball => x=y */ if (x!=y) memcpy(x,y,length*sizeof(datatype)); else free(aux); } else { datatype* aux0=aux; if (auxlengthold>=0) { auxlength-=++auxlengthold; aux+=auxlengthold; while (--auxlengthold>=0) if (aux0[auxlengthold]>tau) tau+=((*(--aux)=aux0[auxlengthold])-tau)/(++auxlength); } do { auxlengthold=auxlength-1; for (i=auxlength=0; i<=auxlengthold; i++) if (aux[i]>tau) aux[auxlength++]=aux[i]; else tau+=(tau-aux[i])/(auxlengthold-i+auxlength); } while (auxlength<=auxlengthold); for (i=0; i<length; i++) x[i]=(y[i]-tau>0.0 ? y[i]-tau : (y[i]+tau<0.0 ? y[i]+tau : 0.0)); if (x==y) free(aux0); } } /* function eplb of the package SLEP, implementing the algorithm IBIS of the paper J. Liu and J. Ye. Efficient Euclidean Projections in Linear Time, ICML 2009. Version without the initial guess lambda0 of lambda (tau in our notations) */ static void l1ballproj_IBIS(datatype* y, datatype* x, const unsigned int length, const double a) { #define delta 1e-13 int i, j, flag=0; int rho_1, rho_2, rho, rho_T, rho_S; int V_i_b, V_i_e, V_i; double lambda_1, lambda_2, lambda_T, lambda_S, lambda; double s_1, s_2, s, s_T, s_S, y_max, temp; double f_lambda_1, f_lambda_2, f_lambda, f_lambda_T, f_lambda_S; int iter_step=0; /* find the maximal absolute value in y * and copy the (absolute) values from y to x */ /*if (a< 0){ printf("\n a should be nonnegative!"); return; }*/ V_i=0; if (y[0] !=0){ rho_1=1; s_1=x[V_i]=y_max=fabs(y[0]); V_i++; } else{ rho_1=0; s_1=y_max=0; } for (i=1;i<length; i++){ if (y[i]!=0){ x[V_i]=fabs(y[i]); s_1+= x[V_i]; rho_1++; if (x[V_i] > y_max) y_max=x[V_i]; V_i++; } } /* If ||y||_1 <= a, then y is the solution */ if (s_1 <= a){ flag=1; lambda=0; for(i=0;i<length;i++){ x[i]=y[i]; } /**root=lambda; *steps=iter_step;*/ return; } lambda_1=0; lambda_2=y_max; f_lambda_1=s_1 -a; /*f_lambda_1=s_1-rho_1* lambda_1 -a;*/ rho_2=0; s_2=0; f_lambda_2=-a; V_i_b=0; V_i_e=V_i-1; /*lambda=lambda0; if ( (lambda<lambda_2) && (lambda> lambda_1) ){ i=V_i_b; j=V_i_e; rho=0; s=0; while (i <= j){ while( (i <= V_i_e) && (x[i] <= lambda) ){ i++; } while( (j>=V_i_b) && (x[j] > lambda) ){ s+=x[j]; j--; } if (i<j){ s+=x[i]; temp=x[i]; x[i]=x[j]; x[j]=temp; i++; j--; } } rho=V_i_e-j; rho+=rho_2; s+=s_2; f_lambda=s-rho*lambda-a; if ( fabs(f_lambda)< delta ){ flag=1; } if (f_lambda <0){ lambda_2=lambda; s_2=s; rho_2=rho; f_lambda_2=f_lambda; V_i_e=j; V_i=V_i_e-V_i_b+1; } else{ lambda_1=lambda; rho_1=rho; s_1=s; f_lambda_1=f_lambda; V_i_b=i; V_i=V_i_e-V_i_b+1; } if (V_i==0){ lambda=(s - a)/ rho; flag=1; } }*/ while (!flag){ iter_step++; /* compute lambda_T */ lambda_T=lambda_1 + f_lambda_1 /rho_1; if(rho_2 !=0){ if (lambda_2 + f_lambda_2 /rho_2 > lambda_T) lambda_T=lambda_2 + f_lambda_2 /rho_2; } /* compute lambda_S */ lambda_S=lambda_2 - f_lambda_2 *(lambda_2-lambda_1)/(f_lambda_2-f_lambda_1); if (fabs(lambda_T-lambda_S) <= delta){ lambda=lambda_T; flag=1; break; } /* set lambda as the middle point of lambda_T and lambda_S */ lambda=(lambda_T+lambda_S)/2; s_T=s_S=s=0; rho_T=rho_S=rho=0; i=V_i_b; j=V_i_e; while (i <= j){ while( (i <= V_i_e) && (x[i] <= lambda) ){ if (x[i]> lambda_T){ s_T+=x[i]; rho_T++; } i++; } while( (j>=V_i_b) && (x[j] > lambda) ){ if (x[j] > lambda_S){ s_S+=x[j]; rho_S++; } else{ s+=x[j]; rho++; } j--; } if (i<j){ if (x[i] > lambda_S){ s_S+=x[i]; rho_S++; } else{ s+=x[i]; rho++; } if (x[j]> lambda_T){ s_T+=x[j]; rho_T++; } temp=x[i]; x[i]=x[j]; x[j]=temp; i++; j--; } } s_S+=s_2; rho_S+=rho_2; s+=s_S; rho+=rho_S; s_T+=s; rho_T+=rho; f_lambda_S=s_S-rho_S*lambda_S-a; f_lambda=s-rho*lambda-a; f_lambda_T=s_T-rho_T*lambda_T-a; /*printf("\n %d & %d & %5.6f & %5.6f & %5.6f & %5.6f & %5.6f \\\\ \n \\hline ", iter_step, V_i, lambda_1, lambda_T, lambda, lambda_S, lambda_2);*/ if ( fabs(f_lambda)< delta ){ /*printf("\n lambda");*/ flag=1; break; } if ( fabs(f_lambda_S)< delta ){ /* printf("\n lambda_S");*/ lambda=lambda_S; flag=1; break; } if ( fabs(f_lambda_T)< delta ){ /* printf("\n lambda_T");*/ lambda=lambda_T; flag=1; break; } /* printf("\n\n f_lambda_1=%5.6f, f_lambda_2=%5.6f, f_lambda=%5.6f",f_lambda_1,f_lambda_2, f_lambda); printf("\n lambda_1=%5.6f, lambda_2=%5.6f, lambda=%5.6f",lambda_1, lambda_2, lambda); printf("\n rho_1=%d, rho_2=%d, rho=%d ",rho_1, rho_2, rho); */ if (f_lambda <0){ lambda_2=lambda; s_2=s; rho_2=rho; f_lambda_2=f_lambda; lambda_1=lambda_T; s_1=s_T; rho_1=rho_T; f_lambda_1=f_lambda_T; V_i_e=j; i=V_i_b; while (i <= j){ while( (i <= V_i_e) && (x[i] <= lambda_T) ){ i++; } while( (j>=V_i_b) && (x[j] > lambda_T) ){ j--; } if (i<j){ x[j]=x[i]; i++; j--; } } V_i_b=i; V_i=V_i_e-V_i_b+1; } else{ lambda_1=lambda; s_1=s; rho_1=rho; f_lambda_1=f_lambda; lambda_2=lambda_S; s_2=s_S; rho_2=rho_S; f_lambda_2=f_lambda_S; V_i_b=i; j=V_i_e; while (i <= j){ while( (i <= V_i_e) && (x[i] <= lambda_S) ){ i++; } while( (j>=V_i_b) && (x[j] > lambda_S) ){ j--; } if (i<j){ x[i]=x[j]; i++; j--; } } V_i_e=j; V_i=V_i_e-V_i_b+1; } if (V_i==0){ lambda=(s - a)/ rho; flag=1; /*printf("\n V_i=0, lambda=%5.6f",lambda);*/ break; } }/* end of while */ for(i=0;i<length;i++){ if (y[i] > lambda) x[i]=y[i]-lambda; else if (y[i]< -lambda) x[i]=y[i]+lambda; else x[i]=0; } /**root=lambda; *steps=iter_step;*/ } /* Example of code to compare the computation times Result on my machine: my algorithm is 2.5x faster than IBIS */ int main() { datatype* y; datatype* x; double val=0.0; double aux; double epsi; int i,j; int Nbrea; unsigned int length; clock_t start, end; const gsl_rng_type *T; gsl_rng *r; gsl_rng_env_setup(); gsl_rng_default_seed=32067; T = gsl_rng_default; r = gsl_rng_alloc(T); double timemean=0.0, timevar=0.0, timedelta; const double a = 1.0; srand((unsigned int)pow(time(NULL)%100,3)); double* timetable; length = 1000000; Nbrea = 100; y=(datatype*)malloc(length*sizeof(datatype)); x=(datatype*)malloc(length*sizeof(datatype)); timetable=(double*)malloc((Nbrea+1)*sizeof(double)); for (j=0; j<=Nbrea; j++) { for (i=0; i<length; i++) { y[i]=gsl_ran_gaussian(r, 0.01); } y[(int)(rand() / (((double)RAND_MAX+1.0)/length))]+=a; start=clock(); l1ballproj_Condat(y,x,length,a); /*l1ballproj_IBIS(y,x,length,a); */ end=clock(); timetable[j]=(double)(end-start)/CLOCKS_PER_SEC; } /* we discard the first value, because the computation time is higher, probably because of cache operations */ for (j=1; j<=Nbrea; j++) { timedelta=timetable[j]-timemean; timemean+=timedelta/j; timevar+=timedelta*(timetable[j]-timemean); } timevar=sqrt(timevar/Nbrea); printf("av. time: %e std dev: %e\n",timemean,timevar); free(x); free(y); return 0; }
{ "alphanum_fraction": 0.5331524131, "avg_line_length": 29.4470842333, "ext": "c", "hexsha": "63b3173f777e82b5ea05389a67057bfb901be146", "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": "54321da61c6d3d0d0c2a8d612a6b4ce8771565f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "c-elvira/bayesian_antisparse_algorithm", "max_forks_repo_path": "condat_l1ballproj.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "54321da61c6d3d0d0c2a8d612a6b4ce8771565f2", "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": "c-elvira/bayesian_antisparse_algorithm", "max_issues_repo_path": "condat_l1ballproj.c", "max_line_length": 155, "max_stars_count": 1, "max_stars_repo_head_hexsha": "54321da61c6d3d0d0c2a8d612a6b4ce8771565f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "c-elvira/bayesian_antisparse_algorithm", "max_stars_repo_path": "condat_l1ballproj.c", "max_stars_repo_stars_event_max_datetime": "2019-03-14T13:27:56.000Z", "max_stars_repo_stars_event_min_datetime": "2019-03-14T13:27:56.000Z", "num_tokens": 4061, "size": 13634 }
// This matrix class is a C++ wrapper for the GNU Scientific Library // Copyright (C) ULP-IPB Strasbourg // 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., 675 Mass Ave, Cambridge, MA 02139, USA. #ifndef __matrix_vector_operators_h #define __matrix_vector_operators_h #include "gsl/gsl_blas.h" #include <gslwrap/matrix_double.h> #include <gslwrap/matrix_float.h> #include <gslwrap/vector_double.h> namespace gsl { inline vector_float operator*(const matrix_float& m, const vector_float& v) { vector_float y(m.get_rows()); gsl_blas_sgemv(CblasNoTrans, 1.0, m.gslobj(), v.gslobj(), 0.0, y.gslobj()); return y; } inline vector operator*(const matrix& m, const vector& v) { vector y(m.get_rows()); gsl_blas_dgemv(CblasNoTrans, 1.0, m.gslobj(), v.gslobj(), 0.0, y.gslobj()); return y; } } #endif //__matrix_vector_operators_h
{ "alphanum_fraction": 0.7415575465, "avg_line_length": 30.2291666667, "ext": "h", "hexsha": "e72182056cbce3af2089324b84a1d4e76629349e", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-11-27T01:35:33.000Z", "max_forks_repo_forks_event_min_datetime": "2018-11-27T01:35:33.000Z", "max_forks_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_forks_repo_licenses": [ "ECL-2.0", "Apache-2.0" ], "max_forks_repo_name": "entn-at/GlottDNN", "max_forks_repo_path": "src/gslwrap/matrix_vector_operators.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "ECL-2.0", "Apache-2.0" ], "max_issues_repo_name": "entn-at/GlottDNN", "max_issues_repo_path": "src/gslwrap/matrix_vector_operators.h", "max_line_length": 76, "max_stars_count": 4, "max_stars_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_stars_repo_licenses": [ "ECL-2.0", "Apache-2.0" ], "max_stars_repo_name": "entn-at/GlottDNN", "max_stars_repo_path": "src/gslwrap/matrix_vector_operators.h", "max_stars_repo_stars_event_max_datetime": "2022-01-27T01:17:11.000Z", "max_stars_repo_stars_event_min_datetime": "2018-11-27T01:35:30.000Z", "num_tokens": 394, "size": 1451 }
#include <assert.h> #include <cblas.h> #include <complex.h> #include <errno.h> #include <fftw3.h> #include <getopt.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_permutation.h> #include <math.h> #include <omp.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #define C 299792458 #define PI 3.141592654 #define ANSI_COLOR_RED "\x1b[31m" #define ANSI_COLOR_GREEN "\x1b[32m" #define ANSI_COLOR_YELLOW "\x1b[33m" #define ANSI_COLOR_BLUE "\x1b[34m" #define ANSI_COLOR_MAGENTA "\x1b[35m" #define ANSI_COLOR_CYAN "\x1b[36m" #define ANSI_COLOR_RESET "\x1b[0m" #define _MODEL_DEBUG 0 #define MAX_TX 1 #define MAX_RX 1 #define MAX_RIBBON_SIZE 20 #define MAX_SURFACES 20 // if max values exceeded, may cause memory bugs struct simulation { struct environment *env; struct file_reader *fr; }; struct spatial_motion_model { double velocity[3]; double position[3]; }; struct transmission_model { double power_in_dBm; }; struct propagation_model { double distance; }; struct general_node { struct spatial_motion_model *smm; struct transmission_model *tm; int id; }; struct transmitter { struct general_node *gn; double complex baseband_signal; }; struct receiver { struct general_node *gn; double recv_noise_power; double complex rx_signal; struct receiver_ray_ribbon_ll_node *rlln; }; struct perfect_reflector { double unit_normal[3]; double unit_length_normal[3]; double unit_width_normal[3]; double center_point[3]; double length, width; }; struct environment { struct receiver **receivers_array; struct transmitter **transmitters_array; struct perfect_reflector **prarray; struct general_node **node_array; struct ray_ribbon_array **env_paths; struct ray_ribbon_array **tx_paths; double recv_unit_normal[3]; double time; double complex *unit_power_gaussian_noise; double frequency; double wavelength; double delta_time; double end_time; double max_limit; double min_limit; int refresh_time; int awgn_supplied; int time_index; int num_transmitters; int num_receivers; int num_reflectors; int sz_array_tx; int sz_array_rx; int sz_array_gn; int sz_array_pr; // flags bool read_in_nodes; /* should be true by the time TX or RX is read in */ bool node_memory_allocated; bool tx_paths_updated; bool tx_paths_updated_rx_paths_updated; }; struct file_reader { FILE *infile; FILE *outfile; // filenames longer than 999 will be truncated char input_filename[1000]; char output_filename[1000]; }; int id(); struct simulation *init_simulation(); struct spatial_motion_model *init_spatial_motion_model(); struct transmission_model *init_transmission_model(); struct propagation_model *init_propagation_model(); struct general_node *init_general_node(); struct transmitter *init_transmitter(); struct receiver *init_receiver(); struct perfect_reflector *init_perfect_reflector(const double *normal, const double *center_point, const double *length_normal, double length, double width); struct perfect_reflector **init_perfect_reflectorarray(int number); struct environment *init_environment(); int malloc_environment(struct environment *env); void print_vector(const double *db); void print_spatial_motion_model(const struct spatial_motion_model *smm); void print_transmission_model(const struct transmission_model *tm); void print_propagation_model(const struct propagation_model *pm); void print_general_node(const struct general_node *gn); void print_transmitter(const struct transmitter *tx); void print_receiver(const struct receiver *rx); void print_perfect_reflectors(const struct perfect_reflector *pr); void print_environment(const struct environment *env); void print_env_paths(const struct environment *env); void print_tx_paths(const struct environment *env); void destroy_spatial_motion_model(struct spatial_motion_model *smm); void destroy_simulation(struct simulation *sim); void destroy_transmission_model(struct transmission_model *tm); void destroy_propagation_model(struct propagation_model *pm); void destroy_transmitter(struct transmitter *tx); void destroy_receiver(struct receiver *tx); void destroy_environment(struct environment *env); void destroy_file_reader(struct file_reader *fr); void destroy_perfect_reflector(struct perfect_reflector *pr); void destroy_perfect_reflectorarray(struct perfect_reflector **pr_begin); struct file_reader *init_file_reader(int argc, char *argv[]); void cross_product(const double *v1, const double *v2, double *v3); double normalize_unit_vector(double *v1); void diff(const double *v1, const double *v2, double *v3); int find_len(void **ptr); void add_receiver_patch(struct environment *env, int length); void destroy_last_reflector(struct environment *env); double distance(const struct general_node *gn1, const struct general_node *gn2); bool update_environment_from_file_sim(struct simulation *sim); bool handle_request(struct environment *env, FILE *fp, const char *req_type); bool custom_fscanf(FILE *fp, const char *str, void *ptr); // Deprecated bool update_environment_from_file(struct environment *env, FILE *fp);
{ "alphanum_fraction": 0.7193383776, "avg_line_length": 31.2252747253, "ext": "h", "hexsha": "0a5e673f86a133f5428014322250594cd299d79c", "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": "ebf7d4fcf9c4ef94f34f843cbfd25bcae6879f45", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "mainakch/wireless_link", "max_forks_repo_path": "include/models.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ebf7d4fcf9c4ef94f34f843cbfd25bcae6879f45", "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": "mainakch/wireless_link", "max_issues_repo_path": "include/models.h", "max_line_length": 77, "max_stars_count": null, "max_stars_repo_head_hexsha": "ebf7d4fcf9c4ef94f34f843cbfd25bcae6879f45", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "mainakch/wireless_link", "max_stars_repo_path": "include/models.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1212, "size": 5683 }
#pragma once #ifndef _NOGSL #include <gsl/gsl_vector.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_blas.h> #else #include "FakeGSL.h" #endif #include <vector> #include <fstream> #include <iostream> #include "BasicError.h" //#define _NOSNOPT 1 #ifndef _NOSNOPT #include "Snopt.h" #else #include "CustomSolver.h" #endif using namespace std; typedef int (* MAX_SOLVER_DF_TYPE)(integer*, doublereal*, integer*, doublereal*, integer*, doublereal*, char*, integer*); class MaxSolver { integer n; integer neF; integer lenG; integer *iGfun; integer *jGvar; doublereal* G; doublereal *x; doublereal *xlow; doublereal *xupp; doublereal *F; doublereal *Flow; doublereal *Fupp; gsl_vector* result; double objectiveVal; MAX_SOLVER_DF_TYPE df; char* workspace; doublereal obj; doublereal* grad; doublereal* oldx; doublereal stepSize = 0.1; int maxSteps = 5000; public: MaxSolver(integer n_, integer neF_): n(n_), neF(neF_){ lenG = n*neF; iGfun = new integer[lenG]; jGvar = new integer[lenG]; G = new doublereal[lenG]; grad = new doublereal[n]; x = new doublereal[n]; xlow = new doublereal[n]; xupp = new doublereal[n]; F = new doublereal[neF]; Flow = new doublereal[neF]; Fupp = new doublereal[neF]; oldx = new doublereal[n]; result = gsl_vector_alloc(n); } ~MaxSolver() { delete []iGfun; delete []jGvar; delete []x; delete []xlow; delete []xupp; delete []F; delete []Flow; delete []Fupp; } void init(char* workspace, integer nef_, MAX_SOLVER_DF_TYPE _df, doublereal *xlow_, doublereal *xupp_, doublereal *Flow_, doublereal *Fupp_); bool optimize(const gsl_vector* initState, const gsl_vector* initDir, bool suppressPrint = false); gsl_vector* getResults() { return result; } double getObjectiveVal() { return objectiveVal; } bool inLimits(); };
{ "alphanum_fraction": 0.6930157011, "avg_line_length": 18.47, "ext": "h", "hexsha": "a20f58e83b1acece6cab91698796b34e8b5d775d", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z", "max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_forks_repo_licenses": [ "X11" ], "max_forks_repo_name": "natebragg/sketch-backend", "max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/Optimizers/MaxSolver.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z", "max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z", "max_issues_repo_licenses": [ "X11" ], "max_issues_repo_name": "natebragg/sketch-backend", "max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/Optimizers/MaxSolver.h", "max_line_length": 142, "max_stars_count": 17, "max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_stars_repo_licenses": [ "X11" ], "max_stars_repo_name": "natebragg/sketch-backend", "max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/Optimizers/MaxSolver.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z", "num_tokens": 596, "size": 1847 }
// Wrapper of the GSL interpolation functions that lets you define a // 1D function by points and then query points on that function. // // Author: Mark Desnoyer (mdesnoyer@gmail.com) // Date: Oct 2012 #ifndef __INTERPOLATION_H__ #define __INTERPOLATION_H__ #include <vector> #include <gsl/gsl_spline.h> #include <assert.h> #include <algorithm> #include <limits> #include <exception> template <typename T> class SortOrder { public: SortOrder(const std::vector<T>& sortArray) : sortArray_(sortArray) {} bool operator()(int lhs, int rhs) const { return sortArray_[lhs] < sortArray_[rhs]; } private: const std::vector<T>& sortArray_; }; // Classes that inherit this abstract class must intialize spline_ in // their constructors. class Interpolator { public: class out_of_bounds : public std::exception {}; template <typename InputIterator> Interpolator(InputIterator xFirst, InputIterator xLast, InputIterator yFirst, InputIterator yLast) : x_(), y_(), acc_(gsl_interp_accel_alloc()) { std::vector<double> x(xFirst, xLast); std::vector<double> y(yFirst, yLast); std::vector<int> idx; for (unsigned int i = 0u; i < x.size(); ++i) { idx.push_back(i); } assert(x.size() == y.size()); // Get the sorting indicies based on the x matrix std::sort(idx.begin(), idx.end(), SortOrder<double>(x)); // Populate the data in ascending x order skipping equal values double curX = std::numeric_limits<double>::quiet_NaN(); for (unsigned int i = 0u; i < idx.size(); ++i) { if (curX != x[idx[i]]) { x_.push_back(x[idx[i]]); y_.push_back(y[idx[i]]); } curX = x[idx[i]]; } } virtual ~Interpolator(); // Evaluate the interpolation at xi double operator()(double xi) const { if (xi < x_[0] || xi > x_.back()) { throw out_of_bounds(); } return gsl_spline_eval(spline_, xi, acc_); } // Evaluate the derivative at xi double EvalDeriv(double xi) const { if (xi < x_[0] || xi > x_.back()) { throw out_of_bounds(); } return gsl_spline_eval_deriv(spline_, xi, acc_); } double minY() const { return y_.front(); } double maxY() const { return y_.back(); } protected: std::vector<double> x_; std::vector<double> y_; gsl_interp_accel* acc_; gsl_spline* spline_; }; class LinearInterpolator : public Interpolator { public: LinearInterpolator(const std::vector<double>& x, const std::vector<double>& y) : Interpolator(x.begin(), x.end(), y.begin(), y.end()) { InitSpline(); } template <typename InputIterator> LinearInterpolator(InputIterator xFirst, InputIterator xLast, InputIterator yFirst, InputIterator yLast) : Interpolator(xFirst, xLast, yFirst, yLast) { InitSpline(); } virtual ~LinearInterpolator(); private: void InitSpline(); }; class SplineInterpolator : public Interpolator { public: SplineInterpolator(const std::vector<double>& x, const std::vector<double>& y) : Interpolator(x.begin(), x.end(), y.begin(), y.end()) { InitSpline(); } template <typename InputIterator> SplineInterpolator(InputIterator xFirst, InputIterator xLast, InputIterator yFirst, InputIterator yLast) : Interpolator(xFirst, xLast, yFirst, yLast) { InitSpline(); } virtual ~SplineInterpolator(); private: void InitSpline(); }; #endif // __INTERPOLATION_H__
{ "alphanum_fraction": 0.6575819078, "avg_line_length": 25.3602941176, "ext": "h", "hexsha": "5b055debee442f20a98e44212caaa00614bfca5d", "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": "a595ca718d0cda277726894a3105815cef000475", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MRSD2018/reefbot-1", "max_forks_repo_path": "hog_detector/include/hog_detector/interpolation.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "a595ca718d0cda277726894a3105815cef000475", "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": "MRSD2018/reefbot-1", "max_issues_repo_path": "hog_detector/include/hog_detector/interpolation.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "a595ca718d0cda277726894a3105815cef000475", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "MRSD2018/reefbot-1", "max_stars_repo_path": "hog_detector/include/hog_detector/interpolation.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 882, "size": 3449 }
#pragma once #include <memory> #include <random> #include <gsl/gsl_rng.h> namespace EERAModel { /** * @brief Namespace containing objects related to random number generation * * This namespace contains a wrapper interace to existing random number * generation libraries in order for them to be used within all * model functions. */ namespace Random { /** * @class RNGInterface * @brief Abstract interface to a random number generator */ class RNGInterface { public: using Sptr = std::shared_ptr<RNGInterface>; virtual ~RNGInterface() = default; /** * @brief Flat distribution * * Return a random number from a flat distribution * * @param a Lower limit of distribution interval * @param b Upper limit of distribution interval * * @return Random number */ virtual double Flat(double a, double b) = 0; /** * @brief Multinomial distribution * * Return a random number from a multinomial distribution */ virtual void Multinomial(size_t K, unsigned int N, const double p[], unsigned int n[]) = 0; /** * @brief Poisson distribution * * Return a random number from a Poisson distribution * * @param mu Mean of the distribution * * @return Random number */ virtual double Poisson(double mu) = 0; /** * @brief Gamma distribution * * Return a random number from a Gamma distribution * * @param a Gamma a parameter * @param b Gamma b parameter * * @return Random number */ virtual double Gamma(double a, double b) = 0; /** * @brief Beta distribution * * Return a random number from a Beta distribution * * @param a Beta a parameter * @param b Beta b parameter * * @return Random number */ virtual double Beta(double a, double b) = 0; /** * @brief Binomial distribution * * Return a random number from a Binomial distribution * * @param p Binomial p parameter: probability * @param n Binomial n parameter: the population to sample * * @return Random number */ virtual unsigned int Binomial(double p, unsigned int n) = 0; /** * @brief MT19937 generator * * Returns a reference to a std::mt19937 object * * @return mt19937 reference */ virtual std::mt19937& MT19937() = 0; }; /** * @class RNG * @brief Wrapper for the GNU Scientific Library random number generator */ class RNG : public RNGInterface { public: using Sptr = std::shared_ptr<RNG>; /** * @brief Contructor * * Sets up a handle for the underlying GSL and STL random number generator. Seeds the randomiser * with the supplied seed * * @param seed Seed value */ RNG(unsigned long int seed); /** @brief Flat distribution override */ virtual double Flat(double a, double b) override; /** @brief Multinomial distribution override */ virtual void Multinomial(size_t K, unsigned int N, const double p[], unsigned int n[]) override; /** @brief Poisson distribution override */ virtual double Poisson(double mu) override; /** @brief Gamma distribution override */ virtual double Gamma(double a, double b) override; /** @brief Beta distribution override */ virtual double Beta(double a, double b) override; /** @brief Binomial distribution override */ virtual unsigned int Binomial(double p, unsigned int n) override; /** @brief MT19937 override */ virtual std::mt19937& MT19937() override; private: /** * @private * @brief Handle for the GSL random number generator */ gsl_rng* r_; /** * @private * @brief Mersenne twister generator */ std::mt19937 gen_; }; } // namespace Random } // namespace EERAModel
{ "alphanum_fraction": 0.6335483871, "avg_line_length": 24.5253164557, "ext": "h", "hexsha": "846fb17e97e547172e9d40ae2c1874fdeea09e55", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-11-10T15:17:29.000Z", "max_forks_repo_forks_event_min_datetime": "2020-04-23T11:21:31.000Z", "max_forks_repo_head_hexsha": "01caaa76e48005c08c598d75a39d7f37d884e7f8", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "ScottishCovidResponse/Covid19_EERAModel", "max_forks_repo_path": "src/Random.h", "max_issues_count": 13, "max_issues_repo_head_hexsha": "01caaa76e48005c08c598d75a39d7f37d884e7f8", "max_issues_repo_issues_event_max_datetime": "2020-09-17T09:11:02.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-14T14:42:02.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "ScottishCovidResponse/Covid19_EERAModel", "max_issues_repo_path": "src/Random.h", "max_line_length": 100, "max_stars_count": 1, "max_stars_repo_head_hexsha": "01caaa76e48005c08c598d75a39d7f37d884e7f8", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "ScottishCovidResponse/Covid19_EERAModel", "max_stars_repo_path": "src/Random.h", "max_stars_repo_stars_event_max_datetime": "2020-09-25T00:33:15.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-25T00:33:15.000Z", "num_tokens": 928, "size": 3875 }