Search is not available for this dataset
text
string
meta
dict
/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil ; -*- */ /** \file * jitconv "doRef" calculation - a simplified gemm impl. * * This should be correct, and may even be somewhat fast "in general". * Do not expect "fastest" performance. * * libvednn has a more sophisticated GEMM convolution. */ #include "vednn_helper.h" #include "convolution_gemm.h" #include <string.h> #include <stdlib.h> #include <cblas.h> #define LOCAL_FTRACE 1 #if LOCAL_FTRACE #include "conv_test_param.h" // just for FTRACE macros #define LFTRACE_BEGIN(...) FTRACE_BEGIN(__VA_ARGS__) #define LFTRACE_END(...) FTRACE_END(__VA_ARGS__) #define LFTRACE_IF(...) FTRACE_IF(__VA_ARGS__) #else #define LFTRACE_BEGIN(...) do{}while(0) #define LFTRACE_END(...) do{}while(0) #define LFTRACE_IF(...) do{}while(0) #endif // LOCAL_FTRACE // Scratchpad: none -- hardwired to malloc/free im2col buffers // slower, but safer. #define GEMM_PARA_THRESH 32768 // Around Jan. 2022, ncc-3.4.20, SGEMM began to segfault for M==1, // so a workaround writes out the trivial matrix multiply. /// 0 : SGEMM works great /// 1 : safe macros /// 2: dev code (generic) #define SGEMM_M1_SEGFAULTS 1 /// 0 : old code, bias via sgemm (w/ problems) /// 1 : just use cblas_saxpy alternate (simpler and avoids sgemm bug!) #define BIAS_SAXPY 0 #if SGEMM_M1_SEGFAULTS==0 // issues ncc-3.4.20 and M==1 ??? #define SGEMM sgemm_ #define SGEMM_A1B0 sgemm_ #define SGEMM_A1B1K1 sgemm_ #define SGEMM_A1B0t sgemm_ #define SGEMM_A1tB1 sgemm_ #else #define SGEMM sgemm_ // dangerous now - require bug workaround for M=1 #define SGEMM_A1B0 SGEMM_SAFE_A1B0 #define SGEMM_A1B1K1 SGEMM_SAFE_A1B1K1 #define SGEMM_A1B0t SGEMM_SAFE_A1B0t #define SGEMM_A1tB1 SGEMM_SAFE_A1tB1 #endif /// A workaround for SGEMM M==1 segfaults. (circa ncc-3.4.20, Jan 2022) /// For alpha=1, beta=0 (main gemm calculation) #define SGEMM_SAFE_A1B0(TRANSA,TRANSB, N,M,K, ALPHA,A,LDA, B,LDB, BETA,C,LDC) \ do { \ if(*(M) > 1){ \ sgemm_(TRANSA,TRANSB, N,M,K, ALPHA,A,LDA, B,LDB, BETA,C,LDC); \ }else{ \ int const NN = *(N); \ /*int const MM = *(M);*/ \ int const KK = *(K); \ if(*(M) == 1 && *(K) > 1){ /* using just M==1 */ \ _Pragma("omp parallel if(NN * KK > 32768)") /* C99 */ \ for (int n=0; n < (NN); ++n) { \ float acc = 0.0f; \ for (int k=0; k < (KK); ++k) { \ acc += (A)[k * (NN) + n] * (B)[k]; \ } \ (C)[n] = acc; /* M==1 && beta==0.0 : no accumulation into C */ \ } \ }else{ /* M=1, K=1 */ \ _Pragma("omp parallel if((NN) > 32768)") \ for (int n=0; n < *(N); ++n) { \ (C)[n] = (A)[n] * (B)[0]; \ } \ } \ } \ }while(0) /// Backward Data also has alpha=1, beta=0, but B[] is transposed // XXX test with jitconv -T BackwardData #define SGEMM_SAFE_A1B0t(TRANSA,TRANSB, N,M,K, ALPHA,A,LDA, B,LDB, BETA,C,LDC) \ do { \ if(*(M) > 1){ \ sgemm_(TRANSA,TRANSB, N,M,K, ALPHA,A,LDA, B,LDB, BETA,C,LDC); \ }else{ \ /* for M=1, B is K x 1, so vector ignoring the transpose is OK */ \ int const NN = *(N); \ /*int const MM = *(M);*/ \ int const KK = *(K); \ if(*(M) == 1 && *(K) > 1){ /* using just M==1 */ \ _Pragma("omp parallel if(NN * KK > 32768)") /* C99 */ \ for (int n=0; n < (NN); ++n) { \ float acc = 0.0f; \ for (int k=0; k < (KK); ++k) { \ acc += (A)[k * (NN) + n] * (B)[k]; \ } \ (C)[n] = acc; /* M==1 && beta==0.0 : no accumulation into C */ \ } \ }else{ /* M=1, K=1 */ \ _Pragma("omp parallel if((NN) > 32768)") \ for (int n=0; n < *(N); ++n) { \ (C)[n] = (A)[n] * (B)[0]; \ } \ } \ } \ }while(0) /// for BackwardFilter, alpha=1, beta=1 and A is transposed // XXX test with jitconv -T BackwardFilter // try only a single omp || ? // needs testing of ALL impls (update jitconv testBackwardFilter!!!) #define SGEMM_SAFE_A1tB1_0(TRANSA,TRANSB, N,M,K, ALPHA,A,LDA, B,LDB, BETA,C,LDC) \ do { \ /*printf(" A1tB1 N=%d M=%d K=%d\n",*(N),*(M),*(K)); fflush(stdout);*/ \ if(*(M) > 1){ \ sgemm_(TRANSA,TRANSB, N,M,K, ALPHA,A,LDA, B,LDB, BETA,C,LDC); \ }else{ \ /* for M=1, A is N x K, so need A transpose wrt. Forward impl */ \ int const NN = *(N); \ int const KK = *(K); \ int const NNKK = NN*KK; \ /* M==1, any K */ \ _Pragma("omp parallel if(NNKK > 32768)") /* C99 */ \ for (int n=0; n < (NN); ++n) { \ float acc = 0.0f; \ for (int k=0; k < (KK); ++k) { \ acc += (A)[n * (KK) + k] * (B)[k]; \ } \ (C)[n] += acc; /* beta=1 accumulation into C */ \ } \ } \ }while(0) #define SGEMM_SAFE_A1tB1(TRANSA,TRANSB, N,M,K, ALPHA,A,LDA, B,LDB, BETA,C,LDC) \ do { \ /*printf(" A1tB1 N=%d M=%d K=%d\n",*(N),*(M),*(K)); fflush(stdout);*/ \ if(*(M) > 1){ \ sgemm_(TRANSA,TRANSB, N,M,K, ALPHA,A,LDA, B,LDB, BETA,C,LDC); \ }else{ \ /* for M=1, A is N x K, so need A transpose wrt. Forward impl */ \ int const NN = *(N); \ int const KK = *(K); \ if(*(M) == 1 && *(K) > 1){ /* using just M==1 */ \ /*_Pragma("omp parallel if(NN * KK > 32768)")*/ /* C99 */ \ for (int n=0; n < (NN); ++n) { \ float acc = 0.0f; \ for (int k=0; k < (KK); ++k) { \ acc += (A)[n * (KK) + k] * (B)[k]; \ } \ (C)[n] += acc; /* beta=1 accumulation into C */ \ } \ }else{ /* M=1, K=1 */ \ /*_Pragma("omp parallel if((NN) > 32768)")*/ \ for (int n=0; n < (NN); ++n) { \ (C)[n] += (A)[n] * (B)[0]; /* beta=1 accum */ \ } \ } \ } \ }while(0) // using M==1 and K==1 // here A[N] is 1.0 /// workaround for M=1 bias segfault. /// Here K=1, alpha=1, beta=1, \b and A[] is all-1.0 (bias accumulation) #define SGEMM_SAFE_A1B1K1(TRANSA,TRANSB, N,M,K, ALPHA,A,LDA, B,LDB, BETA,C,LDC) \ do { \ if(1 && *(M) > 1) /* always elide? */ \ { \ sgemm_(TRANSA,TRANSB, N,M,K, ALPHA,A,LDA, B,LDB, BETA,C,LDC); \ }else{ \ int const MN = *(M) * *(N); \ float const B_0 = *(B);/* (B)[0] */ \ /* wrong output if try to parallelize? */ \ /* _Pragma("omp parallel if(MN > 32768)") */ \ for (int mn=0; mn < MN; ++mn) { \ (C)[mn] += B_0; \ } \ } \ }while(0) #if 0 #define DBG(...) do{printf(__VA_ARGS__);fflush(stdout);}while(0) #else #define DBG(...) #endif #if 1 void sgemm_(char *TRANSA, char *TRANSB, int *M, int *N, int *K, float *ALPHA, float *A, int *LDA, float *B, int *LDB, float *BETA, float *C, int *LDC ) ; //void cblas_saxpy(const int N, const float alpha, const float *X, // const int incX, float *Y, const int incY); #endif static char TRANS = 'T'; static char NOTRANS = 'N'; static float FONE = 1.0f; static float FZERO = 0.0f; static int IONE = 1; /* ----------------------------------------------------------------------- */ static inline int is_a_ge_zero_and_a_lt_b(int a, int b) { //return (unsigned)a < (unsigned)b; return a>=0 && a<b; // for ncc auto vectorization, this is better } static void #if 0 im2col_cpu(const float * restrict data_im, const int channels, const int height, const int width, const int kernel_h, const int kernel_w, const int output_h, const int output_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int dilation_h, const int dilation_w, float * restrict data_col) #else im2col_cpu(const float * data_im, const int channels, const int height, const int width, const int kernel_h, const int kernel_w, const int output_h, const int output_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int dilation_h, const int dilation_w, float * data_col) #endif { LFTRACE_BEGIN("im2col_cpu"); #if 0 const int output_h = (height + 2 * pad_h - (dilation_h * (kernel_h - 1) + 1)) / stride_h + 1; const int output_w = (width + 2 * pad_w - (dilation_w * (kernel_w - 1) + 1)) / stride_w + 1; #endif const int channel_size = height * width; int channel; if (0){ // Note: alloc is for ic * ih * kw, but probably only need (ic/g) * kh * kw here? DBG("im2col_cpu _alloc needs %llu floats\n",(long long)channels*channel_size); for(size_t i=0; i<(size_t)channels*(size_t)channel_size; ++i){ data_col[i] = 0.0f; } DBG("data_col / pColBuf accessible"); } //#pragma omp parallel for if(channels>=3) for (channel = 0 ; channel < channels; channel++) { // inChannel //printf(" i2c c%d/%d",channel,channels); fflush(stdout); int kernel_row, kernel_col, output_rows, output_cols, output_col; int inOffset = channel * channel_size; int outOffset = channel * output_h * output_w * kernel_h * kernel_w; for (kernel_row = 0; kernel_row < kernel_h; kernel_row++) { // kernHeight for (kernel_col = 0; kernel_col < kernel_w; kernel_col++) { // kernWidth int input_row = -pad_h + kernel_row * dilation_h; for (output_rows = output_h; output_rows; output_rows--) { // outHeight if (!is_a_ge_zero_and_a_lt_b(input_row, height)) { for (output_cols = output_w; output_cols; output_cols--) { // *(data_col++) = 0; data_col[outOffset++] = 0.f; } } else { int input_col = -pad_w + kernel_col * dilation_w; // following still bombed //#pragma _NEC novector for (output_col = output_w; output_col; output_col--) { // outWidth #if 1 // newer data_col[outOffset++] //*(data_col++) = (is_a_ge_zero_and_a_lt_b(input_col, width) ? data_im[inOffset + input_row * width + input_col] : 0.f); #else // older if (outOffset < 0 || outOffset >= channels*kernel_h*kernel_w*output_h*output_w){ printf("ERROR: outOffset"); fflush(stdout); exit(-1); } if (is_a_ge_zero_and_a_lt_b(input_col, width)) { // *(data_col++) = data_im[input_row * width + input_col]; data_col[outOffset] = data_im[inOffset + input_row * width + input_col]; } else { // *(data_col++) = 0; data_col[outOffset] = 0; } ++outOffset; #endif input_col += stride_w; } } input_row += stride_h; } } } } LFTRACE_END("im2col_cpu"); } static void col2im_cpu( const float* data_col, const int channels, const int height, const int width, const int kernel_h, const int kernel_w, const int output_h, const int output_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int dilation_h, const int dilation_w, float* data_im) { LFTRACE_BEGIN("col2im_cpu"); memset(data_im, 0, sizeof(float)*height*width*channels) ; #if 0 const int output_h = (height + 2 * pad_h - (dilation_h * (kernel_h - 1) + 1)) / stride_h + 1; const int output_w = (width + 2 * pad_w - (dilation_w * (kernel_w - 1) + 1)) / stride_w + 1; #endif const int channel_size = height * width; int channel; #pragma omp parallel for if(channels>=3) for (channel = 0 ; channel < channels; channel++) { // inChannel int kernel_row, kernel_col, output_rows, output_cols, output_col; int inOffset = channel * channel_size; int outOffset = channel * output_h * output_w * kernel_h * kernel_w; for (kernel_row = 0; kernel_row < kernel_h; kernel_row++) { // kernHeight for (kernel_col = 0; kernel_col < kernel_w; kernel_col++) { // kernWidth int input_row = -pad_h + kernel_row * dilation_h; for (output_rows = output_h; output_rows; output_rows--) { // outHeight if (!is_a_ge_zero_and_a_lt_b(input_row, height)) { for (output_cols = output_w; output_cols; output_cols--) { data_col[outOffset++] ; } } else { int input_col = -pad_w + kernel_col * dilation_w; for (output_col = output_w; output_col; output_col--) { // outWidth if (is_a_ge_zero_and_a_lt_b(input_col, width)) { data_im[inOffset + input_row * width + input_col] += data_col[outOffset++] ; } else { outOffset++ ; } input_col += stride_w; } } input_row += stride_h; } } } } LFTRACE_END("col2im_cpu"); } // pOne is oh*ow of 1.0f // pColBuff is scratch of ic*kw*kh * ow*oh * iw*ih (huge, in this version) see conv_test_param.c vednnError_t convolution_forward_gemm( const vednnTensorParam_t * restrict pParamIn, const void * restrict pDataIn, const vednnFilterParam_t * restrict pParamKernel, const void * restrict pDataKernel, const vednnBiasParam_t * restrict pParamBias, const void * restrict pDataBias, const vednnTensorParam_t * restrict pParamOut, void * restrict pDataOut, //const float * restrict pOne, float * restrict pColBuff, const float * pOne, float * pColBuff, const vednnConvolutionParam_t * restrict pParamConv ) { LFTRACE_BEGIN("convolution_forward_gemm"); int batch = pParamIn->batch; int inChannel = pParamIn->channel; int inWidth = pParamIn->width; int inHeight = pParamIn->height; int outChannel = pParamOut->channel; int outWidth = pParamOut->width; int outHeight = pParamOut->height; int kernWidth = pParamKernel->width; int kernHeight = pParamKernel->height; int group = pParamConv->group; int strideWidth = pParamConv->strideWidth;; int strideHeight = pParamConv->strideHeight; int padWidth = pParamConv->padWidth; int padHeight = pParamConv->padHeight; int dilationWidth = pParamConv->dilationWidth; int dilationHeight = pParamConv->dilationHeight; int inChannelGroup = inChannel / group; // pParamKernel->inChannel int outChannelGroup = outChannel / group; // pParamKernel->outChannel int no_im2col = (kernWidth == 1 && kernHeight == 1 && strideWidth == 1 && strideHeight == 1 && padWidth == 0 && padHeight == 0); if (0){ printf("mb=%d g=%d ic=%d ic/g=%d noi2c=%d", batch,group,inChannel,inChannelGroup, no_im2col); fflush(stdout); float const* pk = (float const*)(pDataKernel); // assume float (debug) XXX int const ksz = group * outChannelGroup * inChannelGroup * kernHeight * kernWidth; size_t const ksz2 = getKernelSize(pParamKernel) * pParamConv->group; if (ksz != ksz2) { printf("ksz %d != ksz2 %d\n"); } for(int i=0; i<ksz; ++i){ if (isnan(pk[i])) { printf("generateRandomData --> nans!\n"); printf("ksz=%d i=%d\n"); exit(-1); } if (pk[i] < -5.0 || pk[i] > +5.0){ printf("generateRandomData --> outside [-5.0,5.0]\n"); printf("ksz=%d i=%d\n"); exit(-1); } } printf("input pDataKernel[0..%d - 1] looks good\n",ksz); printf("input pDataKernel[0..%lu - 1] looks good\n",(long unsigned)ksz2); } float * transformed_filter = NULL ; if( pParamKernel->layout == VEDNN_FILTER_LAYOUT_HWCN ) { // only support group=1 if (group!=1){ printf("Unsupported ref calc: HWCN wants group==1"); exit(-1); //return VEDNN_ERROR_INVALID_PARAM; } const int N = outChannel ; const int C = inChannel ; const int H = kernHeight ; const int W = kernWidth ; float * filter = (float *) pDataKernel ; transformed_filter = (float *) malloc(sizeof(float)*N*C*H*W) ; #pragma omp parallel for for(int n=0; n<N ; n++) { for(int c=0; c<C ; c++) { for(int hw=0; hw<H*W ; hw++) { transformed_filter[((n*C+c)*H)*W+hw] = filter[((hw)*C+c)*N+n] ; } } } } const float * restrict pIn = pDataIn; const float * restrict pBias = pDataBias; const float * restrict pKernel = transformed_filter == NULL ? pDataKernel : transformed_filter ; float * restrict pOut = pDataOut; for (int n = 0; n < batch; n++) { // this->num_ int inBatchOffset = n * inChannel * inWidth * inHeight; int outBatchOffset = n * outChannel * outWidth * outHeight; for (int g = 0; g < group; g++) { int inGroupOffset = g * inChannelGroup * inHeight * inWidth; int outGroupOffset = g * outChannelGroup * outHeight * outWidth; int kernGroupOffset = g * outChannelGroup * inChannelGroup * kernHeight * kernWidth; int biasGroupOffset = g * outChannelGroup; int inOffset = inBatchOffset + inGroupOffset; int outOffset = outBatchOffset + outGroupOffset; if (no_im2col) { int M = outChannelGroup; int N = outWidth * outHeight; int K = inChannelGroup; int LDA = inWidth * inHeight; //printf(" M=%d N=%d K=%d ",M,N,K); #if SGEMM_M1_SEGFAULTS==0 // issues ncc-3.4.20 and M==1 ??? SGEMM(&NOTRANS, &NOTRANS, &N, &M, &K, &FONE, (float *) &pIn[inOffset], &LDA, (float *) &pKernel[kernGroupOffset], &K, &FZERO, &pOut[outOffset], &N); #elif SGEMM_M1_SEGFAULTS==1 // issues ncc-3.4.20 and M==1 ??? SGEMM_A1B0(&NOTRANS, &NOTRANS, &N, &M, &K, &FONE, (float *) &pIn[inOffset], &LDA, (float *) &pKernel[kernGroupOffset], &K, &FZERO, &pOut[outOffset], &N); #else // ncc-3.4.20 fixup... Here I show general equivalent for the SGEMM... if (M>1) { // || K>1) { SGEMM(&NOTRANS, &NOTRANS, &N, &M, &K, &FONE, (float *) &pIn[inOffset], &LDA, // LDA=N for no_im2col (float *) &pKernel[kernGroupOffset], &K, // LDB=K for no_im2col &FZERO, &pOut[outOffset], &N); }else{ // M==1 has some BLAS segv !!! just write it out for now... // At -O3 and -O4, ncc should have -fassociative-math -fmatrix-multiply // and should emit matrix-multiply code for these // consulting sgemm docs // 3rd dim is the summation index float const* A = (float const*)&pIn[inOffset]; // size N x K float const* B = (float const*)&pKernel[kernGroupOffset]; // size K x M float * C = &pOut[outOffset]; // size N x M #if 0 // generic, long-hand matrix multiply if (M>1) { // actually this is NOT quite right yet :( for (int n=0; n<N; n++) { for (int m=0; m<M; m++) { C[m*N + n] = 0.0f; } } for (int n=0; n<N; n++) { for (int m=0; m<M; m++) { float acc = 0.0f; for (int k=0; k<K; k++) { acc += A[k*N + n] * B[m*K + k]; } C[m*N + n] += acc; // beta=0 } } }else #endif #if 1 if(M==1 && K>1){ // using just M==1 #pragma omp parallel if(N*K>GEMM_PARA_THRESH) for (int n=0; n<N; n++) { float acc = 0.0f; for (int k=0; k<K; k++) { acc += A[k*N+n] * B[k]; } C[n] = acc; // beta=0, no accumulation into C } }else #endif { // using M==1 and K==1 float b0 = B[0]; #pragma omp parallel if(N*K>GEMM_PARA_THRESH) for (int n=0; n<N; n++) { C[n] = A[n] * b0; } } } #endif if (pBias) { //printf("noi2c pBias M=%d N=%d K=%d ", M,N,K); #if SGEMM_M1_SEGFAULTS==0 // issues ncc-3.4.20 and M==1 ??? SGEMM(&NOTRANS, &NOTRANS, &N, &M, &IONE, &FONE, (float *) pOne, &N, (float *) &pBias[biasGroupOffset], &IONE, &FONE, &pOut[outOffset], &N); #elif SGEMM_M1_SEGFAULTS==1 // issues ncc-3.4.20 and M==1 ??? #if BIAS_SAXPY==0 SGEMM_A1B1K1(&NOTRANS, &NOTRANS, &N, &M, &IONE, &FONE, (float *) pOne, &N, // N x 1 (float *) &pBias[biasGroupOffset], &IONE, // 1 x M &FONE, &pOut[outOffset], &N); // N x M #else // note that this might be formulated as a // SAXPY( N=MN, // ALPHA=1.0, // X=&pBias[biasGroupOffset], // INCX=0, /* <-- "add constant" */ // Y=&pOut[outOffset], /* add to this */ // INCY=1 // ) // Unfortunately, this only handles for M=1 if (M>1) { SGEMM(&NOTRANS, &NOTRANS, &N, &M, &IONE, &FONE, (float *) pOne, &N, (float *) &pBias[biasGroupOffset], &IONE, &FONE, &pOut[outOffset], &N); }else{ //printf(" saxpy M=%d N=%d\n", M,N); cblas_saxpy( N, 1.0, &pBias[biasGroupOffset], 0, &pOut[outOffset], 1); } #endif #elif 0 // debug { // M==1 has some BLAS segv !!! just write it out for now... // K=1 summation index is a huge simplification // We might want to never fully call the SGEMM! //float const* A = (float const*)pOne; // size N x K float const* B = (float const*)&pBias[biasGroupOffset]; // size K x M float * C = &pOut[outOffset]; // size N x M if (1) { // further simplificcation only elides 1 scalar multiply //for (int n=0; n<N; n++) for (int m=0; m<M; m++) C[m*N + n] = 0.0f; #if 0 // version 0, all loops before simplification printf("x7"); int const K = 1; for (int n=0; n<N; n++) { for (int m=0; m<M; m++) { float acc = 0.0f; for (int k=0; k<K; k++) { acc += 1.0/* A[k*N + n] */ * B[m*K + k]; } C[m*N + n] += acc; // beta=0 } } #elif 0 // K=1 is a drastic simplification printf("x8"); for (int m=0; m<M; ++m) { for (int n=0; n<N; ++n) { C[m*N + n] += B[0]; // beta=0 } } #else // not working with omp parllel DBG("x9"); int const MN = M * N; //#pragma omp parallel if(MN > GEMM_PARA_THRESH) /* this cause wrong output */ for (int mn=0; mn < MN; ++mn) { C[mn] += B[0]; // beta=0 } } } #endif #else // dev code, summarized // maybe it's faster to always elide the SGEMM? if (M>1) { SGEMM(&NOTRANS, &NOTRANS, &N, &M, &IONE, &FONE, (float *) pOne, &N, (float *) &pBias[biasGroupOffset], &IONE, &FONE, &pOut[outOffset], &N); }else{ // workaround for M=1 segfault circa ncc 3.4.20 // using M==1 and K==1 // here A[N] is 1.0 float b0 = pBias[biasGroupOffset+0]; // B[0] int const MN = M * N; /* _Pragma("omp parallel if(MN > 32768)") //wrong output? */ for (int mn=0; mn < MN; ++mn) { pOut[outOffset+mn] += b0; // C[n] } } #endif }// if pBias } else { int M = outChannelGroup; int N = outWidth * outHeight; int K = inChannelGroup * kernWidth * kernHeight; im2col_cpu(&pIn[inOffset], inChannelGroup, inHeight, inWidth, kernHeight, kernWidth, outHeight, outWidth, padHeight, padWidth, strideHeight, strideWidth, dilationHeight, dilationWidth, pColBuff); #if SGEMM_M1_SEGFAULTS==0 // issues ncc-3.4.20 and M==1 ??? SGEMM(&NOTRANS, &NOTRANS, &N, &M, &K, &FONE, pColBuff, &N, (float *)&pKernel[kernGroupOffset], &K, &FZERO, &pOut[outOffset], &N); // segfault if M==1, at least w/ ncc 3.4.20 etc. #elif SGEMM_M1_SEGFAULTS==1 // issues ncc-3.4.20 and M==1 ??? SGEMM_A1B0(&NOTRANS, &NOTRANS, &N, &M, &K, &FONE, pColBuff, &N, (float *)&pKernel[kernGroupOffset], &K, &FZERO, &pOut[outOffset], &N); #else if (M>1) { SGEMM(&NOTRANS, &NOTRANS, &N, &M, &K, &FONE, pColBuff, &N, // N x K (float *)&pKernel[kernGroupOffset], &K, // K x M &FZERO, &pOut[outOffset], &N); // N x M }else{ // M==1 has some BLAS segv !!! just write it out for now... // At -O3 and -O4, ncc should have -fassociative-math -fmatrix-multiply // and should emit matrix-multiply code for these float const* A = pColBuff; // osz x icg*ksz (?) float const* B = (float const*)&pKernel[kernGroupOffset]; // icg*ksz x ocg float * C = &pOut[outOffset]; // osz x ocg (?) #if 0 if (M>1) { for (int n=0; n<N; n++) { for (int m=0; m<M; m++) { C[m*N + n] = 0.0f; } } for (int n=0; n<N; n++) { for (int m=0; m<M; m++) { float acc = 0.0f; for (int k=0; k<K; k++) { acc += A[k*N + n] * B[m*K + k]; } C[m*N + n] += acc; // beta=0, no accumulation into C } } }else #endif { // M==1 for (int n=0; n<N; n++) { float acc = 0.0f; for (int k=0; k<K; k++) { acc += A[k*N+n] * B[k]; } C[n] = acc; } } } #endif //printf(" back from SGEMM..."); fflush(stdout); if (pBias) { //printf("i2c bias...\n"); fflush(stdout); #if SGEMM_M1_SEGFAULTS==0 // issues ncc-3.4.20 and M==1 ??? SGEMM(&NOTRANS, &NOTRANS, &N, &M, &IONE, &FONE, (float *)pOne, &N, (float *) &pBias[biasGroupOffset], &IONE, &FONE, &pOut[outOffset], &N); #elif SGEMM_M1_SEGFAULTS==1 // issues ncc-3.4.20 and M==1 ??? #if 1 //BIAS_SAXPY==0 SGEMM_A1B1K1(&NOTRANS, &NOTRANS, &N, &M, &IONE, &FONE, (float *)pOne, &N, // size N x 1 (float *) &pBias[biasGroupOffset], &IONE, // size 1 x M &FONE, &pOut[outOffset], &N); // size N x M #else cblas_saxpy( M*N, 1.0, &pBias[biasGroupOffset], 0, &pOut[outOffset], 1); #endif #else if (M>1) { SGEMM(&NOTRANS, &NOTRANS, &N, &M, &IONE, &FONE, (float *) pOne, &N, (float *) &pBias[biasGroupOffset], &IONE, &FONE, &pOut[outOffset], &N); }else{ // workaround for M=1 segfault circa ncc 3.4.20 // using M==1 and K==1 // here A[N] is 1.0 float b0 = pBias[biasGroupOffset+0]; // B[0] for (int n=0; n<N; n++) { pOut[outOffset+n] += b0; // C[n] } } #endif } } // no_im2col? } // group } // batch if( transformed_filter != NULL ) free(transformed_filter) ; LFTRACE_END("convolution_forward_gemm"); return VEDNN_SUCCESS; } vednnError_t convolution_backward_data_gemm( const vednnTensorParam_t * restrict pParamGradOut, const void * restrict pDataGradOut, const vednnFilterParam_t * restrict pParamKernel, const void * restrict pDataKernel, const vednnTensorParam_t * restrict pParamGradIn, void * restrict pDataGradIn, float * restrict pColBuff, const vednnConvolutionParam_t * restrict pParamConv ) { LFTRACE_BEGIN("convolution_backward_data_gemm"); int n, g; int batch = pParamGradOut->batch; int gOutChannel = pParamGradOut->channel; int gOutWidth = pParamGradOut->width; int gOutHeight = pParamGradOut->height; int gInChannel = pParamGradIn->channel; int gInWidth = pParamGradIn->width; int gInHeight = pParamGradIn->height; int kernWidth = pParamKernel->width; int kernHeight = pParamKernel->height; int group = pParamConv->group; int strideWidth = pParamConv->strideWidth;; int strideHeight = pParamConv->strideHeight; int padWidth = pParamConv->padWidth; int padHeight = pParamConv->padHeight; int dilationWidth = pParamConv->dilationWidth; int dilationHeight = pParamConv->dilationHeight; int gOutChannelGroup = gOutChannel / group; int gInChannelGroup = gInChannel / group; int no_im2col = (kernWidth == 1 && kernHeight == 1 && strideWidth == 1 && strideHeight == 1 && padWidth == 0 && padHeight == 0); float * transformed_filter = NULL ; if( pParamKernel->layout == VEDNN_FILTER_LAYOUT_HWCN ) { // only support group=1 const int N = gOutChannel ; const int C = gInChannel ; const int H = kernHeight ; const int W = kernWidth ; float * filter = (float *) pDataKernel ; transformed_filter = (float *) malloc(sizeof(float)*N*C*H*W) ; #pragma omp parallel for for(int n=0; n<N ; n++) { for(int c=0; c<C ; c++) { for(int hw=0; hw<H*W ; hw++) { transformed_filter[((n*C+c)*H)*W+hw] = filter[((hw)*C+c)*N+n] ; } } } } const float * restrict pGradOut = pDataGradOut; const float * restrict pKernel = transformed_filter == NULL ? pDataKernel : transformed_filter ; float * restrict pGradIn = pDataGradIn; for (n = 0; n < batch; n++) { // this->num_ int gOutBatchOffset = n * gOutChannel * gOutWidth * gOutHeight; int gInBatchOffset = n * gInChannel * gInWidth * gInHeight; for (g = 0; g < group; g++) { int gOutGroupOffset = g * gOutChannelGroup * gOutHeight * gOutWidth; int gInGroupOffset = g * gInChannelGroup * gInHeight * gInWidth; int kernGroupOffset = g * gInChannelGroup * gOutChannelGroup * kernHeight * kernWidth; int gOutOffset = gOutBatchOffset + gOutGroupOffset; int gInOffset = gInBatchOffset + gInGroupOffset; int M = gInChannelGroup * kernWidth * kernHeight; int N = gOutWidth * gOutHeight; int K = gOutChannelGroup; if( no_im2col ) { SGEMM_A1B0t(&NOTRANS, &TRANS, &N, &M, &K, &FONE, (float *) &pGradOut[gOutOffset], &N, // N x K (float *) &pKernel[kernGroupOffset], &M, // M x K (trans!) &FZERO, &pGradIn[gInOffset], &N); // N x M } else { SGEMM_A1B0t(&NOTRANS, &TRANS, &N, &M, &K, &FONE, (float *) &pGradOut[gOutOffset], &N, (float *) &pKernel[kernGroupOffset], &M, &FZERO, pColBuff, &N); col2im_cpu(pColBuff, gInChannelGroup, gInHeight, gInWidth, kernHeight, kernWidth, gOutHeight, gOutWidth, padHeight, padWidth, strideHeight, strideWidth, dilationHeight, dilationWidth, &pGradIn[gInOffset]); } } // group } // batch if( transformed_filter != NULL ) free(transformed_filter) ; LFTRACE_END("convolution_backward_data_gemm"); return VEDNN_SUCCESS; } vednnError_t convolution_backward_filter_gemm( const vednnTensorParam_t * restrict pParamIn, const void * restrict pDataIn, const vednnTensorParam_t * restrict pParamGradOut, const void * restrict pDataGradOut, const vednnFilterParam_t * restrict pParamGradKernel, void * restrict pDataGradKernel, float * restrict pColBuff, const vednnConvolutionParam_t * restrict pParamConv ) { LFTRACE_BEGIN("convolution_backward_filter_gemm"); int n, g; int batch = pParamIn->batch; int inChannel = pParamIn->channel; int inWidth = pParamIn->width; int inHeight = pParamIn->height; int outChannel = pParamGradOut->channel; int outWidth = pParamGradOut->width; int outHeight = pParamGradOut->height; int kernWidth = pParamGradKernel->width; int kernHeight = pParamGradKernel->height; int group = pParamConv->group; int strideWidth = pParamConv->strideWidth;; int strideHeight = pParamConv->strideHeight; int padWidth = pParamConv->padWidth; int padHeight = pParamConv->padHeight; int dilationWidth = pParamConv->dilationWidth; int dilationHeight = pParamConv->dilationHeight; int inChannelGroup = inChannel / group; // pParamKernel->inChannel int outChannelGroup = outChannel / group; // pParamKernel->outChannel int no_im2col = (kernWidth == 1 && kernHeight == 1 && strideWidth == 1 && strideHeight == 1 && padWidth == 0 && padHeight == 0); float * transformed_filter = NULL ; if( pParamGradKernel->layout == VEDNN_FILTER_LAYOUT_HWCN ) { // only support group=1 const int N = outChannel ; const int C = inChannel ; const int H = kernHeight ; const int W = kernWidth ; transformed_filter = (float *) malloc(sizeof(float)*N*C*H*W) ; #pragma omp parallel for for(int i=0; i<N*C*H*W; i++) transformed_filter[i] = 0.f ; } const float * restrict pIn = pDataIn; const float * restrict pOut = pDataGradOut; float * restrict pKernel = transformed_filter == NULL ? pDataGradKernel : transformed_filter ; for (n = 0; n < batch; n++) { // this->num_ int inBatchOffset = n * inChannel * inWidth * inHeight; int outBatchOffset = n * outChannel * outWidth * outHeight; for (g = 0; g < group; g++) { int inGroupOffset = g * inChannelGroup * inHeight * inWidth; int outGroupOffset = g * outChannelGroup * outHeight * outWidth; int kernGroupOffset = g * outChannelGroup * inChannelGroup * kernHeight * kernWidth; int inOffset = inBatchOffset + inGroupOffset; int outOffset = outBatchOffset + outGroupOffset; if( no_im2col ) { int M = outChannelGroup; int N = inChannelGroup * kernWidth * kernHeight; int K = outWidth * outHeight; SGEMM_A1tB1(&TRANS, &NOTRANS, &N, &M, &K, &FONE, (float*)&pIn[inOffset], &K, (float*)&pOut[outOffset], &K, &FONE, &pKernel[kernGroupOffset], &N); } else { im2col_cpu(&pIn[inOffset], inChannelGroup, inHeight, inWidth, kernHeight, kernWidth, outHeight, outWidth, padHeight, padWidth, strideHeight, strideWidth, dilationHeight, dilationWidth, pColBuff); int M = outChannelGroup; int N = inChannelGroup * kernWidth * kernHeight; int K = outWidth * outHeight; SGEMM_A1tB1(&TRANS, &NOTRANS, &N, &M, &K, &FONE, pColBuff, &K, (float*)&pOut[outOffset], &K, &FONE, &pKernel[kernGroupOffset], &N); } } // group } // batch if( transformed_filter != NULL ) { const int N = outChannel ; const int C = inChannel ; const int H = kernHeight ; const int W = kernWidth ; float * filter = (float *) pDataGradKernel ; #pragma omp parallel for for(int n=0; n<N ; n++) { for(int c=0; c<C ; c++) { for(int hw=0; hw<H*W ; hw++) { filter[((hw)*C+c)*N+n] += transformed_filter[((n*C+c)*H)*W+hw] ; } } } free(transformed_filter) ; } LFTRACE_END("convolution_backward_filter_gemm"); return VEDNN_SUCCESS; } // vim: et ts=2 sw=2 cindent cino=^0,=0,l0,\:0,N-s syntax=cpp.doxygen
{ "alphanum_fraction": 0.5502808275, "avg_line_length": 37.3744725738, "ext": "c", "hexsha": "633b83a67add671583f8d332a2fc724b7ec86918", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-10-18T11:30:13.000Z", "max_forks_repo_forks_event_min_datetime": "2019-10-18T11:30:13.000Z", "max_forks_repo_head_hexsha": "f1ae59587d49ff19a829fccdbf9160989ff205ed", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "sx-aurora-dev/vednn", "max_forks_repo_path": "test/convolution_gemm.c", "max_issues_count": 3, "max_issues_repo_head_hexsha": "f1ae59587d49ff19a829fccdbf9160989ff205ed", "max_issues_repo_issues_event_max_datetime": "2020-10-28T15:42:57.000Z", "max_issues_repo_issues_event_min_datetime": "2019-06-07T05:42:03.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "sx-aurora-dev/vednn", "max_issues_repo_path": "test/convolution_gemm.c", "max_line_length": 130, "max_stars_count": 2, "max_stars_repo_head_hexsha": "f1ae59587d49ff19a829fccdbf9160989ff205ed", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "sx-aurora-dev/vednn", "max_stars_repo_path": "test/convolution_gemm.c", "max_stars_repo_stars_event_max_datetime": "2022-02-12T03:13:07.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-28T22:13:52.000Z", "num_tokens": 10968, "size": 35431 }
#include "indexes/utils/Utils.h" #include <doctest/doctest.h> #include <gsl/span> #include <inttypes.h> #include <limits> #include <map> #include <random> #include <string> #include <thread> #include <vector> enum class ConcurrentMapTestWorkload { WL_CONTENTED, WL_CONTENTED_SWAP, WL_RANDOM, }; enum class LookupType { LT_DEFAULT, LT_CUSTOM, }; std::vector<int64_t> generateUniqueValues(int num_threads, int perthread_count, ConcurrentMapTestWorkload workload); template <typename MapType> void MixedMapTest() { indexes::utils::ThreadRegistry::RegisterThread(); MapType map; int num_operations = 1024 * 1024; int cardinality = num_operations * 0.1; constexpr auto INSERT_OP = 1; constexpr auto LOOKUP_OP = 2; constexpr auto DELETE_OP = 3; std::random_device r; std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()}; std::mt19937 rnd(seed); std::uniform_int_distribution<int> key_dist{1, cardinality}; std::uniform_int_distribution<int> val_dist; std::uniform_int_distribution<> op_dist{INSERT_OP, DELETE_OP}; std::map<int, int> key_values; for (int i = 0; i < num_operations; i++) { const auto key = key_dist(rnd); const auto op = op_dist(rnd); int val; switch (op) { case INSERT_OP: { val = val_dist(rnd); if (key_values.count(key)) { REQUIRE(*map.Search(key) == key_values[key]); REQUIRE(*map.Update(key, val) == key_values[key]); } else { REQUIRE(map.Insert(key, val) == true); REQUIRE(*map.Search(key) == val); } key_values[key] = val; break; } case LOOKUP_OP: { if (key_values.count(key)) REQUIRE(*map.Search(key) == key_values[key]); else REQUIRE(map.Search(key).has_value() == false); break; } case DELETE_OP: { if (key_values.count(key)) { REQUIRE(*map.Search(key) == key_values[key]); REQUIRE(*map.Delete(key) == key_values[key]); key_values.erase(key); } else { REQUIRE(map.Delete(key).has_value() == false); } break; } default: continue; } } REQUIRE(map.size() == key_values.size()); for (const auto &kv : key_values) { REQUIRE(*map.Delete(kv.first) == kv.second); } REQUIRE(map.size() == 0); indexes::utils::ThreadRegistry::UnregisterThread(); } template <typename MapType, LookupType LkType, typename LookupOp> static void lookup_worker(MapType &map, gsl::span<const int64_t> vals, int64_t min_val, int64_t max_val, const LookupOp &op) { indexes::utils::ThreadRegistry::RegisterThread(); if constexpr (LkType == LookupType::LT_DEFAULT) { (void)op; for (auto val : vals) { map.Search(val); } } else { op(map, min_val, max_val, vals.size()); } indexes::utils::ThreadRegistry::UnregisterThread(); } template <typename MapType> static void insert_worker(MapType &map, gsl::span<const int64_t> vals) { indexes::utils::ThreadRegistry::RegisterThread(); for (auto val : vals) { REQUIRE(map.Insert(val, val) == true); REQUIRE(*map.Search(val) == val); } indexes::utils::ThreadRegistry::UnregisterThread(); } enum class OpType { INSERT, DELETE, DELETE_AND_INSERT }; template <typename MapType> static void delete_worker(MapType &map, gsl::span<const int64_t> vals, OpType op) { indexes::utils::ThreadRegistry::RegisterThread(); for (auto val : vals) { switch (op) { case OpType::DELETE: REQUIRE(*map.Delete(val) == val); REQUIRE(map.Search(val).has_value() == false); break; case OpType::DELETE_AND_INSERT: REQUIRE(*map.Delete(val) == val); REQUIRE(map.Insert(val, val) == true); break; case OpType::INSERT: break; } } indexes::utils::ThreadRegistry::UnregisterThread(); } template <typename MapType, LookupType LkType, typename LookupOp> void ConcurrentMapTest(ConcurrentMapTestWorkload workload, LookupOp &&lop) { MapType map; constexpr int PER_THREAD_OP_COUNT = 256 * 1024; const int NUM_THREADS = std::thread::hardware_concurrency(); const std::vector<int64_t> vals = generateUniqueValues(NUM_THREADS, PER_THREAD_OP_COUNT, workload); auto [min_it, max_it] = std::minmax_element(vals.begin(), vals.begin()); int64_t min_val = *min_it, max_val = *max_it; indexes::utils::ThreadRegistry::RegisterThread(); auto run_test = [&](OpType op) { std::vector<std::thread> workers; int startval = 0; int quantum = vals.size() / NUM_THREADS; for (int i = 0; i < NUM_THREADS; i++) { if (op == OpType::INSERT) { workers.emplace_back( insert_worker<MapType>, std::ref(map), gsl::span<const int64_t>{vals.data() + startval, quantum}); } else { workers.emplace_back( delete_worker<MapType>, std::ref(map), gsl::span<const int64_t>{vals.data() + startval, quantum}, op); } startval += quantum; } workers.emplace_back(lookup_worker<MapType, LkType, LookupOp>, std::ref(map), gsl::span<const int64_t>{vals}, min_val, max_val, std::cref(lop)); for (auto &worker : workers) { worker.join(); } }; // Insert check { run_test(OpType::INSERT); REQUIRE(map.size() == vals.size()); for (auto val : vals) { REQUIRE(*map.Search(val) == val); } } // Delete And Insert check { run_test(OpType::DELETE_AND_INSERT); for (auto val : vals) { REQUIRE(*map.Search(val) == val); } REQUIRE(map.size() == vals.size()); } // Delete check { run_test(OpType::DELETE); REQUIRE(map.size() == 0); } indexes::utils::ThreadRegistry::UnregisterThread(); }
{ "alphanum_fraction": 0.620147084, "avg_line_length": 24.9871794872, "ext": "h", "hexsha": "de947fb2310eb69ab3a758ebc7b7b771dc1c2969", "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": "e4027ba2151be57a59034d04dba7d0f2a8e75fef", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "harikrishnan94/bwtree", "max_forks_repo_path": "test/testConcurrentMapUtils.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e4027ba2151be57a59034d04dba7d0f2a8e75fef", "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": "harikrishnan94/bwtree", "max_issues_repo_path": "test/testConcurrentMapUtils.h", "max_line_length": 80, "max_stars_count": 7, "max_stars_repo_head_hexsha": "e4027ba2151be57a59034d04dba7d0f2a8e75fef", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "harikrishnan94/InMemIndexes", "max_stars_repo_path": "test/testConcurrentMapUtils.h", "max_stars_repo_stars_event_max_datetime": "2021-12-27T20:03:10.000Z", "max_stars_repo_stars_event_min_datetime": "2019-07-31T04:06:14.000Z", "num_tokens": 1489, "size": 5847 }
#ifndef QDM_KNOTS_H #define QDM_KNOTS_H 1 #include <gsl/gsl_rng.h> #include <gsl/gsl_vector.h> gsl_vector * qdm_knots_vector( size_t spline_df, gsl_vector *knots_inter ); int qdm_knots_optimize( gsl_vector *result, gsl_rng *rng, gsl_vector *sorted_data, gsl_vector *middle, gsl_vector *possible_knots, size_t iterate_n, size_t spline_df ); #endif /* QDM_KNOTS_H */
{ "alphanum_fraction": 0.7435897436, "avg_line_length": 13.9285714286, "ext": "h", "hexsha": "45ed64e55681b7646a06eecedbbaa7f83f408ebe", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "calebcase/qdm", "max_forks_repo_path": "include/qdm/knots.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z", "max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "calebcase/qdm", "max_issues_repo_path": "include/qdm/knots.h", "max_line_length": 29, "max_stars_count": null, "max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "calebcase/qdm", "max_stars_repo_path": "include/qdm/knots.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 129, "size": 390 }
/* Multisteps: 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_4_4.c * \brief Source file to optimize Runge-Kutta 5 steps 4th order methods. * \author Javier Burguete Tolosa. * \copyright Copyright 2011-2019. */ #define _GNU_SOURCE #include <string.h> #include <math.h> #include <libxml/parser.h> #include <glib.h> #include <libintl.h> #include <gsl/gsl_rng.h> #include "config.h" #include "utils.h" #include "optimize.h" #include "rk.h" #include "rk_4_4.h" #define DEBUG_RK_4_4 0 ///< macro to debug. /** * Function to obtain the coefficients of a 4 steps 4th order Runge-Kutta * method. */ int rk_tb_4_4 (Optimize * optimize) ///< Optimize struct. { long double *tb, *r; #if DEBUG_RK_4_4 fprintf (stderr, "rk_tb_4_4: start\n"); #endif tb = optimize->coefficient; r = optimize->random_data; t4 (tb) = 1.L; t1 (tb) = r[0]; t2 (tb) = r[1]; t3 (tb) = 1.L; b43 (tb) = (0.25L - 1.L / 3.L * t1 (tb) - (1.L / 3.L - 0.5L * t1 (tb)) * t2 (tb)) / (t3 (tb) * (t3 (tb) - t2 (tb)) * (t3 (tb) - t1 (tb))); if (isnan (b43 (tb))) return 0; b42 (tb) = (1.L / 3.L - 0.5L * t1 (tb) - b43 (tb) * t3 (tb) * (t3 (tb) - t1 (tb))) / (t2 (tb) * (t2 (tb) - t1 (tb))); if (isnan (b42 (tb))) return 0; b41 (tb) = (0.5L - b42 (tb) * t2 (tb) - b43 (tb) * t3 (tb)) / t1 (tb); if (isnan (b41 (tb))) return 0; b32 (tb) = (1.L / 12.L - 1.L / 6.L * t1 (tb)) / (b43 (tb) * t2 (tb) * (t2 (tb) - t1 (tb))); if (isnan (b32 (tb))) return 0; b31 (tb) = ((0.125L - 1.L / 6.L * t2 (tb)) / (b43 (tb) * (t3 (tb) - t2 (tb))) - b32 (tb) * t2 (tb)) / t1 (tb); if (isnan (b31 (tb))) return 0; b21 (tb) = 1.L / 24.L / (t1 (tb) * b43 (tb) * b32 (tb)); if (isnan (b21 (tb))) return 0; rk_b_4 (tb); #if DEBUG_RK_4_4 fprintf (stderr, "rk_tb_4_4: end\n"); #endif return 1; } /** * Function to obtain the coefficients of a 4 steps 4th order, 5th order in * equations depending only in time, Runge-Kutta method. */ int rk_tb_4_4t (Optimize * optimize) ///< Optimize struct. { long double *tb, *r; #if DEBUG_RK_4_4 fprintf (stderr, "rk_tb_4_4t: start\n"); #endif tb = optimize->coefficient; r = optimize->random_data; t4 (tb) = 1.L; t1 (tb) = r[0]; t2 (tb) = 0.5L * (t1 (tb) - 0.6L) / (t1 (tb) - 0.5L); t3 (tb) = 1.L; b43 (tb) = (0.25L - 1.L / 3.L * t1 (tb) - (1.L / 3.L - 0.5L * t1 (tb)) * t2 (tb)) / (t3 (tb) * (t3 (tb) - t2 (tb)) * (t3 (tb) - t1 (tb))); if (isnan (b43 (tb))) return 0; b42 (tb) = (1.L / 3.L - 0.5L * t1 (tb) - b43 (tb) * t3 (tb) * (t3 (tb) - t1 (tb))) / (t2 (tb) * (t2 (tb) - t1 (tb))); if (isnan (b42 (tb))) return 0; b41 (tb) = (0.5L - b42 (tb) * t2 (tb) - b43 (tb) * t3 (tb)) / t1 (tb); if (isnan (b41 (tb))) return 0; b32 (tb) = (1.L / 12.L - 1.L / 6.L * t1 (tb)) / (b43 (tb) * t2 (tb) * (t2 (tb) - t1 (tb))); if (isnan (b32 (tb))) return 0; b31 (tb) = ((0.125L - 1.L / 6.L * t2 (tb)) / (b43 (tb) * (t3 (tb) - t2 (tb))) - b32 (tb) * t2 (tb)) / t1 (tb); if (isnan (b31 (tb))) return 0; b21 (tb) = 1.L / 24.L / (t1 (tb) * b43 (tb) * b32 (tb)); if (isnan (b21 (tb))) return 0; rk_b_4 (tb); #if DEBUG_RK_4_4 fprintf (stderr, "rk_tb_4_4t: end\n"); #endif return 1; } /** * Function to calculate the objective function of a 4 steps 4th order * Runge-Kutta method. * * \return objective function value. */ long double rk_objective_tb_4_4 (RK * rk) ///< RK struct. { long double *tb; long double o; #if DEBUG_RK_4_4 fprintf (stderr, "rk_objective_tb_4_4: start\n"); #endif tb = rk->tb->coefficient; o = fminl (0.L, b20 (tb)); if (b21 (tb) < 0.L) o += b21 (tb); if (b30 (tb) < 0.L) o += b30 (tb); if (b31 (tb) < 0.L) o += b31 (tb); if (b32 (tb) < 0.L) o += b32 (tb); if (b40 (tb) < 0.L) o += b40 (tb); if (b41 (tb) < 0.L) o += b41 (tb); if (b42 (tb) < 0.L) o += b42 (tb); if (b43 (tb) < 0.L) o += b43 (tb); if (o < 0.L) { o = 40.L - o; goto end; } o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), t3 (tb)))); if (rk->strong) { rk_bucle_ac (rk); o = fminl (o, *rk->ac0->optimal); } end: #if DEBUG_RK_4_4 fprintf (stderr, "rk_objective_tb_4_4: optimal=%Lg\n", o); fprintf (stderr, "rk_objective_tb_4_4: end\n"); #endif return o; } /** * Function to calculate the objective function of a 4 steps 4th order, 5th * order in equations depending only in time, Runge-Kutta method. * * \return objective function value. */ long double rk_objective_tb_4_4t (RK * rk) ///< RK struct. { long double *tb; long double o; #if DEBUG_RK_4_4 fprintf (stderr, "rk_objective_tb_4_4: start\n"); #endif tb = rk->tb->coefficient; o = fminl (0.L, b20 (tb)); if (b21 (tb) < 0.L) o += b21 (tb); if (b30 (tb) < 0.L) o += b30 (tb); if (b31 (tb) < 0.L) o += b31 (tb); if (b32 (tb) < 0.L) o += b32 (tb); if (b40 (tb) < 0.L) o += b40 (tb); if (b41 (tb) < 0.L) o += b41 (tb); if (b42 (tb) < 0.L) o += b42 (tb); if (b43 (tb) < 0.L) o += b43 (tb); if (o < 0.L) { o = 40.L - o; goto end; } o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), t3 (tb)))); if (rk->strong) { rk_bucle_ac (rk); o = fminl (o, *rk->ac0->optimal); } end: #if DEBUG_RK_4_4 fprintf (stderr, "rk_objective_tb_4_4: optimal=%Lg\n", o); fprintf (stderr, "rk_objective_tb_4_4: end\n"); #endif return o; }
{ "alphanum_fraction": 0.574941452, "avg_line_length": 27.7723577236, "ext": "c", "hexsha": "2d2dc82c27211ba1dad284dbfe07a76f46f641f7", "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_4_4.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_4_4.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_4_4.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2635, "size": 6832 }
#include <string.h> #include <mpi.h> #include <math.h> #include <alloca.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_integration.h> #include <fastpm/libfastpm.h> #include <fastpm/logging.h> #include <fastpm/string.h> #include "pmpfft.h" void fastpm_powerspectrum_init(FastPMPowerSpectrum * ps, const size_t size) { fastpm_funck_init(&ps->base, size); ps->pm = NULL; ps->edges = malloc(sizeof(ps->edges[0]) * (ps->base.size + 1)); ps->Nmodes = malloc(sizeof(ps->Nmodes[0]) * ps->base.size); } void fastpm_powerspectrum_init_from(FastPMPowerSpectrum * ps, const FastPMPowerSpectrum * other) { fastpm_powerspectrum_init(ps, other->base.size); memcpy(ps->base.k, other->base.k, sizeof(ps->base.k[0]) * ps->base.size); memcpy(ps->base.f, other->base.f, sizeof(ps->base.f[0]) * ps->base.size); memcpy(ps->edges, other->edges, sizeof(ps->edges[0]) * (ps->base.size + 1)); memcpy(ps->Nmodes, other->Nmodes, sizeof(ps->Nmodes[0]) * ps->base.size); } void fastpm_powerspectrum_init_from_delta(FastPMPowerSpectrum * ps, PM * pm, const FastPMFloat * delta1_k, const FastPMFloat * delta2_k) { /* This function measures powerspectrum from two overdensity or 1+overdensity fields */ /* normalize them with fastpm_apply_normalize_transfer if needed before using this function.*/ /* N is used to store metadata -- the shot-noise level. */ fastpm_powerspectrum_init(ps, pm_nmesh(pm)[0] / 2); ps->pm = pm; double Volume = 1.0; int d; double k0 = 2 * M_PI / pm_boxsize(ps->pm)[0]; for (d = 0; d < 3; d ++) { Volume *= pm_boxsize(pm)[d]; } ps->Volume = Volume; ps->k0 = k0; memset(ps->base.f, 0, sizeof(ps->base.f[0]) * ps->base.size); memset(ps->base.k, 0, sizeof(ps->base.k[0]) * ps->base.size); memset(ps->edges, 0, sizeof(ps->edges[0]) * (ps->base.size + 1)); memset(ps->Nmodes, 0, sizeof(ps->Nmodes[0]) * ps->base.size); int i; for(i = 0; i < ps->base.size + 1; i ++) { ps->edges[i] = i * k0; } #pragma omp parallel { PMKIter kiter; for(pm_kiter_init(ps->pm, &kiter); !pm_kiter_stop(&kiter); pm_kiter_next(&kiter)) { int d; ptrdiff_t kk = 0.; for(d = 0; d < 3; d++) { double ik = kiter.iabs[d]; if(ik > pm->Nmesh[d] / 2) ik -= pm->Nmesh[d]; kk += ik * ik; } ptrdiff_t ind = kiter.ind; ptrdiff_t bin = ((ptrdiff_t)floor(sqrt(kk))) - 2; if(bin < 0) bin = 0; while((bin + 1) * (bin + 1) <= kk) { bin ++; } double k = sqrt(kk) * k0; if(bin >= 0 && bin < ps->base.size) { double real1 = delta1_k[ind + 0]; double imag1 = delta1_k[ind + 1]; double real2 = delta2_k[ind + 0]; double imag2 = delta2_k[ind + 1]; double value = real1 * real2 + imag1 * imag2; int w = 2; if(kiter.i[2] == 0 || kiter.i[2] == pm->Nmesh[2] / 2) w = 1; if(kiter.iabs[0] == 0 && kiter.iabs[1] == 0 && kiter.iabs[2] == 0) { } else { #pragma omp atomic ps->Nmodes[bin] += w; #pragma omp atomic ps->base.f[bin] += w * value; /// cic; #pragma omp atomic ps->base.k[bin] += w * k; } } } } MPI_Allreduce(MPI_IN_PLACE, ps->base.f, ps->base.size, MPI_DOUBLE, MPI_SUM, ps->pm->Comm2D); MPI_Allreduce(MPI_IN_PLACE, ps->Nmodes, ps->base.size, MPI_DOUBLE, MPI_SUM, ps->pm->Comm2D); MPI_Allreduce(MPI_IN_PLACE, ps->base.k, ps->base.size, MPI_DOUBLE, MPI_SUM, ps->pm->Comm2D); ptrdiff_t ind; for(ind = 0; ind < ps->base.size; ind++) { if(ps->Nmodes[ind] == 0) continue; ps->base.k[ind] /= ps->Nmodes[ind]; ps->base.f[ind] /= ps->Nmodes[ind]; ps->base.f[ind] *= ps->Volume; } } void fastpm_transferfunction_init(FastPMPowerSpectrum * ps, PM * pm, FastPMFloat * src_k, FastPMFloat * dest_k) { FastPMPowerSpectrum * ps2 = alloca(sizeof(*ps2)); fastpm_powerspectrum_init_from_delta(ps, pm, src_k, src_k); fastpm_powerspectrum_init_from_delta(ps2, pm, dest_k, dest_k); ptrdiff_t i; for(i = 0; i < ps->base.size; i ++) { ps->base.f[i] = sqrt(ps2->base.f[i] / ps->base.f[i]); } fastpm_powerspectrum_destroy(ps2); } void fastpm_powerspectrum_destroy(FastPMPowerSpectrum * ps) { free(ps->edges); free(ps->Nmodes); fastpm_funck_destroy(&ps->base); } void fastpm_powerspectrum_write(FastPMPowerSpectrum * ps, char * filename, double N) { FILE * fp = fopen(filename, "w"); int i; fprintf(fp, "# k p N \n"); for(i = 0; i < ps->base.size; i ++) { fprintf(fp, "%g %g %g\n", ps->base.k[i], ps->base.f[i], ps->Nmodes[i]); } double * BoxSize = pm_boxsize(ps->pm); fprintf(fp, "# metadata 7\n"); fprintf(fp, "# volume %g float64\n", ps->Volume); fprintf(fp, "# shotnoise %g float64\n", ps->Volume / N); fprintf(fp, "# N1 %g int\n", N); fprintf(fp, "# N2 %g int\n", N); fprintf(fp, "# Lz %g float64\n", BoxSize[2]); fprintf(fp, "# Lx %g float64\n", BoxSize[0]); fprintf(fp, "# Ly %g float64\n", BoxSize[1]); fclose(fp); } double fastpm_powerspectrum_large_scale(FastPMPowerSpectrum * ps, int Nmax) { double kmax = Nmax * ps->k0; ptrdiff_t i; double Plin = 0; double Nmodes = 0; /* ignore zero mode ! */ for(i = 0; (i == 0) || (i < ps->base.size && ps->base.k[i] <= kmax); i ++) { Plin += ps->base.f[i] * ps->Nmodes[i]; Nmodes += ps->Nmodes[i]; } Plin /= Nmodes; return Plin; } /* inverted calling signature for callbacks */ double fastpm_powerspectrum_eval2(double k, FastPMPowerSpectrum * ps) { return fastpm_powerspectrum_eval(ps, k); } double fastpm_powerspectrum_eval(FastPMPowerSpectrum * ps, double k) { return fastpm_funck_eval(&ps->base, k); } double fastpm_powerspectrum_get(FastPMPowerSpectrum * ps, double k) { if(k == 0) return 1; /* ignore the 0 mode */ int l = 0; int r = ps->base.size; while(r - l > 1) { int m = (r + l) / 2; /* if we are on the exact k, return value from there.*/ if(k <= ps->edges[m]) r = m; else l = m; } return ps->base.f[l]; } double fastpm_powerspectrum_get2(double k, FastPMPowerSpectrum * ps) { return fastpm_powerspectrum_get(ps, k); } struct sigma2_int { FastPMPowerSpectrum * ps; double R; }; static double sigma2_int(double k, struct sigma2_int * param) { double kr, kr3, kr2, w, x; double r_tophat = param->R; kr = r_tophat * k; kr2 = kr * kr; kr3 = kr2 * kr; if(kr < 1e-8) return 0; w = 3 * (sin(kr) / kr3 - cos(kr) / kr2); x = 4 * M_PI * k * k * w * w * fastpm_powerspectrum_eval(param->ps, k); return x / pow(2 * M_PI, 3); } double fastpm_powerspectrum_sigma(FastPMPowerSpectrum * ps, double R) { const int WORKSIZE = 81920; double result, abserr; gsl_integration_workspace *workspace; gsl_function F; struct sigma2_int param; param.ps = ps; param.R = R; workspace = gsl_integration_workspace_alloc(WORKSIZE); F.function = (void*) &sigma2_int; F.params = &param; void * handler = gsl_set_error_handler_off (); // // note: 500/R is here chosen as (effectively) infinity integration boundary gsl_integration_qag(&F, 0, 500.0 * 1 / R, 0, 1.0e-4, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr); // high precision caused error gsl_integration_workspace_free(workspace); gsl_set_error_handler (handler); return sqrt(result); } void fastpm_powerspectrum_scale(FastPMPowerSpectrum * ps, double factor) { ptrdiff_t i; /* neglect the zero mode */ for(i = 1; i < ps->base.size; i ++) { ps->base.f[i] *= factor; } } void fastpm_powerspectrum_rebin(FastPMPowerSpectrum * ps, size_t newsize) { /* this doesn't work */ double * k1 = malloc(newsize * sizeof(k1[0])); double * p1 = malloc(newsize * sizeof(p1[0])); double * Nmodes1 = malloc(newsize * sizeof(Nmodes1[0])); double * edges1 = malloc((newsize + 1) * sizeof(edges1[0])); ptrdiff_t i; for(i = 0; i < newsize; i ++) { ptrdiff_t j1 = (i ) * ps->base.size / newsize; ptrdiff_t j2 = (i + 1) * ps->base.size / newsize; ptrdiff_t j; k1[i] = 0; p1[i] = 0; Nmodes1[i] = 0; edges1[i] = ps->edges[j1]; edges1[i + 1] = ps->edges[j2]; for(j = j1; j < j2; j ++) { k1[i] += ps->base.k[j] * ps->Nmodes[j]; p1[i] += ps->base.f[j] * ps->Nmodes[j]; Nmodes1[i] += ps->Nmodes[j]; } if(Nmodes1[i] > 0) { k1[i] /= Nmodes1[i]; p1[i] /= Nmodes1[i]; } } free(ps->base.k); free(ps->base.f); free(ps->Nmodes); free(ps->edges); ps->base.k = k1; ps->base.f = p1; ps->Nmodes = Nmodes1; ps->edges = edges1; ps->base.size = newsize; } int fastpm_powerspectrum_init_from_string(FastPMPowerSpectrum * ps, const char * string) { int r = fastpm_funck_init_from_string(&ps->base, string); ps->edges = malloc(sizeof(ps->edges[0]) * (ps->base.size + 1)); ps->Nmodes = malloc(sizeof(ps->Nmodes[0]) * ps->base.size); return r; } void fastpm_funck_init(FastPMFuncK * fk, const size_t size) { fk->size = size; fk->k = malloc(sizeof(fk->k[0]) * fk->size); fk->f = malloc(sizeof(fk->f[0]) * fk->size); } int fastpm_funck_init_from_string(FastPMFuncK * fk, const char * string) { char ** list = fastpm_strsplit(string, "\n"); char ** line; ptrdiff_t i; int pass = 0; /* two pass parsing, first pass for counting */ /* second pass for assignment */ while(pass < 2) { i = 0; for (line = list; *line; line++) { double k, f; if(2 == sscanf(*line, "%lg\t%lg", &k, &f)) { // note tab. Could make more general? if(pass == 1) { fk->k[i] = k; fk->f[i] = f; } i ++; } } if(pass == 0) { fastpm_funck_init(fk, i); } pass ++; } free(list); if(fk->size == 0) { /* Nothing is savagable in the file.*/ return 0; } return 0; } /* inverted calling signature for callbacks */ double fastpm_funck_eval2(double k, FastPMFuncK * fk) { return fastpm_funck_eval(fk, k); } double fastpm_funck_eval(FastPMFuncK * fk, double k) { /* ignore the 0 mode */ if(k == 0) return 1; int l = 0; int r = fk->size - 1; /* determine the right and left values around k */ while(r - l > 1) { int m = (r + l) / 2; if(k < fk->k[m]) r = m; else l = m; } double k2 = fk->k[r], k1 = fk->k[l]; double f2 = fk->f[r], f1 = fk->f[l]; if(l == r) { return fk->f[l]; } if(f1 <= 0 || f2 <= 0 || k1 == 0 || k2 == 0) { /* if any of the f is zero, or negative, use linear interpolation */ double f = (k - k1) * f2 + (k2 - k) * f1; f /= (k2 - k1); return f; } else { k = log(k); f1 = log(f1); f2 = log(f2); k1 = log(k1); k2 = log(k2); double f = (k - k1) * f2 + (k2 - k) * f1; f /= (k2 - k1); return exp(f); } } void fastpm_funck_destroy(FastPMFuncK * fk) { free(fk->f); free(fk->k); }
{ "alphanum_fraction": 0.5427267348, "avg_line_length": 26.8276643991, "ext": "c", "hexsha": "49e95c017d27aa637bee778585f52d3bfe9e331b", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-04-14T23:24:19.000Z", "max_forks_repo_forks_event_min_datetime": "2021-04-14T23:24:19.000Z", "max_forks_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sbird/FastPMRunner", "max_forks_repo_path": "fastpm/libfastpm/powerspectrum.c", "max_issues_count": 4, "max_issues_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_issues_repo_issues_event_max_datetime": "2022-01-24T05:51:04.000Z", "max_issues_repo_issues_event_min_datetime": "2021-04-19T23:01:33.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "sbird/FastPMRunner", "max_issues_repo_path": "fastpm/libfastpm/powerspectrum.c", "max_line_length": 131, "max_stars_count": null, "max_stars_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sbird/FastPMRunner", "max_stars_repo_path": "fastpm/libfastpm/powerspectrum.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3739, "size": 11831 }
#ifndef INCLUDED_TELEPATH_BLAS_3_GEMM_H #define INCLUDED_TELEPATH_BLAS_3_GEMM_H #include <cblas.h> namespace telepath{ template< typename T > void gemm( CBLAS_ORDER order, CBLAS_TRANSPOSE transA, CBLAS_TRANSPOSE transB, std::size_t m std::size_t n, std::size_t k, T alpha, const T* A, std::size_t lda, const T* B, std::size_t ldb, T beta, T* C, std::size_t ldc ); template<> void gemm<float>( CBLAS_ORDER order, CBLAS_TRANSPOSE transA, CBLAS_TRANSPOSE transB, std::size_t m, std::size_t n, std::size_t k, float alpha, const float* A, std::size_t lda, const float* B, std::size_t ldb, float beta, float* C, std::size_t ldc ){ return cblas_sgemm( order, transA, transB, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc ); } template<> void gemm<double>( CBLAS_ORDER order, CBLAS_TRANSPOSE transA, CBLAS_TRANSPOSE transB, std::size_t m, std::size_t n, std::size_t k, double alpha, const double* A, std::size_t lda, const double* B, std::size_t ldb, double beta, double* C, std::size_t ldc ){ return cblas_dgemm( order, transA, transB, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc ); } template<> void gemm<std::complex<float>>( CBLAS_ORDER order, CBLAS_TRANSPOSE transA, CBLAS_TRANSPOSE transB, std::size_t m, std::size_t n, std::size_t k, const std::complex<float>* alpha, const std::complex<float>* A, std::size_t lda, std::const complex<float>* B, std::size_t ldb, const std::complex<float>* beta, std::complex<float>* C, std::size_t ldc ){ return cblas_cgemm( order, transA, transB, m, n, k, (float*) alpha, (float*) A, lda, (float*) B, ldb, (float*) beta, (float*) C, ldc ); } template<> void gemm<std::complex<double>>( CBLAS_ORDER order, CBLAS_TRANSPOSE transA, CBLAS_TRANSPOSE transB, std::size_t m, std::size_t n, std::size_t k, const std::complex<double>* alpha, const std::complex<double>* A, std::size_t lda, const std::complex<double>* B, std::size_t ldb, const std::complex<double>* beta, std::complex<double>* C, std::size_t ldc ){ return cblas_zgemm( order, transA, transB, m, n, k, (double*) alpha, (double*) A, lda, (double*) B, ldb, (double*) beta, (double*) C, ldc ); } } //namespace telepath #endif
{ "alphanum_fraction": 0.6238114924, "avg_line_length": 43.9818181818, "ext": "h", "hexsha": "0541b793324fe8500e8d19edc420c6c0419a2b13", "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": "636f7345b6479d5c48dbf03cb17343b14c305c7c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tbepler/telepath", "max_forks_repo_path": "include/telepath/blas/level3/gemm.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "636f7345b6479d5c48dbf03cb17343b14c305c7c", "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": "tbepler/telepath", "max_issues_repo_path": "include/telepath/blas/level3/gemm.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "636f7345b6479d5c48dbf03cb17343b14c305c7c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tbepler/telepath", "max_stars_repo_path": "include/telepath/blas/level3/gemm.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 740, "size": 2419 }
/** *@file CosanBO.h *@author Xinyu Zhang *@brief CosanBO *@date 2021-04-10 */ #ifndef __COSANBO_H_INCLUDED__ #define __COSANBO_H_INCLUDED__ #include <string> #ifndef FMT_HEADER_ONLY #define FMT_HEADER_ONLY #include <fmt/format.h> #endif #include <gsl/gsl> #include <type_traits> #include <cosan/utils/utils.h> #include <cosan/utils/Exceptions.h> #include <random> template<typename NumericType> concept Numeric = std::is_arithmetic<NumericType>::value ; template <class T, class U> concept Derived = std::is_base_of<U, T>::value; namespace Cosan { // template<typename NumericType, // typename = typename std::enable_if<std::is_arithmetic<NumericType>::value,NumericType>::type // > /** Description: data structure for matrix. Will be used throughout the project. */ template<Numeric NumericType> using CosanMatrix = Eigen::Matrix<NumericType, Eigen::Dynamic, Eigen::Dynamic> ; // template<typename NumericType, // typename = typename std::enable_if<std::is_arithmetic<NumericType>::value,NumericType>::type // > /** Description: data structure for column vector. Will be used throughout the project. */ template<Numeric NumericType> using CosanColVector = Eigen::Matrix<NumericType, Eigen::Dynamic, 1> ; // template<typename NumericType, // typename = typename std::enable_if<std::is_arithmetic<NumericType>::value,NumericType>::type // > /** Description: data structure for row vector. Will be used throughout the project. */ template<Numeric NumericType> using CosanRowVector = Eigen::Matrix<NumericType, 1, Eigen::Dynamic> ; // typedef std::variant<CosanMatrix<unsigned int>, CosanMatrix<unsigned long>, // CosanMatrix<unsigned long long>, > /** * @brief Cosan Base Object * @details: Description: Base object CosanBO which all other Cosan objects inherited from. * */ class CosanBO { public: /** * @brief Default constructor. **/ CosanBO(){ } // virtual ~CosanBO(); // virtual CosanBO *Shallow_copy() const; // virtual CosanBO *Deep_copy() const; /** * @brief Get the name of the objects. * @details Description: Get the name of the object. It should return "Abstract Object" **/ virtual const std::string GetName() const { return "Abstract Object";} // virtual bool SaveFile(const std::string &path ,const std::string & prefix = ""); // virtual bool LoadFile(const std::string &path); // void PrintModel(); // virtual bool Equals(CosanBO* other, float accuracy = 0.0); // virtual CosanBO* Clone(); protected: }; } #endif
{ "alphanum_fraction": 0.6550724638, "avg_line_length": 30, "ext": "h", "hexsha": "b80262a5cd7718e4f5ef65c6c5b9807ccbc29782", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-04-13T05:56:38.000Z", "max_forks_repo_forks_event_min_datetime": "2021-04-13T05:56:38.000Z", "max_forks_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zhxinyu/cosan", "max_forks_repo_path": "cosan/base/CosanBO.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "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": "zhxinyu/cosan", "max_issues_repo_path": "cosan/base/CosanBO.h", "max_line_length": 106, "max_stars_count": null, "max_stars_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zhxinyu/cosan", "max_stars_repo_path": "cosan/base/CosanBO.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 660, "size": 2760 }
#pragma once #include <wrl/client.h> #include <d3d11.h> #include <gsl/span> namespace vrutil { template <typename T> using ComPtr = Microsoft::WRL::ComPtr<T>; using SharedTexture = std::pair<ComPtr<ID3D11Texture2D>, HANDLE>; class D3DManager { class D3D11ManagerImpl *m_impl; public: D3DManager(); ~D3DManager(); bool Initialize(); ComPtr<ID3D11Texture2D> CreateStaticTexture(int w, int h, const gsl::span<uint8_t> &bytes); SharedTexture CreateSharedStaticTexture(int w, int h, const gsl::span<uint8_t> &bytes); void Copy(const ComPtr<ID3D11Texture2D> &src, const ComPtr<ID3D11Texture2D> &dst); }; } // namespace vrutil
{ "alphanum_fraction": 0.7017804154, "avg_line_length": 28.0833333333, "ext": "h", "hexsha": "559b53fdd76b4417b04d55a77a597d84d568e282", "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": "6116b91403393f2f7747c3da902b29612b0ce20a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ousttrue/VROverlaySample", "max_forks_repo_path": "vrutil/D3DManager.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "6116b91403393f2f7747c3da902b29612b0ce20a", "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": "ousttrue/VROverlaySample", "max_issues_repo_path": "vrutil/D3DManager.h", "max_line_length": 96, "max_stars_count": null, "max_stars_repo_head_hexsha": "6116b91403393f2f7747c3da902b29612b0ce20a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ousttrue/VROverlaySample", "max_stars_repo_path": "vrutil/D3DManager.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 198, "size": 674 }
/* Author: G. Jungman */ #ifndef __GSL_SF_H__ #define __GSL_SF_H__ #include <gsl/gsl_sf_result.h> #include <gsl/gsl_sf_airy.h> #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_sf_clausen.h> #include <gsl/gsl_sf_coupling.h> #include <gsl/gsl_sf_coulomb.h> #include <gsl/gsl_sf_dawson.h> #include <gsl/gsl_sf_debye.h> #include <gsl/gsl_sf_dilog.h> #include <gsl/gsl_sf_elementary.h> #include <gsl/gsl_sf_ellint.h> #include <gsl/gsl_sf_elljac.h> #include <gsl/gsl_sf_erf.h> #include <gsl/gsl_sf_exp.h> #include <gsl/gsl_sf_expint.h> #include <gsl/gsl_sf_fermi_dirac.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_sf_gegenbauer.h> #include <gsl/gsl_sf_hyperg.h> #include <gsl/gsl_sf_laguerre.h> #include <gsl/gsl_sf_lambert.h> #include <gsl/gsl_sf_legendre.h> #include <gsl/gsl_sf_log.h> #include <gsl/gsl_sf_pow_int.h> #include <gsl/gsl_sf_psi.h> #include <gsl/gsl_sf_synchrotron.h> #include <gsl/gsl_sf_transport.h> #include <gsl/gsl_sf_trig.h> #include <gsl/gsl_sf_zeta.h> #endif /* __GSL_SF_H__ */
{ "alphanum_fraction": 0.7668650794, "avg_line_length": 25.8461538462, "ext": "h", "hexsha": "3c1ec93da33ab89fc703634d7e7ec802c08397c3", "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": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_sf.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_sf.h", "max_line_length": 35, "max_stars_count": 14, "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_sf.h", "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": 361, "size": 1008 }
#pragma once #include <utility> #include <iostream> #include <initializer_list> #include <exception> #include <gsl/gsl_math.h> #include <gsl/gsl_linalg.h> #include "utils/fcmp.h" namespace gsl_wrapper { class Vector { public: // Constructors and destructor Vector(size_t vec_size); Vector(gsl_vector *gsl_vec_ptr); Vector(const Vector &copy_from); Vector(Vector &&move_from); Vector(std::initializer_list<double> args); ~Vector(); // Member functions auto get_gsl_vector() const -> gsl_vector *; auto size() const -> size_t; auto begin() const -> double *; auto end() const -> double *; // Operators auto operator=(const Vector &copy_from) -> Vector &; auto operator=(Vector &&move_from) -> Vector &; auto operator==(const Vector &comparasion_vector) -> bool; auto operator!=(const Vector &comparasion_vector) -> bool; auto operator[](const size_t index) -> double &; auto operator[](const size_t index) const -> const double &; auto operator+(const Vector &add_to) const -> Vector; auto operator-(const Vector &sub) const -> Vector; auto operator*(const double number) const -> Vector; // Friend declarations friend auto operator<<(std::ostream &stream, const Vector &to_print) -> std::ostream &; friend auto operator*(const double number, const Vector &vec) -> Vector; private: gsl_vector *m_vector_ptr; size_t m_vector_size; }; inline Vector::Vector(size_t vec_size) : m_vector_ptr{gsl_vector_calloc(vec_size)}, m_vector_size{vec_size} { } inline Vector::Vector(gsl_vector *gsl_vec_ptr) : m_vector_ptr{gsl_vec_ptr}, m_vector_size{gsl_vec_ptr->size} { } inline Vector::Vector(const Vector &copy_from) : m_vector_ptr{gsl_vector_calloc(copy_from.m_vector_size)}, m_vector_size{copy_from.m_vector_size} { gsl_vector_memcpy(m_vector_ptr, copy_from.m_vector_ptr); } inline Vector::Vector(Vector &&move_from) : m_vector_ptr{std::exchange(move_from.m_vector_ptr, nullptr)}, m_vector_size{std::exchange(move_from.m_vector_size, 0)} { } inline Vector::Vector(std::initializer_list<double> args) : m_vector_ptr{gsl_vector_calloc(args.size())}, m_vector_size{args.size()} { size_t i = 0; for (auto &&el : args) { gsl_vector_set(m_vector_ptr, i++, el); } } inline Vector::~Vector() { gsl_vector_free(m_vector_ptr); } inline auto Vector::get_gsl_vector() const -> gsl_vector * { return m_vector_ptr; } inline auto Vector::size() const -> size_t { return m_vector_size; } inline auto Vector::begin() const -> double * { return m_vector_ptr->data; } inline auto Vector::end() const -> double * { return m_vector_ptr->data + m_vector_size; } inline auto Vector::operator=(const Vector &copy_from) -> Vector & { // Prevent self copy if (m_vector_ptr == copy_from.m_vector_ptr) return *this; gsl_vector_free(m_vector_ptr); m_vector_ptr = gsl_vector_calloc(copy_from.m_vector_size); gsl_vector_memcpy(m_vector_ptr, copy_from.m_vector_ptr); m_vector_size = copy_from.m_vector_size; return *this; } inline auto Vector::operator=(Vector &&move_from) -> Vector & { // Prevent self move if (m_vector_ptr == move_from.m_vector_ptr) return *this; gsl_vector_free(m_vector_ptr); m_vector_ptr = std::exchange(move_from.m_vector_ptr, nullptr); m_vector_size = std::exchange(move_from.m_vector_size, 0); return *this; } inline auto Vector::operator==(const Vector &comparasion_vector) -> bool { if (m_vector_size != comparasion_vector.m_vector_size) return false; for (size_t i = 0; i < m_vector_size; i++) { bool test = ::gsl_wrapper::utils::equal((*this)[i], comparasion_vector[i]); if (!test) return false; } return true; } inline auto Vector::operator!=(const Vector &comparasion_vector) -> bool { return !(*this == comparasion_vector); } inline auto Vector::operator[](const size_t index) -> double & { if (index >= m_vector_size) throw std::range_error{"Accesing vector elements out of bounds"}; return *gsl_vector_ptr(m_vector_ptr, index); } inline auto Vector::operator[](const size_t index) const -> const double & { return *gsl_vector_const_ptr(m_vector_ptr, index); } inline auto operator<<(std::ostream &stream, const Vector &to_print) -> std::ostream & { for (size_t i = 0; i < to_print.m_vector_size - 1; i++) { stream << to_print[i] << " "; } stream << to_print[to_print.m_vector_size - 1]; return stream; } inline auto Vector::operator+(const Vector &add_to) const -> Vector { if (m_vector_size != add_to.m_vector_size) throw std::range_error{"Adding vector of diffrent sizes"}; Vector result(m_vector_size); for (size_t i = 0; i < m_vector_size; i++) { result[i] = (*this)[i] + add_to[i]; } return result; } inline auto Vector::operator-(const Vector &sub) const -> Vector { if (m_vector_size != sub.m_vector_size) throw std::range_error{"Subtracting vector of diffrent sizes"}; Vector result(m_vector_size); for (size_t i = 0; i < m_vector_size; i++) { result[i] = (*this)[i] - sub[i]; } return result; } inline auto Vector::operator*(const double number) const -> Vector { Vector result = *this; for (auto &&el : result) { el *= number; } return result; } inline auto operator*(const double number, const Vector &vec) -> Vector { Vector result = vec; for (auto &&el : result) { el *= number; } return result; } }
{ "alphanum_fraction": 0.6518288475, "avg_line_length": 24.0497925311, "ext": "h", "hexsha": "e92f30dccbbd32f476cb4f319443eea03fe4ac64", "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": "0c9c4edfe751474edbf1a9a23075762cc3362cc1", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Szynkaa/gsl_cpp_wrapper", "max_forks_repo_path": "include/gsl_wrapper/vector.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0c9c4edfe751474edbf1a9a23075762cc3362cc1", "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": "Szynkaa/gsl_cpp_wrapper", "max_issues_repo_path": "include/gsl_wrapper/vector.h", "max_line_length": 91, "max_stars_count": null, "max_stars_repo_head_hexsha": "0c9c4edfe751474edbf1a9a23075762cc3362cc1", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "Szynkaa/gsl_cpp_wrapper", "max_stars_repo_path": "include/gsl_wrapper/vector.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1498, "size": 5796 }
//Normalizes RMS of each vector in X according to dim. //See C++ command-line code for more info. #include <stdio.h> #include <stdlib.h> #include <float.h> #include <math.h> #include <lapacke.h> #ifdef __cplusplus namespace codee { extern "C" { #endif int rms_scale_s (float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const float sr, const float tau, const float target_dB_SPL, const float max_dB_SPL); int rms_scale_d (double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const double sr, const double tau, const double target_dB_SPL, const double max_dB_SPL); int rms_scale_s (float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const float sr, const float tau, const float target_dB_SPL, const float max_dB_SPL) { if (dim>3u) { fprintf(stderr,"error in rms_scale_s: dim must be in [0 3]\n"); return 1; } if (sr<=0.0f) { fprintf(stderr,"error in rms_scale_s: sr (sample rate) must be positive\n"); return 1; } if (tau<=0.0f) { fprintf(stderr,"error in rms_scale_s: tau (time constant) must be positive\n"); return 1; } const size_t N = R*C*S*H; const size_t L = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; if (N<2u || L<2u) {} else { const float rms_prctile = 0.9f; const float target_RMS = 20e-6f * powf(10.0f, target_dB_SPL/20.0f); const float max_RMS = 20e-6f * powf(10.0f, max_dB_SPL/20.0f); const float a1 = expf(-1.0f/(sr*tau)); const float b0 = 1.0f - a1; const size_t tranz = (L>5u) ? 5u : 0u; //nsamps to zero in case transient const size_t rms_p = (size_t)roundf((1.0f-rms_prctile)*(float)L); //index for rms_prctile float rms, scale, scalemx; float *Y; if (!(Y=(float *)malloc(L*sizeof(float)))) { fprintf(stderr,"error in rms_scale_s: problem with malloc. "); perror("malloc"); return 1; } if (L==N) { *Y = b0 * *X * *X; ++X; ++Y; for (size_t l=L-1u; l>0u; --l, ++X, ++Y) { *Y = b0**X**X + a1**(Y-1); } Y -= L; for (size_t l=tranz; l>0u; --l, ++Y) { *Y = 0.0f; } //in case transient Y -= tranz; if (LAPACKE_slasrt_work('D',(int)L,Y)) { fprintf(stderr,"error in rms_scale_s: problem with LAPACKE function\n"); } rms = sqrtf(*Y); scalemx = (rms>FLT_EPSILON) ? max_RMS/rms : 1.0f; rms = sqrtf(*(Y+rms_p)); scale = (rms>FLT_EPSILON) ? target_RMS/rms : 1.0f; scale = (scale<scalemx) ? scale : scalemx; for (size_t l=L; l>0u; --l) { *--X *= scale; } } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/L, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=V; v>0u; --v, X+=L) { *Y = b0 * *X * *X; ++X; ++Y; for (size_t l=L-1u; l>0u; --l, ++X, ++Y) { *Y = b0**X**X + a1**(Y-1); } Y -= L; for (size_t l=tranz; l>0u; --l, ++Y) { *Y = 0.0f; } //in case transient Y -= tranz; if (LAPACKE_slasrt_work('D',(int)L,Y)) { fprintf(stderr,"error in rms_scale_s: problem with LAPACKE function\n"); } rms = sqrtf(*Y); scalemx = (rms>FLT_EPSILON) ? max_RMS/rms : 1.0f; rms = sqrtf(*(Y+rms_p)); scale = (rms>FLT_EPSILON) ? target_RMS/rms : 1.0f; scale = (scale<scalemx) ? scale : scalemx; for (size_t l=L; l>0u; --l) { *--X *= scale; } } } else { for (size_t g=G; g>0u; --g, X+=B*(L-1u)) { for (size_t b=B; b>0u; --b, ++X) { *Y = b0 * *X * *X; X+=K; ++Y; for (size_t l=L-1u; l>0u; --l, X+=K, ++Y) { *Y = b0**X**X + a1**(Y-1); } Y -= L; for (size_t l=tranz; l>0u; --l, ++Y) { *Y = 0.0f; } //in case transient Y -= tranz; if (LAPACKE_slasrt_work('D',(int)L,Y)) { fprintf(stderr,"error in rms_scale_s: problem with LAPACKE function\n"); } rms = sqrtf(*Y); scalemx = (rms>FLT_EPSILON) ? max_RMS/rms : 1.0f; rms = sqrtf(*(Y+rms_p)); scale = (rms>FLT_EPSILON) ? target_RMS/rms : 1.0f; scale = (scale<scalemx) ? scale : scalemx; for (size_t l=L; l>0u; --l) { X-=K; *X *= scale; } } } } } free(Y); } return 0; } int rms_scale_d (double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const double sr, const double tau, const double target_dB_SPL, const double max_dB_SPL) { if (dim>3u) { fprintf(stderr,"error in rms_scale_d: dim must be in [0 3]\n"); return 1; } if (sr<=0.0) { fprintf(stderr,"error in rms_scale_d: sr (sample rate) must be positive\n"); return 1; } if (tau<=0.0) { fprintf(stderr,"error in rms_scale_d: tau (time constant) must be positive\n"); return 1; } const size_t N = R*C*S*H; const size_t L = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; if (N<2u || L<2u) {} else { const double rms_prctile = 0.9; const double target_RMS = 20e-6 * pow(10.0, target_dB_SPL/20.0); const double max_RMS = 20e-6 * pow(10.0, max_dB_SPL/20.0); const double a1 = exp(-1.0/(sr*tau)); const double b0 = 1.0 - a1; const size_t tranz = (L>5u) ? 5u : 0u; //nsamps to zero in case transient const size_t rms_p = (size_t)round((1.0-rms_prctile)*(double)L); //index for rms_prctile double rms, scale, scalemx; double *Y; if (!(Y=(double *)malloc(L*sizeof(double)))) { fprintf(stderr,"error in rms_scale_d: problem with malloc. "); perror("malloc"); return 1; } if (L==N) { *Y = b0 * *X * *X; ++X; ++Y; for (size_t l=L-1u; l>0u; --l, ++X, ++Y) { *Y = b0**X**X + a1**(Y-1); } Y -= L; for (size_t l=tranz; l>0u; --l, ++Y) { *Y = 0.0; } //in case transient Y -= tranz; if (LAPACKE_dlasrt_work('D',(int)L,Y)) { fprintf(stderr,"error in rms_scale_d: problem with LAPACKE function\n"); } rms = sqrt(*Y); scalemx = (rms>DBL_EPSILON) ? max_RMS/rms : 1.0; rms = sqrt(*(Y+rms_p)); scale = (rms>DBL_EPSILON) ? target_RMS/rms : 1.0; scale = (scale<scalemx) ? scale : scalemx; for (size_t l=L; l>0u; --l) { *--X *= scale; } } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/L, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=V; v>0u; --v, X+=L) { *Y = b0 * *X * *X; ++X; ++Y; for (size_t l=L-1u; l>0u; --l, ++X, ++Y) { *Y = b0**X**X + a1**(Y-1); } Y -= L; for (size_t l=tranz; l>0u; --l, ++Y) { *Y = 0.0; } //in case transient Y -= tranz; if (LAPACKE_dlasrt_work('D',(int)L,Y)) { fprintf(stderr,"error in rms_scale_d: problem with LAPACKE function\n"); } rms = sqrt(*Y); scalemx = (rms>DBL_EPSILON) ? max_RMS/rms : 1.0; rms = sqrt(*(Y+rms_p)); scale = (rms>DBL_EPSILON) ? target_RMS/rms : 1.0; scale = (scale<scalemx) ? scale : scalemx; for (size_t l=L; l>0u; --l) { *--X *= scale; } } } else { for (size_t g=G; g>0u; --g, X+=B*(L-1u)) { for (size_t b=B; b>0u; --b, ++X) { *Y = b0 * *X * *X; X+=K; ++Y; for (size_t l=L-1u; l>0u; --l, X+=K, ++Y) { *Y = b0**X**X + a1**(Y-1); } Y -= L; for (size_t l=tranz; l>0u; --l, ++Y) { *Y = 0.0; } //in case transient Y -= tranz; if (LAPACKE_dlasrt_work('D',(int)L,Y)) { fprintf(stderr,"error in rms_scale_d: problem with LAPACKE function\n"); } rms = sqrt(*Y); scalemx = (rms>DBL_EPSILON) ? max_RMS/rms : 1.0; rms = sqrt(*(Y+rms_p)); scale = (rms>DBL_EPSILON) ? target_RMS/rms : 1.0; scale = (scale<scalemx) ? scale : scalemx; for (size_t l=L; l>0u; --l) { X-=K; *X *= scale; } } } } } free(Y); } return 0; } #ifdef __cplusplus } } #endif
{ "alphanum_fraction": 0.4607032058, "avg_line_length": 44.976744186, "ext": "c", "hexsha": "684e7f30350a9ed18b2a14755d7c1b24505b59aa", "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": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "erikedwards4/aud", "max_forks_repo_path": "c/rms_scale.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b", "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": "erikedwards4/aud", "max_issues_repo_path": "c/rms_scale.c", "max_line_length": 220, "max_stars_count": null, "max_stars_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "erikedwards4/aud", "max_stars_repo_path": "c/rms_scale.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3167, "size": 9670 }
// THE VIRTUAL BRAIN -- C // A fast implementation of TVB-style brain network models based on // DYNAMIC MEAN FIELD MODEL Deco et al. 2014 Journal of Neuroscience // // m.schirner@fu-berlin.de // michael.schirner@charite.de // // MIT LICENSE // Copyright 2020 Michael Schirner // // 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 <stdio.h> #include <xmmintrin.h> #include <emmintrin.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <math.h> #include <pthread.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> //#include <semaphore.h> /* Definition of pthread barrier -- since OSX doesn't seem to have it */ typedef int pthread_barrierattr_t; typedef struct { pthread_mutex_t mutex; pthread_cond_t cond; int count; int tripCount; } pthread_barrier_t; int pthread_barrier_init(pthread_barrier_t *barrier, const pthread_barrierattr_t *attr, unsigned int count) { if(count == 0) { //errno = EINVAL; return -1; } if(pthread_mutex_init(&barrier->mutex, 0) < 0) { return -1; } if(pthread_cond_init(&barrier->cond, 0) < 0) { pthread_mutex_destroy(&barrier->mutex); return -1; } barrier->tripCount = count; barrier->count = 0; return 0; } int pthread_barrier_destroy(pthread_barrier_t *barrier) { pthread_cond_destroy(&barrier->cond); pthread_mutex_destroy(&barrier->mutex); return 0; } int pthread_barrier_wait(pthread_barrier_t *barrier) { pthread_mutex_lock(&barrier->mutex); ++(barrier->count); if(barrier->count >= barrier->tripCount) { barrier->count = 0; pthread_cond_broadcast(&barrier->cond); pthread_mutex_unlock(&barrier->mutex); return 1; } else { pthread_cond_wait(&barrier->cond, &(barrier->mutex)); pthread_mutex_unlock(&barrier->mutex); return 0; } } /* End: Definition of pthread barrier */ pthread_mutex_t mutex_thrcount; struct Xi_p{ float **Xi_elems; }; struct SC_capS{ float *cap; }; struct SC_inpregS{ int *inpreg; }; pthread_barrier_t mybarrier_base, mybarrier1, mybarrier2, mybarrier3; #define REAL float //#define REAL double int divRoundClosest(const int n, const int d) { return ((n < 0) ^ (d < 0)) ? ((n - d/2)/d) : ((n + d/2)/d); } int divRoundUp(const int x, const int y) { return (x + y - 1) / y; } /* Compute Pearson's correlation coefficient */ float corr(float *x, float *y, int n){ int i; float mx=0, my=0; /* Calculate the mean of the two series x[], y[] */ for (i=0; i<n; i++) { mx += x[i]; my += y[i]; } mx /= n; my /= n; /* Calculate the correlation */ float sxy = 0, sxsq = 0, sysq = 0, tmpx, tmpy; for (i=0; i<n; i++) { tmpx = x[i] - mx; tmpy = y[i] - my; sxy += tmpx*tmpy; sxsq += tmpx*tmpx; sysq += tmpy*tmpy; } return (sxy / (sqrt(sxsq)*sqrt(sysq))); } //float gaussrand_ret() //{ // static double V1=0.0, V2=0.0, S=0.0, U1=0.0, U2=0.0; // S=0.0; // do { // U1 = (double)rand() / RAND_MAX; // U2 = (double)rand() / RAND_MAX; // V1 = 2 * U1 - 1; // V2 = 2 * U2 - 1; // S = V1 * V1 + V2 * V2; // } while(S >= 1 || S == 0); // // return (float)(V1 * sqrt(-2 * log(S) / S)); //} // //static inline void gaussrand(float *randnum) //{ // static double V1=0.0, V2=0.0, S=0.0, U1=0.0, U2=0.0; // // S=0.0; // do { // U1 = (double)rand() / RAND_MAX; // U2 = (double)rand() / RAND_MAX; // V1 = 2 * U1 - 1; // V2 = 2 * U2 - 1; // S = V1 * V1 + V2 * V2; // } while(S >= 1 || S == 0); // // randnum[0] = (float)(V1 * sqrt(-2 * log(S) / S)); // randnum[1] = (float)(V2 * sqrt(-2 * log(S) / S)); // // S=0.0; // do { // U1 = (double)rand() / RAND_MAX; // U2 = (double)rand() / RAND_MAX; // V1 = 2 * U1 - 1; // V2 = 2 * U2 - 1; // S = V1 * V1 + V2 * V2; // } while(S >= 1 || S == 0); // // randnum[2] = (float)(V1 * sqrt(-2 * log(S) / S)); // randnum[3] = (float)(V2 * sqrt(-2 * log(S) / S)); //} int importGlobalConnectivity(char *SC_cap_filename, char *SC_dist_filename, char *SC_inputreg_filename, int regions, float **region_activity, struct Xi_p **reg_globinp_p, float global_trans_v, int **n_conn_table, float G_J_NMDA, struct SC_capS **SC_cap, float **SC_rowsums, struct SC_inpregS **SC_inpreg) { int i,j,k, maxdelay=0, tmpint; float *region_activity_p; double tmp, tmp2; struct Xi_p *reg_globinp_pp; struct SC_capS *SC_capp; struct SC_inpregS *SC_inpregp; // Open SC files FILE *file_cap, *file_dist; file_cap=fopen(SC_cap_filename, "r"); file_dist=fopen(SC_dist_filename, "r"); if (file_cap==NULL || file_dist==NULL) { printf( "\nERROR: Could not open SC files. Terminating... \n\n"); exit(0); } // Allocate a counter that stores number of region input connections for each region and the SCcap array *SC_rowsums = (float *)_mm_malloc(regions*sizeof(float),16); *n_conn_table = (int *)_mm_malloc(regions*sizeof(int),16); *SC_cap = (struct SC_capS *)_mm_malloc(regions*sizeof(struct SC_capS),16); SC_capp = *SC_cap; *SC_inpreg = (struct SC_inpregS *)_mm_malloc(regions*sizeof(struct SC_inpregS),16); SC_inpregp = *SC_inpreg; if(*n_conn_table==NULL || SC_capp==NULL || SC_rowsums==NULL || SC_inpregp==NULL){ printf("Running out of memory. Terminating.\n");fclose(file_dist);fclose(file_cap);exit(2); } // Read out the maximal fiber length and the degree of each node and rewind SC files int n_entries = 0, curr_col = 0, curr_row = 0, curr_row_nonzero = 0; double tmp_max = -9999; while(fscanf(file_dist,"%lf",&tmp) != EOF && fscanf(file_cap,"%lf",&tmp2) != EOF){ if (tmp_max < tmp) tmp_max = tmp; n_entries++; if (tmp2 > 0.0) curr_row_nonzero++; curr_col++; if (curr_col == regions) { curr_col = 0; (*n_conn_table)[curr_row] = curr_row_nonzero; curr_row_nonzero = 0; curr_row++; } } if (n_entries < regions * regions) { printf( "ERROR: Unexpected end-of-file in file. File contains less input than expected. Terminating... \n"); exit(0); } rewind(file_dist); rewind(file_cap); maxdelay = (int)(((tmp_max/global_trans_v)*10)+0.5); // *10 for getting from m/s to 10kHz sampling, +0.5 for rounding by casting if (maxdelay < 1) maxdelay = 1; // Case: no time delays // Allocate ringbuffer that contains region activity for each past time-step until maxdelay and another ringbuffer that contains pointers to the first ringbuffer *region_activity = (float *)_mm_malloc(maxdelay*regions*sizeof(float),16); region_activity_p = *region_activity; *reg_globinp_p = (struct Xi_p *)_mm_malloc(maxdelay*regions*sizeof(struct Xi_p),16); reg_globinp_pp = *reg_globinp_p; if(region_activity_p==NULL || reg_globinp_p==NULL){ printf("Running out of memory. Terminating.\n");fclose(file_dist);exit(2); } for (j=0; j<maxdelay*regions; j++) { region_activity_p[j]=0.001; } // Read SC files and set pointers for each input region and correspoding delay for each ringbuffer time-step int ring_buff_position; for (i=0; i<regions; i++) { if ((*n_conn_table)[i] > 0) { // SC strength and inp region numbers SC_capp[i].cap = (float *)_mm_malloc(((*n_conn_table)[i])*sizeof(float),16); SC_inpregp[i].inpreg = (int *)_mm_malloc(((*n_conn_table)[i])*sizeof(int),16); if(SC_capp[i].cap==NULL || SC_inpregp[i].inpreg==NULL){ printf("Running out of memory. Terminating.\n");exit(2); } // Allocate memory for input-region-pointer arrays for each time-step in ringbuffer for (j=0; j<maxdelay; j++){ reg_globinp_pp[i+j*regions].Xi_elems=(float **)_mm_malloc(((*n_conn_table)[i])*sizeof(float *),16); if(reg_globinp_pp[i+j*regions].Xi_elems==NULL){ printf("Running out of memory. Terminating.\n");exit(2); } } float sum_caps=0.0; // Read incoming connections and set pointers curr_row_nonzero = 0; for (j=0; j<regions; j++) { if(fscanf(file_cap,"%lf",&tmp) != EOF && fscanf(file_dist,"%lf",&tmp2) != EOF){ if (tmp > 0.0) { tmpint = (int)(((tmp2/global_trans_v)*10)+0.5); // *10 for getting from m/s or mm/ms to 10kHz sampling, +0.5 for rounding by casting if (tmpint < 0 || tmpint > maxdelay){ printf( "\nERROR: Negative or too high (larger than maximum specified number) connection length/delay %d -> %d. Terminating... \n\n",i,j);exit(0); } if (tmpint <= 0) tmpint = 1; // If time delay is smaller than integration step size, than set time delay to one integration step SC_capp[i].cap[curr_row_nonzero] = (float)tmp * G_J_NMDA; //sum_caps += (float)tmp; sum_caps += SC_capp[i].cap[curr_row_nonzero]; SC_inpregp[i].inpreg[curr_row_nonzero] = j; ring_buff_position=maxdelay*regions - tmpint*regions + j; for (k=0; k<maxdelay; k++) { reg_globinp_pp[i+k*regions].Xi_elems[curr_row_nonzero]=&region_activity_p[ring_buff_position]; ring_buff_position += regions; if (ring_buff_position > (maxdelay*regions-1)) ring_buff_position -= maxdelay*regions; } curr_row_nonzero++; } } else{ printf( "\nERROR: Unexpected end-of-file in file %s or %s. File contains less input than expected. Terminating... \n\n", SC_cap_filename, SC_dist_filename); exit(0); } } if (sum_caps <= 0) { printf( "\nERROR: Sum of connection strenghts is negative or zero. sum-caps node %d = %f. Terminating... \n\n",i,sum_caps);exit(0); } (*SC_rowsums)[i] = sum_caps; } } fclose(file_dist);fclose(file_cap); return maxdelay; } /* Initialize thread barriers */ void initialize_thread_barriers(int n_threads) { pthread_barrier_init(&mybarrier1, NULL, n_threads); pthread_barrier_init(&mybarrier2, NULL, n_threads); pthread_barrier_init(&mybarrier3, NULL, n_threads); return; } /* create thread argument struct for thr_func() */ typedef struct _thread_data_t { int tid, rand_num_seed; int nodes, nodes_vec, fake_nodes, n_threads, vectorization_grade, time_steps, BOLD_TR, BOLD_ts_len; float *J_i; int reg_act_size; float *region_activity; float model_dt; __m128 _gamma; __m128 _one; __m128 _imintau_E; __m128 _dt; __m128 _sigma_sqrt_dt; __m128 _sigma; __m128 _gamma_I; __m128 _imintau_I; __m128 _min_d_I; __m128 _b_I; __m128 _J_NMDA; __m128 _w_I__I_0; __m128 _a_I; __m128 _min_d_E; __m128 _b_E; __m128 _a_E; __m128 _w_plus_J_NMDA; __m128 _w_E__I_0; struct SC_capS *SC_cap; struct SC_inpregS *SC_inpreg; struct Xi_p *reg_globinp_p; int *n_conn_table; float *BOLD_ex; char *output_file; } thread_data_t; /* Function for multi-threaded FIC tuning */ void *run_simulation(void *arg) { /* Local function parameters (no concurrency) */ int j, i_node_vec, i_node_vec_local, k, int_i, ts; float tmpglobinput, tmpglobinput_FFI; __m128 _tmp_H_E, _tmp_H_I, _tmp_I_I, _tmp_I_E; float tmp_exp_E[4] __attribute__((aligned(16))); float tmp_exp_I[4] __attribute__((aligned(16))); __m128 *_tmp_exp_E = (__m128*)tmp_exp_E; __m128 *_tmp_exp_I = (__m128*)tmp_exp_I; float rand_number[4] __attribute__((aligned(16))); __m128 *_rand_number = (__m128*)rand_number; int ring_buf_pos = 0; /* Global function parameters (some with concurrency) */ thread_data_t *thr_data = (thread_data_t *)arg; //printf("Hello from thread %d, process %d\n", thr_data->tid, thr_data->rank); int t_id = thr_data->tid; int rand_num_seed = thr_data->rand_num_seed; int nodes = thr_data->nodes; int fake_nodes = thr_data->fake_nodes; const int nodes_vec = thr_data->nodes_vec; int n_threads = thr_data->n_threads; int vectorization_grade = thr_data->vectorization_grade; int reg_act_size = thr_data->reg_act_size; int *n_conn_table = thr_data->n_conn_table; float *J_i = thr_data->J_i; float *region_activity = thr_data->region_activity; float *BOLD_ex = thr_data->BOLD_ex; const __m128 _gamma = thr_data->_gamma; const __m128 _one = thr_data->_one; const __m128 _imintau_E = thr_data->_imintau_E; const __m128 _dt = thr_data->_dt; const __m128 _sigma_sqrt_dt = thr_data->_sigma_sqrt_dt; const __m128 _gamma_I = thr_data->_gamma_I; const __m128 _imintau_I = thr_data->_imintau_I; const __m128 _min_d_I = thr_data->_min_d_I; const __m128 _b_I = thr_data->_b_I; const __m128 _J_NMDA = thr_data->_J_NMDA; const __m128 _w_I__I_0 = thr_data->_w_I__I_0; const __m128 _a_I = thr_data->_a_I; const __m128 _min_d_E = thr_data->_min_d_E; const __m128 _b_E = thr_data->_b_E; const __m128 _a_E = thr_data->_a_E; const __m128 _w_plus_J_NMDA = thr_data->_w_plus_J_NMDA; const __m128 _w_E__I_0 = thr_data->_w_E__I_0; struct SC_capS *SC_cap = thr_data->SC_cap; struct Xi_p *reg_globinp_p = thr_data->reg_globinp_p; int time_steps = thr_data->time_steps; int BOLD_TR = thr_data->BOLD_TR; float model_dt = thr_data->model_dt; int BOLD_ts_len = thr_data->BOLD_ts_len; /* Parallelism: divide work among threads */ int nodes_vec_mt = divRoundUp(nodes_vec, n_threads); int nodes_mt = nodes_vec_mt * vectorization_grade; int start_nodes_vec_mt = t_id * nodes_vec_mt; int start_nodes_mt = t_id * nodes_mt; int end_nodes_vec_mt = (t_id + 1) * nodes_vec_mt; int end_nodes_mt = (t_id + 1) * nodes_mt; int end_nodes_mt_glob = end_nodes_mt; // end_nodes_mt_glob may differ from end_nodes_mt in the last thread (fake-nodes vs nodes) /* Correct settings for last thread */ if (end_nodes_mt > nodes) { end_nodes_vec_mt = nodes_vec; end_nodes_mt = fake_nodes; end_nodes_mt_glob = nodes; nodes_mt = end_nodes_mt - start_nodes_mt; nodes_vec_mt = end_nodes_vec_mt - start_nodes_vec_mt; } printf("thread %d: start: %d end: %d size: %d\n", thr_data->tid, start_nodes_mt, end_nodes_mt, nodes_mt); /* Check whether splitting makes sense (i.e. each thread has something to do). Terminate if not. */ if (nodes_vec_mt <= 1) { printf("The splitting is ineffective (e.g. fewer nodes than threads or some threads have nothing to do). Use different numbers of threads. Terminating.\n"); exit(0); } /* Set up barriers */ if (t_id == 0) { initialize_thread_barriers(n_threads); } pthread_barrier_wait(&mybarrier_base); /* Initialize random number generator */ //const gsl_rng_type * T; gsl_rng *r = gsl_rng_alloc (gsl_rng_mt19937); gsl_rng_set (r, (t_id+rand_num_seed)); // Random number seed -- otherwise every node gets the same random nums srand((unsigned)(t_id+rand_num_seed)); // All threads float *meanFR = (float *)_mm_malloc(nodes_mt * sizeof(float),16); // summation array for mean firing rate over all threads float *meanFR_INH = (float *)_mm_malloc(nodes_mt * sizeof(float),16); // summation array for mean firing rate over all threads float *global_input = (float *)_mm_malloc(nodes_mt * sizeof(float),16); float *global_input_FFI = (float *)_mm_malloc(nodes_mt * sizeof(float),16); float *S_i_E = (float *)_mm_malloc(nodes_mt * sizeof(float),16); float *S_i_I = (float *)_mm_malloc(nodes_mt * sizeof(float),16); //float *r_i_E = (float *)_mm_malloc(nodes_mt * sizeof(float),16); //float *r_i_I = (float *)_mm_malloc(nodes_mt * sizeof(float),16); float *J_i_local = (float *)_mm_malloc(nodes_mt * sizeof(float),16); if (meanFR == NULL || meanFR_INH == NULL || global_input == NULL || global_input_FFI == NULL || S_i_E==NULL || S_i_I==NULL || J_i_local==NULL) { printf( "ERROR: Running out of memory. Aborting... \n"); exit(0); } // Cast to vector/SSE arrays __m128 *_meanFR = (__m128*)meanFR; __m128 *_meanFR_INH = (__m128*)meanFR_INH; __m128 *_global_input = (__m128*)global_input; __m128 *_global_input_FFI = (__m128*)global_input_FFI; __m128 *_S_i_E = (__m128*)S_i_E; __m128 *_S_i_I = (__m128*)S_i_I; //__m128 *_r_i_E = (__m128*)r_i_E; //__m128 *_r_i_I = (__m128*)r_i_I; __m128 *_J_i_local = (__m128*)J_i_local; //Balloon-Windkessel model parameters / arrays float rho = 0.34, alpha = 0.32, tau = 0.98, y = 1.0/0.41, kappa = 1.0/0.65; float V_0 = 0.02, k1 = 7 * rho, k2 = 2.0, k3 = 2 * rho - 0.2, ialpha = 1.0/alpha, itau = 1.0/tau, oneminrho = (1.0 - rho); float f_tmp; float *BOLD = (float *)_mm_malloc(nodes_mt * BOLD_ts_len * sizeof(float),16); // resulting BOLD data float *bw_x_ex = (float *)_mm_malloc(nodes_mt * sizeof(float),16); // State-variable 1 of BW-model (exc. pop.) float *bw_f_ex = (float *)_mm_malloc(nodes_mt * sizeof(float),16); // State-variable 2 of BW-model (exc. pop.) float *bw_nu_ex = (float *)_mm_malloc(nodes_mt * sizeof(float),16); // State-variable 3 of BW-model (exc. pop.) float *bw_q_ex = (float *)_mm_malloc(nodes_mt * sizeof(float),16); // State-variable 4 of BW-model (exc. pop.) //float *bw_x_in = (float *)_mm_malloc(nodes_mt * sizeof(float),16); // State-variable 1 of BW-model (inh. pop.) //float *bw_f_in = (float *)_mm_malloc(nodes_mt * sizeof(float),16); // State-variable 2 of BW-model (inh. pop.) //float *bw_nu_in = (float *)_mm_malloc(nodes_mt * sizeof(float),16); // State-variable 3 of BW-model (inh. pop.) //float *bw_q_in = (float *)_mm_malloc(nodes_mt * sizeof(float),16); // State-variable 4 of BW-model (inh. pop.) //if (bw_x_ex == NULL || bw_f_ex == NULL || bw_nu_ex==NULL || bw_q_ex==NULL || bw_x_in==NULL || bw_f_in==NULL || bw_nu_in==NULL || bw_q_in==NULL) {} if (bw_x_ex == NULL || bw_f_ex == NULL || bw_nu_ex==NULL || bw_q_ex==NULL) { printf( "ERROR: Running out of memory. Aborting... \n"); exit(0); } // Reset arrays and variables ring_buf_pos = 0; for (j = 0; j < nodes_mt; j++) { meanFR[j] = 0.0; meanFR_INH[j] = 0.0; global_input[j] = 0.00; global_input_FFI[j] = 0.00; S_i_E[j] = 0.00; S_i_I[j] = 0.00; J_i_local[j] = J_i[j+start_nodes_mt]; } if (t_id == 0) { for (j=0; j<reg_act_size; j++) { region_activity[j]=0.00; } } // Reset Balloon-Windkessel model parameters and arrays for (j = 0; j < nodes_mt; j++) { bw_x_ex[j] = 0.0; bw_f_ex[j] = 1.0; bw_nu_ex[j] = 1.0; bw_q_ex[j] = 1.0; //bw_x_in[j] = 0.0; //bw_f_in[j] = 1.0; //bw_nu_in[j] = 1.0; //bw_q_in[j] = 1.0; } /* Barrier: only start simulating when arrays were cleared */ pthread_barrier_wait(&mybarrier1); /* Simulation loop */ int ts_bold_i = 0; for (ts = 0; ts < time_steps; ts++) { if (t_id == 0){ printf("%.1f %% \r", ((float)ts / (float)time_steps) * 100.0f ); } // dt = 0.1 ms => 10 integration iterations per ms for (int_i = 0; int_i < 10; int_i++) { /* Barrier: only start integrating input when all other threads are finished copying their results to buffer */ pthread_barrier_wait(&mybarrier2); /* Compute global coupling */ i_node_vec_local = 0; for(j=start_nodes_mt; j<end_nodes_mt_glob; j++){ tmpglobinput = 0; tmpglobinput_FFI = 0; for (k=0; k<n_conn_table[j]; k++) { tmpglobinput += *reg_globinp_p[j+ring_buf_pos].Xi_elems[k] * SC_cap[j].cap[k]; //tmpglobinput_FFI += *reg_globinp_p[j+ring_buf_pos].Xi_elems[k] * SC_cap_FFI[j].cap[k]; } global_input[i_node_vec_local] = tmpglobinput; //global_input_FFI[i_node_vec_local] = tmpglobinput_FFI; i_node_vec_local++; } i_node_vec_local = 0; for (i_node_vec = start_nodes_vec_mt; i_node_vec < end_nodes_vec_mt; i_node_vec++) { // Excitatory population firing rate _tmp_I_E = _mm_sub_ps(_mm_mul_ps(_a_E,_mm_add_ps(_mm_add_ps(_w_E__I_0,_mm_mul_ps(_w_plus_J_NMDA, _S_i_E[i_node_vec_local])),_mm_sub_ps(_global_input[i_node_vec_local],_mm_mul_ps(_J_i_local[i_node_vec_local], _S_i_I[i_node_vec_local])))),_b_E); *_tmp_exp_E = _mm_mul_ps(_min_d_E, _tmp_I_E); tmp_exp_E[0] = tmp_exp_E[0] != 0 ? expf(tmp_exp_E[0]) : 0.9; tmp_exp_E[1] = tmp_exp_E[1] != 0 ? expf(tmp_exp_E[1]) : 0.9; tmp_exp_E[2] = tmp_exp_E[2] != 0 ? expf(tmp_exp_E[2]) : 0.9; tmp_exp_E[3] = tmp_exp_E[3] != 0 ? expf(tmp_exp_E[3]) : 0.9; _tmp_H_E = _mm_div_ps(_tmp_I_E, _mm_sub_ps(_one, *_tmp_exp_E)); _meanFR[i_node_vec_local] = _mm_add_ps(_meanFR[i_node_vec_local],_tmp_H_E); //_r_i_E[i_node_vec_local] = _tmp_H_E; // Inhibitory population firing rate _tmp_I_I = _mm_sub_ps(_mm_mul_ps(_a_I,_mm_sub_ps(_mm_add_ps(_mm_add_ps(_w_I__I_0,_global_input_FFI[i_node_vec_local]),_mm_mul_ps(_J_NMDA, _S_i_E[i_node_vec_local])), _S_i_I[i_node_vec_local])),_b_I); *_tmp_exp_I = _mm_mul_ps(_min_d_I, _tmp_I_I); tmp_exp_I[0] = tmp_exp_I[0] != 0 ? expf(tmp_exp_I[0]) : 0.9; tmp_exp_I[1] = tmp_exp_I[1] != 0 ? expf(tmp_exp_I[1]) : 0.9; tmp_exp_I[2] = tmp_exp_I[2] != 0 ? expf(tmp_exp_I[2]) : 0.9; tmp_exp_I[3] = tmp_exp_I[3] != 0 ? expf(tmp_exp_I[3]) : 0.9; _tmp_H_I = _mm_div_ps(_tmp_I_I, _mm_sub_ps(_one, *_tmp_exp_I)); _meanFR_INH[i_node_vec_local] = _mm_add_ps(_meanFR_INH[i_node_vec_local],_tmp_H_I); //_r_i_I[i_node_vec_local] = _tmp_H_I; //gaussrand(rand_number); rand_number[0] = (float)gsl_ran_gaussian(r, 1.0); rand_number[1] = (float)gsl_ran_gaussian(r, 1.0); rand_number[2] = (float)gsl_ran_gaussian(r, 1.0); rand_number[3] = (float)gsl_ran_gaussian(r, 1.0); _S_i_I[i_node_vec_local] = _mm_add_ps(_mm_add_ps(_mm_mul_ps(_sigma_sqrt_dt, *_rand_number),_S_i_I[i_node_vec_local]),_mm_mul_ps(_dt,_mm_add_ps(_mm_mul_ps(_imintau_I, _S_i_I[i_node_vec_local]),_mm_mul_ps(_tmp_H_I,_gamma_I)))); //gaussrand(rand_number); rand_number[0] = (float)gsl_ran_gaussian(r, 1.0); rand_number[1] = (float)gsl_ran_gaussian(r, 1.0); rand_number[2] = (float)gsl_ran_gaussian(r, 1.0); rand_number[3] = (float)gsl_ran_gaussian(r, 1.0); _S_i_E[i_node_vec_local] = _mm_add_ps(_mm_add_ps(_mm_mul_ps(_sigma_sqrt_dt, *_rand_number),_S_i_E[i_node_vec_local]),_mm_mul_ps(_dt, _mm_add_ps(_mm_mul_ps(_imintau_E, _S_i_E[i_node_vec_local]),_mm_mul_ps(_mm_mul_ps(_mm_sub_ps(_one, _S_i_E[i_node_vec_local]),_gamma),_tmp_H_E)))); i_node_vec_local++; } /* ensure that synaptic activity is within its boundaries */ for(j=0; j<nodes_mt; j++){ S_i_E[j] = S_i_E[j] >= 0.0 ? S_i_E[j] : 0.0; S_i_E[j] = S_i_E[j] <= 1.0 ? S_i_E[j] : 1.0; S_i_I[j] = S_i_I[j] >= 0.0 ? S_i_I[j] : 0.0; S_i_I[j] = S_i_I[j] <= 1.0 ? S_i_I[j] : 1.0; } /* Copy result of this thread into global region_activity buffer */ memcpy(&region_activity[ring_buf_pos+start_nodes_mt], S_i_E, nodes_mt*sizeof( float )); /* Shift region_activity ring-buffer start */ ring_buf_pos = ring_buf_pos<(reg_act_size-nodes) ? (ring_buf_pos+nodes) : 0; } /* Compute BOLD for that time-step (subsampled to 1 ms) */ for (j = 0; j < nodes_mt; j++) { bw_x_ex[j] = bw_x_ex[j] + model_dt * (S_i_E[j] - kappa * bw_x_ex[j] - y * (bw_f_ex[j] - 1.0)); f_tmp = bw_f_ex[j] + model_dt * bw_x_ex[j]; bw_nu_ex[j] = bw_nu_ex[j] + model_dt * itau * (bw_f_ex[j] - powf(bw_nu_ex[j], ialpha)); bw_q_ex[j] = bw_q_ex[j] + model_dt * itau * (bw_f_ex[j] * (1.0 - powf(oneminrho,(1.0/bw_f_ex[j]))) / rho - powf(bw_nu_ex[j],ialpha) * bw_q_ex[j] / bw_nu_ex[j]); bw_f_ex[j] = f_tmp; /* bw_x_in[j] = bw_x_in[j] + model_dt * (S_i_I[j] - kappa * bw_x_in[j] - y * (bw_f_in[j] - 1.0)); f_tmp = bw_f_in[j] + model_dt * bw_x_in[j]; bw_nu_in[j] = bw_nu_in[j] + model_dt * itau * (bw_f_in[j] - powf(bw_nu_in[j], ialpha)); bw_q_in[j] = bw_q_in[j] + model_dt * itau * (bw_f_in[j] * (1.0 - powf(oneminrho,(1.0/bw_f_in[j]))) / rho - powf(bw_nu_in[j],ialpha) * bw_q_in[j] / bw_nu_in[j]); bw_f_in[j] = f_tmp; */ } if (ts % BOLD_TR == 0) { for (j = 0; j < nodes_mt; j++) { BOLD[ts_bold_i + j * BOLD_ts_len] = 100 / rho * V_0 * (k1 * (1 - bw_q_ex[j]) + k2 * (1 - bw_q_ex[j]/bw_nu_ex[j]) + k3 * (1 - bw_nu_ex[j])); } ts_bold_i++; } } /* Copy results of this thread into shared memory buffer */ memcpy(&BOLD_ex[start_nodes_mt*BOLD_ts_len], BOLD, nodes_mt * BOLD_ts_len * sizeof( float )); /* Wait until other threads finished before writing out result */ pthread_barrier_wait(&mybarrier3); /* Write out fMRI time series */ if (t_id == 0){ FILE *FCout = fopen(thr_data->output_file, "w"); for (j = 0; j < nodes; j++) { for (k = 0; k < ts_bold_i; k++) { fprintf(FCout, "%.5f ",BOLD_ex[j*BOLD_ts_len + k]); } fprintf(FCout, "\n"); } fclose(FCout); } gsl_rng_free (r); pthread_exit(NULL); } /* Usage: tvbii <paramfile> <subject_id> */ int main(int argc, char *argv[]) { /* Check whether right number of arguments was passed to program call */ if (argc != 4 || atoi(argv[3]) <= 0) { printf("\nERROR: Invalid arguments.\n\nUsage: tvbii <paramset_file> <sub_id> <#threads>\n\nTerminating... \n\n"); printf("\nProvided arguments:\n"); int i; for (i=0; i<argc; i++) { printf("%s\n", argv[i]); } exit(0); } /* Get current time and do some initializations */ time_t start = time(NULL); int i, j; int n_threads = atoi(argv[3]); /* Global model and integration parameters */ const float dt = 0.1; // Integration step length dt = 0.1 ms const float sqrt_dt = sqrtf(dt);// Noise in the diffusion part scaled by sqrt of dt const float model_dt = 0.001; // Time-step of model (sampling-rate=1000 Hz) const int vectorization_grade = 4; // How many operations can be done simultaneously. Depends on CPU Architecture and available intrinsics. int time_steps = 667*1.94*1000; // Simulation length int nodes = 84; // Number of surface vertices; must be a multiple of vectorization grade int fake_nodes = 84; float global_trans_v = 1.0; // Global transmission velocity (m/s); Local time-delays can be ommited since smaller than integration time-step float G = 0.5; // Global coupling strength int BOLD_TR = 1940; // TR of BOLD data int rand_num_seed = 1403; /* Local model: DMF-Parameters from Deco et al. JNeuro 2014 */ float w_plus = 1.4; // local excitatory recurrence //float I_ext = 0; // External stimulation float J_NMDA = 0.15; // (nA) excitatory synaptic coupling //float J_i = 1.0; // 1 for no-FIC, !=1 for Feedback Inhibition Control const float a_E = 310; // (n/C) const float b_E = 125; // (Hz) const float d_E = 0.16; // (s) const float a_I = 615; // (n/C) const float b_I = 177; // (Hz) const float d_I = 0.087; // (s) const float gamma = 0.641/1000.0; // factor 1000 for expressing everything in ms const float tau_E = 100; // (ms) Time constant of NMDA (excitatory) const float tau_I = 10; // (ms) Time constant of GABA (inhibitory) float sigma = 0.00316228; // (nA) Noise amplitude const float I_0 = 0.382; // (nA) overall effective external input const float w_E = 1.0; // scaling of external input for excitatory pool const float w_I = 0.7; // scaling of external input for inhibitory pool const float gamma_I = 1.0/1000.0; // for expressing inhib. pop. in ms float tmpJi = 1.0; // Feedback inhibition J_i /* Read parameters from input file. Input file is a simple text file that contains one line with parameters and white spaces in between. */ FILE *file; char param_file[300];memset(param_file, 0, 300*sizeof(char)); snprintf(param_file, sizeof(param_file), "/input/%s",argv[1]); file=fopen(param_file, "r"); if (file==NULL){ printf( "\nERROR: Could not open file %s. Terminating... \n\n", param_file); exit(0); } if(fscanf(file,"%d",&nodes) != EOF && fscanf(file,"%f",&G) != EOF && fscanf(file,"%f",&J_NMDA) != EOF && fscanf(file,"%f",&w_plus) != EOF && fscanf(file,"%f",&tmpJi) != EOF && fscanf(file,"%f",&sigma) != EOF && fscanf(file,"%d",&time_steps) != EOF && fscanf(file,"%d",&BOLD_TR) != EOF && fscanf(file,"%f",&global_trans_v) != EOF && fscanf(file,"%d",&rand_num_seed) != EOF){ } else{ printf( "\nERROR: Unexpected end-of-file in file %s. File contains less input than expected. Terminating... \n\n", param_file); exit(0); } fclose(file); char output_file[300];memset(output_file, 0, 300*sizeof(char)); snprintf(output_file, sizeof(output_file), "/output/%s_%s_fMRI.txt",argv[2],argv[1]); /* Add fake regions to make region count a multiple of vectorization grade */ if (nodes % vectorization_grade != 0){ printf( "\nWarning: Specified number of nodes (%d) is not a multiple of vectorization degree (%d). Will add some fake nodes... \n\n", nodes, vectorization_grade); int remainder = nodes%vectorization_grade; if (remainder > 0) { fake_nodes = nodes + (vectorization_grade - remainder); } } else{ fake_nodes = nodes; } /* Initialize random number generator */ srand((unsigned)rand_num_seed); /* Derived parameters */ const float sigma_sqrt_dt = sqrt_dt * sigma; const int nodes_vec = fake_nodes/vectorization_grade; const float min_d_E = -1.0 * d_E; const float min_d_I = -1.0 * d_I; const float imintau_E = -1.0 / tau_E; const float imintau_I = -1.0 / tau_I; const float w_E__I_0 = w_E * I_0; const float w_I__I_0 = w_I * I_0; const float one = 1.0; const float w_plus__J_NMDA= w_plus * J_NMDA; const float G_J_NMDA = G * J_NMDA; float TR = (float)BOLD_TR / 1000; // (s) TR of fMRI data int BOLD_ts_len = time_steps / (TR / model_dt) + 1; // Length of BOLD time-series written to HDD /* Import and setup global and local connectivity */ int *n_conn_table; float *region_activity, *SC_rowsums; struct Xi_p *reg_globinp_p; struct SC_capS *SC_cap; struct SC_inpregS *SC_inpreg; char cap_file[300];memset(cap_file, 0, 300*sizeof(char)); snprintf(cap_file, sizeof(cap_file), "/input/%s_SC_weights.txt",argv[2]); char dist_file[300];memset(dist_file, 0, 300*sizeof(char)); snprintf(dist_file, sizeof(dist_file), "/input/%s_SC_distances.txt",argv[2]); char reg_file[300];memset(reg_file, 0, 300*sizeof(char)); snprintf(reg_file, sizeof(reg_file), "/input/%s_SC_regionids.txt",argv[2]); int maxdelay = importGlobalConnectivity(cap_file, dist_file, reg_file, nodes, &region_activity, &reg_globinp_p, global_trans_v, &n_conn_table, G_J_NMDA, &SC_cap, &SC_rowsums, &SC_inpreg); int reg_act_size = nodes * maxdelay; /* Initialize and/or cast to vector-intrinsics types for variables & parameters */ float *J_i = (float *)_mm_malloc(fake_nodes * sizeof(float),16); // (nA) inhibitory synaptic coupling float *BOLD_ex = (float *)_mm_malloc(nodes * BOLD_ts_len * sizeof(float),16); if (J_i == NULL || BOLD_ex == NULL) { printf( "ERROR: Running out of memory. Aborting... \n"); _mm_free(J_i);_mm_free(BOLD_ex); return 1; } // Initialize state variables / parameters for (j = 0; j < fake_nodes; j++) { J_i[j] = tmpJi; } const __m128 _dt = _mm_load1_ps(&dt); const __m128 _sigma_sqrt_dt = _mm_load1_ps(&sigma_sqrt_dt); const __m128 _w_plus_J_NMDA = _mm_load1_ps(&w_plus__J_NMDA); const __m128 _a_E = _mm_load1_ps(&a_E); const __m128 _b_E = _mm_load1_ps(&b_E); const __m128 _min_d_E = _mm_load1_ps(&min_d_E); const __m128 _a_I = _mm_load1_ps(&a_I); const __m128 _b_I = _mm_load1_ps(&b_I); const __m128 _min_d_I = _mm_load1_ps(&min_d_I); const __m128 _gamma = _mm_load1_ps(&gamma); const __m128 _gamma_I = _mm_load1_ps(&gamma_I); const __m128 _imintau_E = _mm_load1_ps(&imintau_E); const __m128 _imintau_I = _mm_load1_ps(&imintau_I); const __m128 _w_E__I_0 = _mm_load1_ps(&w_E__I_0); const __m128 _w_I__I_0 = _mm_load1_ps(&w_I__I_0); float tmp_sigma = sigma*dt;// pre-compute dt*sigma for the integration of sigma*randnumber in equations (9) and (10) of Deco2014 const __m128 _sigma = _mm_load1_ps(&tmp_sigma); const __m128 _one = _mm_load1_ps(&one); const __m128 _J_NMDA = _mm_load1_ps(&J_NMDA); /* Start multithread simulation */ /* Create threads */ pthread_barrier_init(&mybarrier_base, NULL, n_threads); pthread_t thr[n_threads]; thread_data_t thr_data[n_threads]; int rc; for (i = 0; i < n_threads; ++i) { thr_data[i].tid = i ; thr_data[i].n_threads = n_threads ; thr_data[i].vectorization_grade = vectorization_grade; thr_data[i].nodes = nodes ; thr_data[i].fake_nodes = fake_nodes ; thr_data[i].J_i = J_i ; thr_data[i].reg_act_size = reg_act_size ; thr_data[i].region_activity = region_activity ; thr_data[i]._gamma = _gamma ; thr_data[i]._one = _one ; thr_data[i]._imintau_E = _imintau_E ; thr_data[i]._dt = _dt ; thr_data[i]._sigma_sqrt_dt = _sigma_sqrt_dt ; thr_data[i]._sigma = _sigma ; thr_data[i]._gamma_I = _gamma_I ; thr_data[i]._imintau_I = _imintau_I ; thr_data[i]._min_d_I = _min_d_I ; thr_data[i]._b_I = _b_I ; thr_data[i]._J_NMDA = _J_NMDA ; thr_data[i]._w_I__I_0 = _w_I__I_0 ; thr_data[i]._a_I = _a_I ; thr_data[i]._min_d_E = _min_d_E ; thr_data[i]._b_E = _b_E ; thr_data[i]._a_E = _a_E ; thr_data[i]._w_plus_J_NMDA = _w_plus_J_NMDA ; thr_data[i]._w_E__I_0 = _w_E__I_0 ; thr_data[i].nodes_vec = nodes_vec ; thr_data[i].SC_cap = SC_cap ; thr_data[i].SC_inpreg = SC_inpreg ; thr_data[i].reg_globinp_p = reg_globinp_p ; thr_data[i].n_conn_table = n_conn_table ; thr_data[i].time_steps = time_steps ; thr_data[i].BOLD_TR = BOLD_TR ; thr_data[i].model_dt = model_dt ; thr_data[i].BOLD_ex = BOLD_ex ; thr_data[i].rand_num_seed = rand_num_seed ; thr_data[i].BOLD_ts_len = BOLD_ts_len ; thr_data[i].output_file = output_file ; if ((rc = pthread_create(&thr[i], NULL, run_simulation, &thr_data[i]))) { fprintf(stderr, "error: pthread_create, rc: %d\n", rc); return EXIT_FAILURE; } } /* block until all threads complete */ for (i = 0; i < n_threads; ++i) { pthread_join(thr[i], NULL); } printf("Threads finished. Back to main thread.\n"); printf("MT-TVBii finished. Execution took %.2f s for %d nodes. Goodbye!\n", (float)(time(NULL) - start), nodes); return 0; }
{ "alphanum_fraction": 0.5649822996, "avg_line_length": 41.0368159204, "ext": "c", "hexsha": "06667f8c61a2eb8b83a1890fe51f64efaa1408a0", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2021-03-22T10:35:45.000Z", "max_forks_repo_forks_event_min_datetime": "2020-03-02T12:52:56.000Z", "max_forks_repo_head_hexsha": "ea3f86d1941f2e68b9efe59d23969fedd82ce5f3", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "AmoghJohri/fast_tvb", "max_forks_repo_path": "step1_compile_C_code/tvbii_multicore.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ea3f86d1941f2e68b9efe59d23969fedd82ce5f3", "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": "AmoghJohri/fast_tvb", "max_issues_repo_path": "step1_compile_C_code/tvbii_multicore.c", "max_line_length": 463, "max_stars_count": 1, "max_stars_repo_head_hexsha": "ea3f86d1941f2e68b9efe59d23969fedd82ce5f3", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "AmoghJohri/fast_tvb", "max_stars_repo_path": "step1_compile_C_code/tvbii_multicore.c", "max_stars_repo_stars_event_max_datetime": "2020-08-18T21:34:39.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-18T21:34:39.000Z", "num_tokens": 11912, "size": 41242 }
#include <stdio.h> #include <gsl/gsl_ieee_utils.h> int main() { //gsl_ieee_printf_double double a = 1.1; while (a > 0){ gsl_ieee_printf_double(&a); printf("\r\n"); a /= 2.0; } float b = 1.1; while (b > 0){ gsl_ieee_printf_float(&b); printf("\r\n"); b /= 2.0; } return 0; }
{ "alphanum_fraction": 0.4845070423, "avg_line_length": 16.9047619048, "ext": "c", "hexsha": "5835e2acede52d0765f4bb3425797b0a40709dfa", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-12-13T10:05:17.000Z", "max_forks_repo_forks_event_min_datetime": "2018-12-13T10:05:17.000Z", "max_forks_repo_head_hexsha": "0d63eea12291789800df29b23bda0772f6af6695", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kamilok1965/CMfSaT", "max_forks_repo_path": "lab_1/main.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0d63eea12291789800df29b23bda0772f6af6695", "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": "kamilok1965/CMfSaT", "max_issues_repo_path": "lab_1/main.c", "max_line_length": 35, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0d63eea12291789800df29b23bda0772f6af6695", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kamilok1965/CMfSaT", "max_stars_repo_path": "lab_1/main.c", "max_stars_repo_stars_event_max_datetime": "2019-01-09T18:59:11.000Z", "max_stars_repo_stars_event_min_datetime": "2019-01-09T18:59:11.000Z", "num_tokens": 119, "size": 355 }
#ifndef alphas_H_INCLUDED #define alphas_H_INCLUDED //for fixed alpha //#define g2 (4.6) #include <gsl/gsl_spline.h> //http://pdg.lbl.gov/2010/reviews/rpp2010-rev-qcd.pdf #define Mz 91.1876 #define LamQCD 0.217 //fixednf = 0 for nf(mu) #define fixednf 3 //extrapolates below mu0*LamQCD to value of (mu0-1.0)*LamQCD at mu=0 #define mu0 4. #define pi 3.14159265359 #define Nc (3.) #define Cf ((Nc*Nc-1.)/(2.*Nc)) void TabulateAlpha(); double alpha(double mu); double nf(double mu); double alpha_b0(double nf); double alpha_b1(double nf); double alpha_b2(double nf); double alpha_s0(double mu); double alpha_s1(double mu); double alpha_s2(double mu); gsl_interp_accel *accAlpha; gsl_spline *Alpha; #endif
{ "alphanum_fraction": 0.7366197183, "avg_line_length": 19.7222222222, "ext": "h", "hexsha": "e644cee18e7d6d34626927a30387bfd1c5d4b8fa", "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": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kdusling/mpc", "max_forks_repo_path": "src/alphas.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "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": "kdusling/mpc", "max_issues_repo_path": "src/alphas.h", "max_line_length": 68, "max_stars_count": null, "max_stars_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kdusling/mpc", "max_stars_repo_path": "src/alphas.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 235, "size": 710 }
#if !defined (RAND_H) #define RAND_H #include <cstdlib> #include <iostream> #include <cmath> #include <vector> #include <list> #include <set> #include <limits> #include <algorithm> #include <gsl/gsl_sf_zeta.h> using namespace std; const double TOLERANCE = numeric_limits<double>::epsilon(); const int INTMAX = numeric_limits<int>::max(); const int BIGPRIME = 899999963; const double PI = 3.1415926535897932384626433832795028841971693993751; typedef double (*FUNC)(const double, const double, const double); inline double fx(const double htilde, const double y, const double u) { return (pow(htilde,y+1) - (y+1)*htilde + fabs(2*u-1)*y); } inline int Getnode(list<int>& X, int index) { int pos=0; for(list<int>::iterator p = X.begin(); p!= X.end(); p++, pos++) { if(pos==index) return (*p); } return -1; } class Rand { double c,cd,cm,u[97]; int i97,j97 ; bool outputReady; double output; int idum; public: Rand(int seed) { ranmarin(fabs(seed%BIGPRIME)); outputReady=false; idum=-1*seed; flag_setFvector = false; flag_setPvector = false; } Rand() { ranmarin(1); outputReady=false; idum=-1; flag_setFvector = false; flag_setPvector = false; } void seed(int seed) { ranmarin(fabs(seed%BIGPRIME)); outputReady=false; idum=-1*seed; flag_setFvector = false; flag_setPvector = false; } double ran() { return rand()/(double)RAND_MAX;} double uniform() { double uni; uni=u[i97]-u[j97]; if (uni<0.0) uni+=1.0; u[i97]=uni; if (--i97<0) i97=96; if (--j97<0) j97=96; c-=cd; if (c<0.0) c+=cm; uni-=c; if (uni<0.0) uni+=1.0; return(uni); } double ran1() { const int IA=16807,IM=2147483647,IQ=127773,IR=2836,NTAB=32; const int NDIV=(1+(IM-1)/NTAB); const double EPS=3.0e-16,AM=1.0/IM,RNMX=(1.0-EPS); static int iy=0; static vector<int> iv(NTAB); int j,k; double temp; if (idum <= 0 || !iy) { if (-idum < 1) idum=1; else idum = -idum; for (j=NTAB+7;j>=0;j--) { k=idum/IQ; idum=IA*(idum-k*IQ)-IR*k; if (idum < 0) idum += IM; if (j < NTAB) iv[j] = idum; } iy=iv[0]; } k=idum/IQ; idum=IA*(idum-k*IQ)-IR*k; if (idum < 0) idum += IM; j=iy/NDIV; iy=iv[j]; iv[j] = idum; if ((temp=AM*iy) > RNMX) return RNMX; else return temp; } int discrete(int min, int max) { int ret= (int)(floor(ran1()*(max+1-min)+min)); return ret; } void discrete(int min, int max, int& a, int& b) { a = (int)(floor(ran1()*(max+1-min)+min)); do { b = (int)(floor(ran1()*(max+1-min)+min)); } while (a==b); } void discrete(int min, int max, int& a, int& b, int& c) { a = (int)(floor(ran1()*(max+1-min)+min)); do { b = (int)(floor(ran1()*(max+1-min)+min)); } while (b==a); do { c = (int)(floor(ran1()*(max+1-min)+min)); } while (c==b || c==a); } void discrete(int min, int max, int& a, int& b, int& c, int& d) { a = (int)(floor(ran1()*(max+1-min)+min)); do { b = (int)(floor(ran1()*(max+1-min)+min)); } while (b==a); do { c = (int)(floor(ran1()*(max+1-min)+min)); } while (c==b || c==a); do { d = (int)(floor(ran1()*(max+1-min)+min)); } while (d==c || d==b || d==a); } void discrete(int min, int max, int n, set<int>& Set) { Set.clear(); for(int i=0; i<n; ) { int a = (int)(floor(ran1()*(max+1-min)+min)); if(Set.find(a)==Set.end()) { Set.insert(a); i++; } } } void discrete(int min, int max, int n, vector<int>& Vec) { set<int> Set; Vec.clear(); for(int i=0; i<n; ) { int a = (int)(floor(ran1()*(max+1-min)+min)); if(Set.find(a)==Set.end()) { Set.insert(a); Vec.push_back(a); i++; } } } int discrete_logbin(int xmin, int xmax) { double ratio = 1.15; if (xmin==0) xmin=1; int Nbins = (int)(floor(log(xmax/xmin)/log(ratio))) + 1; int i = discrete(0, Nbins-1); int a = xmin * pow(ratio, (double)i); int b = a*ratio; if(b>xmax) b = xmax; int x = discrete(a,b); return x; } void randomsubset(int N, int Nc, vector<int>& S) { list<int> Lbig; for(int i=0; i<N; i++) { Lbig.push_back(i); } int N0= N; int M = (2*Nc>N0) ? (N0-Nc) : Nc; list<int> Lsmall; for(int i=0; i<M; i++) { int index = discrete(0, N-1); int j = Getnode(Lbig, index); Lsmall.push_back(j); Lbig.remove(j); N--; } S.clear(); S.resize(Nc); if(2*Nc>N0) copy(Lbig.begin(), Lbig.end(), S.begin()); else copy(Lsmall.begin(), Lsmall.end(), S.begin()); } void randomsubset_knuth(int n, int m, vector<int>& S) { for (int i = 0; i < n; i++) if ((discrete(1,n) % (n-i)) < m) { S.push_back(i); m--; } } void randomsubset_shuf(int n, int m, vector<int>& S) { int i,j,t; vector<int> x(n); for (i = 0; i < n; i++) x[i] = i; for (i = 0; i < m; i++) { j = discrete(i, n-1); t = x[i]; x[i] = x[j]; x[j] = t; } sort(x.begin(), x.begin()+m); for (i = 0; i< m; i++) S.push_back(x[i]); } void randomsubset_shuffle(int n, int m, vector<int>& S) { vector<int> x(n); for(int i=0; i<n; i++) x[i] = i; random_shuffle(x.begin(), x.end()); for (int i=0; i<m; i++) S.push_back(x[i]); } double gaussian(double sd) { double v1,v2,Rsq,z; if(outputReady) { outputReady = false; return output; } do { v1=(uniform()*2.0)-1.0; v2=(uniform()*2.0)-1.0; Rsq=v1*v1+v2*v2; } while (Rsq>=1.0); z=sqrt(-2.0*log(Rsq)/Rsq); output = v1*z*sd; outputReady=true; return v2*z*sd; } double lorentzian(double sd) { double v1,v2,z; do { v2 = uniform(); v1 = 2.0 * uniform() - 1.0; } while ((v1*v1+v2*v2)>1.0); z = v2/v1; return sd*z/2.0; } double powerlaw_continuous(double alpha, double xmin) { return ( xmin*pow(1-ran1(), 1./(1-alpha) ) ); } double powerlaw_continuous_interval(double a, double beta) { return pow( (1- (1-ran1())*(1-pow(a, 1-beta))), 1/(1-beta) ); } int powerlaw_discrete_approximate(double alpha, double xmin) { double r = ran1(); int k = (int)( (xmin-0.5)*pow(1-r, 1./(1-alpha) ) + 0.5 ); if(k<0) { cout << 1-r << ',' << k << endl; k = INTMAX; } return k; } int powerlaw_discrete(double alpha, int xmin) { if(!flag_setPvector) SetPvector(alpha,xmin); double r = ran1(); int j = Findj(P, 1-r); return j; } int powerlaw_exponentialcutoff_discrete(double gamma, double kappa) { if(!flag_setPvector) SetPvector_SFEC(gamma, kappa); double r = ran1(); int j = Findj(P, 1-r); return j; } int arbitrary_discrete(vector<double>& CDF) { double r = ran1(); int j = Findj(CDF, r); return j+1; } int arbitrary_discrete(vector<long double>& CDF) { double r = ran1(); int j = Findj(CDF, r); return j+1; } double lognormal(double sd) { double v1,v2,Rsq,z; if(outputReady) { outputReady = false; return output; } do { v1=(ran1()*2.0)-1.0; v2=(ran1()*2.0)-1.0; Rsq=v1*v1+v2*v2; } while (Rsq>=1.0); z=sqrt(-2.0*log(Rsq)/Rsq); output = exp(v1*z*sd); outputReady=true; return exp(v2*z*sd); } double bimodal(double R) { return (ran1()>0.5) ? (R) : (-R); } double rectangular(double R) { return ((ran1()*2-1)*R); } double parabolic(double R) { double x = ran1(); int sign = (x>0.5) ? (-1) : (+1); double R2 = R*R; double R3 = R2*R; double q = 4*R3*(x-0.5); double p = -3*R2; double Disc = q*q/4. + p*p*p/27.; double r = R3; double theta = atan(sqrt(-Disc)/(-q/2.)); double ronethird = pow(r,1/3.); double h1 = sign * 2 * ronethird * cos(theta/3.); double h2 = sign * 2 * ronethird * cos((theta+2*PI)/3.); double h3 = sign * 2 * ronethird * cos((theta-2*PI)/3.); double y = 0; if(h1<R && h1>(-R)) y = h1; else if(h2<R && h2>(-R)) y = h2; else if(h3<R && h3>(-R)) y = h3; else cout << "range is wrong!"; return y; } double antiparabolic(double R) { double x = ran1(); int sign = (x>0.5) ? (+1) : (-1); double h = sign * pow(sign*(2*x-1),1./3.) * R; return h; } double DMI_lookuptable(double y, double R) { if(!flag_setFvector) SetFvector(y,R); double u = ran1(); int j = Findj(F, u); double h = -R + j*dh; return h; } double DMI(double y, double R) { double u = ran1(); int sign = (u>0.5) ? (+1) : (-1); const double hacc = 1e-12; double htilde = rtbis(&fx, y, u, 0, 1, hacc); double h = sign*htilde*R; return h; } int exponential(double kappa) { double u = ran1(); int k = -kappa * log(1-u); return k; } private: bool flag_setFvector; vector<double> F; double dh; double P_DMI(double h, double y, double R) { if(h<-R || h>R) return 0; else return (y+1)/(2*y*R)*(1-pow(fabs(h)/R,y)); } void SetFvector(double y, double R) { int N = 10000001; dh = R/(double)(N-1); F.resize(2*N-1,0); F[0] = 0; F[2*N-2] = 1 - F[0]; for(int i=1;i<N;i++) { double h1 = -R + i*dh; double h2 = h1 + dh; F[i] = F[i-1] + 0.5* (P_DMI(h1,y,R)+P_DMI(h2,y,R))*dh; F[2*N-2-i] = 1- F[i]; } flag_setFvector = true; } int Findj(vector<double>& xx, const double x) { int j,jl,jm,ju; int n=xx.size(); jl=-1; ju=n; bool ascnd = (xx[n-1] >= xx[0]); while (ju-jl > 1) { jm=(ju+jl) >> 1; if ((x >= xx[jm]) == ascnd) jl=jm; else ju=jm; } if (x == xx[0]) j=0; else if (x == xx[n-1]) j=n-2; else j=jl; return j; } int Findj(vector<long double>& xx, const double x) { int j,jl,jm,ju; int n=xx.size(); jl=-1; ju=n; bool ascnd = (xx[n-1] >= xx[0]); while (ju-jl > 1) { jm=(ju+jl) >> 1; if ((x >= xx[jm]) == ascnd) jl=jm; else ju=jm; } if (x == xx[0]) j=0; else if (x == xx[n-1]) j=n-2; else j=jl; return j; } double rtbis(FUNC func, const double y, const double u, const double x1, const double x2, const double xacc) { const int JMAX=40; int j; double dx,f,fmid,xmid,rtb; f=func(x1,y,u); fmid=func(x2,y,u); if (f*fmid >= 0.0) cout << "Root must be bracketed for bisection in rtbis\n"; rtb = f < 0.0 ? (dx=x2-x1,x1) : (dx=x1-x2,x2); for (j=0;j<JMAX;j++) { fmid=func(xmid=rtb+(dx *= 0.5),y,u); if (fmid <= 0.0) rtb=xmid; if (fabs(dx) < xacc || fmid == 0.0) return rtb; } cout << "Too many bisections in rtbis\n"; return 0.0; } void ranmarin(int ijkl) { int i,ii,j,jj,k,l,m ; double s,t ; int ij=ijkl/30082; int kl=ijkl-30082*ij; i=((ij/177)%177)+2 ; j=(ij%177)+2 ; k=((kl/169)%178)+1 ; l=kl%169 ; for (ii=0;ii<97;ii++) { s=0.0 ; t=0.5 ; for (jj=0;jj<24;jj++) { m=(((i*j)%179)*k)%179 ; i=j; j=k; k=m; l=(53*l+1)%169; if (((l*m)%64)>=32) s+=t; t*=0.5; } u[ii]=s; } c=362436.0/16777216.0; cd=7654321.0/16777216.0; cm=16777213.0/16777216.0; i97=96; j97=32; } bool flag_setPvector; vector<double> P; double Hzeta(double s, double q) { double sum = 0; double nterm = 0; int n; for(n=0; ;n++) { nterm = pow((n+q),-s); sum += nterm; if(fabs(nterm/sum) < TOLERANCE) break; } cout << "nmax= " << n << endl; return sum; } void SetPvector(double alpha, int xmin) { double a = gsl_sf_hzeta(alpha, xmin); int N = 10000000+xmin; P.resize(N,2); P[xmin] = 1; for(int i=xmin;i<N-1;i++) { P[i+1] = P[i] - 1/(pow((double)i,alpha)*a); } flag_setPvector = true; } double polylog(double s, double z) { double sum = 0; double zn = z; int nmax = 1; for(int n=1; ; n++) { double term = zn/pow((double)n,s); sum += term; zn *= z; if(term < TOLERANCE) { nmax = n; break; } } return sum; } void SetPvector_SFEC(double gamma, double kappa) { double enkappa= exp(-1/kappa); double C = polylog(gamma, enkappa); int N = 10000000; P.resize(N,2); P[1] = 1; double a = enkappa; for(int i=1;i<=N;i++) { P[i+1] = P[i] - pow((double)i,-gamma) * a/ C ; a *= enkappa; } flag_setPvector = true; } }; #endif
{ "alphanum_fraction": 0.4892594262, "avg_line_length": 15.4813953488, "ext": "h", "hexsha": "42ef13c82005d00f2dbebf40e7f59ec33ad6a560", "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": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "spxuw/RFIM", "max_forks_repo_path": "Source/Gadgets/Random/Rand.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "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": "spxuw/RFIM", "max_issues_repo_path": "Source/Gadgets/Random/Rand.h", "max_line_length": 110, "max_stars_count": null, "max_stars_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "spxuw/RFIM", "max_stars_repo_path": "Source/Gadgets/Random/Rand.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4818, "size": 13314 }
#ifndef GNUPLOT_H #define GNUPLOT_H #include <fstream> #include <gsl/gsl_vector.h> #include "constants.h" void writePlotData(gsl_vector *f, const std::string& filename); #endif // GNUPLOT_H
{ "alphanum_fraction": 0.7411167513, "avg_line_length": 13.1333333333, "ext": "h", "hexsha": "886c77362f2285385fbc2b82f3474bb7451d3537", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-03-27T14:41:25.000Z", "max_forks_repo_forks_event_min_datetime": "2019-04-27T00:23:35.000Z", "max_forks_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ichi-rika/glottal-inverse", "max_forks_repo_path": "inc/gnuplot.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "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": "ichi-rika/glottal-inverse", "max_issues_repo_path": "inc/gnuplot.h", "max_line_length": 63, "max_stars_count": 6, "max_stars_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ichi-rika/glottal-inverse", "max_stars_repo_path": "inc/gnuplot.h", "max_stars_repo_stars_event_max_datetime": "2021-05-26T16:22:08.000Z", "max_stars_repo_stars_event_min_datetime": "2019-01-24T17:01:28.000Z", "num_tokens": 54, "size": 197 }
/** * @file lapacke.h * @brief Header file to automatically handle Intel MKL or LAPACKE includes. * * `npypacke` can be linked with a reference LAPACKE implementation, OpenBLAS, * or Intel MKL, but Intel MKL uses a different header file, `mkl.h`, while * OpenBLAS uses the LAPACKE header `lapacke.h`. This file includes the correct * header file given an appropriate preprocessor macro is defined and defines * some types appropriately so that the user can simply write in terms of the * Intel MKL interface, whether or not Intel MKL is actually linked. */ #ifndef NPY_LPK_LAPACKE_H #define NPY_LPK_LAPACKE_H // if linking with Netlib LAPACKE #if defined(LAPACKE_INCLUDE) #include <lapacke.h> // define MKL_INT used in extension modules as in mkl.h #ifndef MKL_INT #define MKL_INT int #endif /* MKL_INT */ // else if linking with OpenBLAS CBLAS #elif defined(OPENBLAS_INCLUDE) #include <complex.h> #include <lapacke.h> // OpenBLAS has blasint typedef, so define MKL_INT using blasint. for LAPACKE // routines, should cast to lapack_int (same size as blasint in OpenBLAS) #ifndef MKL_INT #define MKL_INT blasint #endif /* MKL_INT */ // else if linking with Intel MKL LAPACKE implementation #elif defined(MKL_INCLUDE) #include <mkl.h> // else error, no LAPACKE includes specified #else // silence error squiggles in VS Code (__INTELLISENSE__ always defined) #ifndef __INTELLISENSE__ #error "no LAPACKE includes specified. try -D(LAPACKE|OPENBLAS|MKL)_INCLUDE" #endif /* __INTELLISENSE__ */ #endif // silence error squiggles in VS Code. use mkl.h since it also define MKL types #ifdef __INTELLISENSE__ #include <mkl.h> #endif /* __INTELLISENSE__ */ #endif /* NPY_LPK_LAPACKE_H */
{ "alphanum_fraction": 0.7668639053, "avg_line_length": 35.9574468085, "ext": "h", "hexsha": "cb8f60e00f70ced77061e06ef2f767df3d3f2a78", "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": "ff5f9932b19f82162bc0d9d46b341d42805f942b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "phetdam/numpy-lapacke-demo", "max_forks_repo_path": "npypacke/include/npypacke/lapacke.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ff5f9932b19f82162bc0d9d46b341d42805f942b", "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": "phetdam/numpy-lapacke-demo", "max_issues_repo_path": "npypacke/include/npypacke/lapacke.h", "max_line_length": 79, "max_stars_count": 1, "max_stars_repo_head_hexsha": "ff5f9932b19f82162bc0d9d46b341d42805f942b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "phetdam/npy_openblas_demo", "max_stars_repo_path": "npypacke/include/npypacke/lapacke.h", "max_stars_repo_stars_event_max_datetime": "2021-10-16T00:59:11.000Z", "max_stars_repo_stars_event_min_datetime": "2021-10-16T00:59:11.000Z", "num_tokens": 475, "size": 1690 }
#pragma once #include "SimpleEvaluator.h" #include "BooleanDAG.h" #include "Interface.h" #include "SuggestionGenerator.h" #include <map> #include <set> #ifndef _NOGSL #include <gsl/gsl_vector.h> #else #include "FakeGSL.h" #endif class SmartSuggestionGenerator1: public SuggestionGenerator { Interface* interf; BooleanDAG* dag; map<string, int>& ctrls; SimpleEvaluator* seval; const vector<vector<int>>& dependentInputs; const vector<vector<int>>& dependentCtrls; vector<int> inputsToAsserts; // TODO: this is pretty local hack int counter; public: SmartSuggestionGenerator1(BooleanDAG* _dag, Interface* _interface, map<string, int>& _ctrls, const vector<vector<int>>& _dependentInputs, const vector<vector<int>>& _dependentCtrls): dag(_dag), interf(_interface), ctrls(_ctrls), dependentInputs(_dependentInputs), dependentCtrls(_dependentCtrls) { seval = new SimpleEvaluator(*dag, ctrls); seval->setInputs(interf); counter = 0; inputsToAsserts.resize(dag->size(), -1); for (int i = 0; i < dag->size(); i++) { bool_node* n = (*dag)[i]; if (n->type == bool_node::ASSERT) { const auto& inputs = dependentInputs[i]; for (auto it = inputs.begin(); it != inputs.end(); ++it) { inputsToAsserts[*it] = i; } } } } pair<int, int> getSuggestion(const gsl_vector* state) { return make_pair(-1, 0); } pair<int, int> getUnsatSuggestion(const gsl_vector* state) { return make_pair(-1, 0); } set<bool_node*> getResponsibleNodes(bool_node* node) { Assert(node->type == bool_node::ASSERT, "dsfqhuopwqe"); set<bool_node*> responsibleNodes; vector<bool_node*> nodes; // queue nodes.push_back(node); while(nodes.size() > 0) { bool_node* n = nodes.back(); nodes.pop_back(); Assert(n->type == bool_node::LT || n->type == bool_node::ASSERT || n->type == bool_node::NOT || n->type == bool_node::AND || n->type == bool_node::OR, "Unexpected node type"); if (n->type == bool_node::LT) { responsibleNodes.insert(n); } if (n->type == bool_node::ASSERT || n->type == bool_node::NOT) { nodes.push_back(n->mother()); } if (n->type == bool_node::AND || n->type == bool_node::OR) { double dist = seval->d(n); double mdist = seval->d(n->mother()); double fdist = seval->d(n->father()); if (dist * mdist > 0.0) { nodes.push_back(n->mother()); } if (dist * fdist > 0.0) { nodes.push_back(n->father()); } } } return responsibleNodes; } virtual IClause* getConflictClause(int level, LocalState * state) { return NULL; } virtual SClause* getUnsatClause(const gsl_vector* state) { return NULL; } virtual SClause* getUnsatClause(const gsl_vector* state, const gsl_vector* initState) { return NULL; } vector<tuple<int, int, int>> getUnsatSuggestions(const gsl_vector* state) { vector<tuple<int, int, int>> suggestions; cout << "state: " << Util::print(state) << endl; seval->run(state); double minNegDist = GradUtil::MAXVAL; int minNegDistId = -1; for (int i = 0; i < dag->size(); i++) { bool_node* n = (*dag)[i]; if (n->type == bool_node::ASSERT) { double dist = seval->d(n); if (dist < 0.0) { if (dist < minNegDist) { minNegDist = dist; minNegDistId = n->id; } } } } cout << "MinNegNode: " << (*dag)[minNegDistId]->lprint() << " with error " << minNegDist << endl; /*cout << "python test.py " << counter++ << " \"" << Util::print(state) << "\" data.txt"; string assertMsg = ((ASSERT_node*)(*dag)[minNegDistId])->getMsg(); size_t start = assertMsg.find("("); if (start != string::npos) { size_t end = assertMsg.find(")"); cout << " \"" << assertMsg.substr(start, end - start + 1) << "\""; } const set<int>& inputConstraints = interface->getInputConstraints(); cout << " \""; for (auto it = inputConstraints.begin(); it != inputConstraints.end(); it++) { string line = to_string(dependentCtrls[*it][0]); string assertMsg = ((ASSERT_node*)(*dag)[inputsToAsserts[*it]])->getMsg(); string point = ""; size_t start = assertMsg.find("("); if (start != string::npos) { size_t end = assertMsg.find(")"); point = assertMsg.substr(start, end - start + 1); } cout << line << ":" << point << ":" << interface->getValue(*it) << ";" ; } cout << "\"" << endl;*/ map<int, int> ctrlsToScore; for (int i = 0; i < dag->size(); i++) { bool_node* n = (*dag)[i]; if (n->type == bool_node::ASSERT) { bool satisfied = seval->d(n) >= 0.0; const set<bool_node*>& responsibleNodes = getResponsibleNodes(n); for (auto it = responsibleNodes.begin(); it != responsibleNodes.end(); it++) { const vector<int>& ctrls = dependentCtrls[(*it)->id]; int cost = satisfied ? 1 : -1; for (int j = 0; j < ctrls.size(); j++) { if (ctrlsToScore.find(ctrls[j]) == ctrlsToScore.end()) { ctrlsToScore[ctrls[j]] = cost; } else { ctrlsToScore[ctrls[j]] += cost; } } } } } for (auto it = ctrlsToScore.begin(); it != ctrlsToScore.end(); it++) { cout << "(" << it->first << "," << it->second << "); "; } cout << endl; const set<bool_node*>& influentialInputs = getResponsibleNodes((*dag)[minNegDistId]); // this should be a subset of dependentInputs of minNegDistId vector<tuple<int, int, int>> s; for (auto it = influentialInputs.begin(); it != influentialInputs.end(); it++) { int inputId = (*it)->id; double inputDist = seval->d(*it); int val = inputDist >= 0.0 ? 0 : 1; const vector<int>& ctrls = dependentCtrls[inputId]; int cost = 0; for (int j = 0; j < ctrls.size(); j++) { if (ctrlsToScore.find(ctrls[j]) != ctrlsToScore.end()) { cost += ctrlsToScore[ctrls[j]]; } } s.push_back(make_tuple(cost, inputId, val)); cout << (*dag)[inputId]->lprint() << " " << seval->d((*dag)[inputId]) << " [" << Util::print(dependentCtrls[inputId]) << "] " << cost << endl; } sort(s.begin(), s.end()); reverse(s.begin(), s.end()); for (int k = 0; k < s.size(); k++) { int nodeid = get<1>(s[k]); if (!interf->hasValue(nodeid)) { suggestions.push_back(make_tuple(0, nodeid, get<2>(s[k]))); } } int lastIdx = suggestions.size() - 1; if (lastIdx > 0) { cout << "Suggesting " << ((*dag)[get<1>(suggestions[lastIdx])])->lprint() << " " << get<2>(suggestions[lastIdx]) << endl; } return suggestions; } };
{ "alphanum_fraction": 0.4991648465, "avg_line_length": 39.5076142132, "ext": "h", "hexsha": "0e5e3bef4e09fbdc36fb6eafea0d2f67d18a2cf5", "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/SuggestionGenerators/SmartSuggestionGenerator1.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/SuggestionGenerators/SmartSuggestionGenerator1.h", "max_line_length": 301, "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/SuggestionGenerators/SmartSuggestionGenerator1.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": 1917, "size": 7783 }
#include <assert.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include <asf.h> #include "asf_tiff.h" #include <gsl/gsl_math.h> #include <proj_api.h> #include "asf_jpeg.h" #include <png.h> #include "envi.h" #include "dateUtil.h" #include <time.h> #include "matrix.h" #include <asf_nan.h> #include <asf_endian.h> #include <asf_meta.h> #include <asf_export.h> #include <asf_raster.h> #include <float_image.h> #include <spheroids.h> #include <typlim.h> #include <netcdf.h> #define PGM_MAGIC_NUMBER "P5" #ifdef MAX_RGB #undef MAX_RGB #endif #define MAX_RGB 255 #define USHORT_MAX 65535 #ifdef OPT_STRIP_BYTES #undef OPT_STRIP_BYTES #endif #define OPT_STRIP_BYTES 8192 // If you change the BAND_ID_STRING here, make sure you make an identical // change in the import library ...the defs must match #define BAND_ID_STRING "Color Channel (Band) Contents in RGBA+ order" /* This constant is from the GeoTIFF spec. It basically means that the system which would normally be specified by the field (projected coordinate system, datum, ellipsoid, whatever), in instead going to be specified by more detailed low level tags. */ static const int user_defined_value_code = 32767; static char *t3_matrix[9] = {"T11.bin","T12_real.bin","T12_imag.bin", "T13_real.bin","T13_imag.bin","T22.bin", "T23_real.bin","T23_imag.bin","T33.bin"}; static char *t4_matrix[16] = {"T11.bin","T12_real.bin","T12_imag.bin", "T13_real.bin","T13_imag.bin","T14_real.bin", "T14_imag.bin","T22.bin","T23_real.bin", "T23_imag.bin","T24_real.bin","T24_imag.bin", "T33.bin","T34_real.bin","T34_imag.bin", "T44.bin"}; static char *c2_matrix[4] = {"C11.bin","C12_real.bin","C12_imag.bin", "C22.bin"}; static char *c3_matrix[9] = {"C11.bin","C12_real.bin","C12_imag.bin", "C13_real.bin","C13_imag.bin","C22.bin", "C23_real.bin","C23_imag.bin","C33.bin"}; static char *c4_matrix[16] = {"C11.bin","C12_real.bin","C12_imag.bin", "C13_real.bin","C13_imag.bin","C14_real.bin", "C14_imag.bin","C22.bin","C23_real.bin", "C23_imag.bin","C24_real.bin","C24_imag.bin", "C33.bin","C34_real.bin","C34_imag.bin", "C44.bin"}; static char *freeman2_decomposition[2] = {"Freeman2_Ground.bin","Freeman2_Vol.bin"}; static char *freeman3_decomposition[3] = {"Freeman_Dbl.bin","Freeman_Odd.bin","Freeman_Vol.bin"}; static char *vanZyl3_decomposition[3] = {"VanZyl3_Dbl.bin","VanZyl3_Odd.bin","VanZyl3_Vol.bin"}; static char *yamaguchi3_decomposition[3] = {"Yamaguchi3_Dbl.bin","Yamaguchi3_Odd.bin","Yamaguchi3_Vol.bin"}; static char *yamaguchi4_decomposition[4] = {"Yamaguchi4_Dbl.bin","Yamaguchi4_Hlx.bin","Yamaguchi4_Odd.bin", "Yamaguchi4_Vol.bin"}; static char *krogager_decomposition[3] = {"Krogager_Kd.bin","Krogager_Kh.bin","Krogager_Ks.bin"}; static char *touzi1_decomposition[3] = {"TSVM_alpha_s1.bin","TSVM_alpha_s2.bin","TSVM_alpha_s3.bin"}; static char *touzi2_decomposition[3] = {"TSVM_phi_s1.bin","TSVM_phi_s2.bin","TSVM_phi_s3.bin"}; static char *touzi3_decomposition[3] = {"TSVM_tau_m1.bin","TSVM_tau_m2.bin","TSVM_tau_m3.bin"}; static char *touzi4_decomposition[3] = {"TSVM_psi1.bin","TSVM_psi2.bin","TSVM_psi3.bin"}; static char *touzi5_decomposition[4] = {"TSVM_alpha_s.bin","TSVM_phi_s.bin","TSVM_tau_m.bin","TSVM_psi.bin"}; int is_slant_range(meta_parameters *md); void initialize_tiff_file (TIFF **otif, GTIF **ogtif, const char *output_file_name, const char *metadata_file_name, int is_geotiff, scale_t sample_mapping, int rgb, int *palette_color_tiff, char **band_names, char *look_up_table_name, int is_colormapped); GTIF* write_tags_for_geotiff (TIFF *otif, const char *metadata_file_name, int rgb, char **band_names, int palette_color_tiff); void finalize_tiff_file(TIFF *otif, GTIF *ogtif, int is_geotiff); void append_band_names(char **band_names, int rgb, char *citation, int have_look_up_table); int lut_to_tiff_palette(unsigned short **colors, int size, char *look_up_table_name); void dump_palette_tiff_color_map(unsigned short *colors, int map_size); int meta_colormap_to_tiff_palette(unsigned short **colors, int *byte_image, meta_colormap *colormap); char *sample_mapping2string(scale_t sample_mapping); void colormap_to_lut_file(meta_colormap *cm, const char *lut_file); static char *format2str(output_format_t format) { char *str = (char *) MALLOC(sizeof(char)*256); if (format == ENVI) strcpy(str, "ENVI"); else if (format == ESRI) strcpy(str, "ESRI"); else if (format == GEOTIFF) strcpy(str, "GEOTIFF"); else if (format == TIF) strcpy(str, "TIFF"); else if (format == JPEG) strcpy(str, "JPEG"); else if (format == PGM) strcpy(str, "PGM"); else if (format == PNG) strcpy(str, "PNG"); else if (format == PNG_ALPHA) strcpy(str, "PNG ALPHA"); else if (format == PNG_GE) strcpy(str, "PNG GOOGLE EARTH"); else if (format == KML) strcpy(str, "KML"); else if (format == POLSARPRO_HDR) strcpy(str, "POLSARPRO with ENVI header"); else if (format == HDF) strcpy(str, "HDF5"); else if (format == NC) strcpy(str, "netCDF"); else strcpy(str, MAGIC_UNSET_STRING); return str; } void initialize_tiff_file (TIFF **otif, GTIF **ogtif, const char *output_file_name, const char *metadata_file_name, int is_geotiff, scale_t sample_mapping, int rgb, int *palette_color_tiff, char **band_names, char *look_up_table_name, int is_colormapped) { unsigned short sample_size; int max_dn, map_size = 0, palette_color = 0; unsigned short rows_per_strip; unsigned short *colors = NULL; int have_look_up_table = look_up_table_name && strlen(look_up_table_name) > 0; _XTIFFInitialize(); // Open output tiff file *otif = XTIFFOpen (output_file_name, "w"); asfRequire(otif != NULL, "Error opening output TIFF file.\n"); /* Get the image metadata. */ meta_parameters *md = meta_read (metadata_file_name); int byte_image = (md->general->data_type == BYTE) || !(sample_mapping == NONE && !md->optical && !have_look_up_table); int int_image = (md->general->data_type == INTEGER16 && !md->optical && !have_look_up_table); if (!byte_image && !int_image) { // Float image asfRequire(sizeof (float) == 4, "Size of the unsigned char data type on this machine is " "different than expected.\n"); sample_size = 4; TIFFSetField(*otif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP); } else if (int_image) { sample_size = 2; TIFFSetField(*otif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT); } else { // Byte image asfRequire(sizeof(unsigned char) == 1, "Size of the unsigned char data type on this machine is " "different than expected.\n"); if (have_look_up_table) { // Get max DN from lut file and if it's greater than 255, then // the TIFF standard will not allow indexed color. if (sizeof(unsigned short) != 2) { // The TIFF standard requires an unsigned short to be 16 bits long asfPrintError("Size of the unsigned short integer data type on this machine (%d bytes) is " "different than expected (2 bytes).\n", sizeof(unsigned short)); } // Try #1 ...Try 2 bytes just to get past lut_to_tiff_palette() with no errors // ...More accurately, we are using lut_to_tiff_palette() to determine max_dn, the // minimum number of entries that the color table must have sample_size = 2; // Unsigned short ...2 bytes allows a color map 65535 elements long or smaller map_size = 1 << (sample_size * 8); // 2^bits_per_sample; max_dn = lut_to_tiff_palette(&colors, map_size, look_up_table_name); sample_size = 1; palette_color = 0; if (max_dn <= MAX_RGB) { sample_size = 1; map_size = 1 << (sample_size * 8); // 2^bits_per_sample; max_dn = lut_to_tiff_palette(&colors, map_size, look_up_table_name); palette_color = 1; } } else { // No look-up table, so the data is already 0-255 or will be resampled down to // the 0-255 range. Only need a 1-byte pixel... sample_size = 1; } // The sample format is 'unsigned integer', but the number of bytes per // sample, i.e. short, int, or long, is set by TIFFTAG_BITSPERSAMPLE below // which in turn is determined by the sample_size (in bytes) set above ;-) // Note that for color images, "bits per sample" refers to one color component, // not the group of 3 components. TIFFSetField(*otif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT); } // use the metadata's colormap if we have one. a -lut specified on the command // line will override, though (and in that case we should have already set // up the colormap via lut_to_tiff_palette()) if (is_colormapped && md->colormap && !have_look_up_table) { asfPrintStatus("\nFound single-band image with RGB color map ...storing as a Palette\n" "Color TIFF\n\n"); palette_color = 1; max_dn = map_size = meta_colormap_to_tiff_palette(&colors, &byte_image, md->colormap); } /* Set the normal TIFF image tags. */ TIFFSetField(*otif, TIFFTAG_SUBFILETYPE, 0); TIFFSetField(*otif, TIFFTAG_IMAGEWIDTH, md->general->sample_count); TIFFSetField(*otif, TIFFTAG_IMAGELENGTH, md->general->line_count); TIFFSetField(*otif, TIFFTAG_BITSPERSAMPLE, sample_size * 8); TIFFSetField(*otif, TIFFTAG_COMPRESSION, COMPRESSION_LZW); if ( (!have_look_up_table && rgb ) || ( have_look_up_table && !palette_color) ) { // Color RGB (no palette) image TIFFSetField(*otif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB); TIFFSetField(*otif, TIFFTAG_SAMPLESPERPIXEL, 3); } else if (byte_image && palette_color) { // Color Palette image TIFFSetField(*otif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE); TIFFSetField(*otif, TIFFTAG_SAMPLESPERPIXEL, 1); unsigned short *red, *green, *blue; asfRequire(colors != NULL, "Color map not allocated.\n"); asfRequire(map_size > 0, "Color map not initialized.\n"); red = colors; green = colors + map_size; blue = colors + 2*map_size; TIFFSetField(*otif, TIFFTAG_COLORMAP, red, green, blue); } else { // Else assume grayscale with minimum value (usually zero) means 'black' TIFFSetField(*otif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK); TIFFSetField(*otif, TIFFTAG_SAMPLESPERPIXEL, 1); } // Set rows per strip to 1, 4, 8, or 16 ...trying to set a near optimal 8k strip size // FIXME: Implement the creation of TIFFS with optimized number of rows per strip ...someday rows_per_strip = 1;//((OPT_STRIP_BYTES / (sample_size * md->general->sample_count)) < 4) ? 1 : //((OPT_STRIP_BYTES / (sample_size * md->general->sample_count)) < 8) ? 4 : //((OPT_STRIP_BYTES / (sample_size * md->general->sample_count)) < 16) ? 8 : //((OPT_STRIP_BYTES / (sample_size * md->general->sample_count)) < 32) ? 16 : // (unsigned short) USHORT_MAX; TIFFSetField(*otif, TIFFTAG_ROWSPERSTRIP, rows_per_strip); TIFFSetField(*otif, TIFFTAG_XRESOLUTION, 1.0); TIFFSetField(*otif, TIFFTAG_YRESOLUTION, 1.0); TIFFSetField(*otif, TIFFTAG_RESOLUTIONUNIT, RESUNIT_NONE); TIFFSetField(*otif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); if (is_geotiff) { *ogtif = write_tags_for_geotiff (*otif, metadata_file_name, rgb, band_names, palette_color); } if (should_write_insar_xml_meta(md)) { char *xml_meta = get_insar_xml_string(md, TRUE); TIFFSetField(*otif, TIFFTAG_ASF_INSAR_METADATA, xml_meta); FREE(xml_meta); } else if (should_write_dem_xml_meta(md)) { char *xml_meta = get_dem_xml_string(md, TRUE); TIFFSetField(*otif, TIFFTAG_ASF_DEM_METADATA, xml_meta); FREE(xml_meta); } *palette_color_tiff = palette_color; meta_free(md); } void initialize_png_file(const char *output_file_name, meta_parameters *meta, FILE **opng, png_structp *png_ptr, png_infop *info_ptr, int rgb) { return initialize_png_file_ext(output_file_name, meta, opng, png_ptr, info_ptr, rgb, FALSE); } void initialize_png_file_ext(const char *output_file_name, meta_parameters *meta, FILE **opng, png_structp *png_ptr, png_infop *info_ptr, int rgb, int alpha) { *opng = FOPEN(output_file_name, "wb"); *png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!(*png_ptr)) asfPrintError("Error creating PNG write structure!\n"); *info_ptr = png_create_info_struct(*png_ptr); if (!(*info_ptr)) asfPrintError("Error creating PNG info structure!\n"); png_init_io(*png_ptr, *opng); int width = meta->general->sample_count; int height = meta->general->line_count; png_byte color_type; if (alpha == 0) color_type = rgb ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_GRAY; else if (alpha == 1) { color_type = rgb ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_GRAY; int ii; if (rgb) { png_color_16 trans_rgb_value[256]; for (ii=0; ii<256; ii++) { trans_rgb_value[ii].red = 255; trans_rgb_value[ii].green = 255; trans_rgb_value[ii].blue = 255; } // setting black to transparent trans_rgb_value[0].red = 0; trans_rgb_value[0].green = 0; trans_rgb_value[0].blue = 0; png_set_tRNS(*png_ptr, *info_ptr, trans_rgb_value, 256, NULL); } else { png_byte trans_values[256]; for (ii=0; ii<256; ii++) trans_values[ii] = 255; trans_values[0] = 0; // setting black to transparent png_set_tRNS(*png_ptr, *info_ptr, trans_values, 256, NULL); } } else if (alpha == 2) color_type = PNG_COLOR_TYPE_RGB_ALPHA; png_set_IHDR(*png_ptr, *info_ptr, width, height, 8, color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_write_info(*png_ptr, *info_ptr); } void initialize_jpeg_file(const char *output_file_name, meta_parameters *meta, FILE **ojpeg, struct jpeg_compress_struct *cinfo, int rgb) { struct jpeg_error_mgr *jerr = MALLOC(sizeof(struct jpeg_error_mgr)); /* We need a version of the data in JSAMPLE form, so we have to map floats into JSAMPLEs. We do this by defining a region 2 sigma on either side of the mean to be mapped in the range of JSAMPLE linearly, and clamping everything outside this range at the limits o the JSAMPLE range. */ /* Here are some very funky checks to try to ensure that the JSAMPLE really is the type we expect, so we can scale properly. */ asfRequire(sizeof(unsigned char) == 1, "Size of the unsigned char data type on this machine is " "different than expected.\n"); asfRequire(sizeof(unsigned char) == sizeof (JSAMPLE), "Size of unsigned char data type on this machine is different " "than JPEG byte size.\n"); JSAMPLE test_jsample = 0; test_jsample--; asfRequire(test_jsample == UCHAR_MAX, "Something wacky happened, like data overflow.\n"); // Initializae libjpg structures. cinfo->err = jpeg_std_error (jerr); jpeg_create_compress (cinfo); // Open the output file to be used. *ojpeg = FOPEN(output_file_name, "wb"); // Connect jpeg output to the output file to be used. jpeg_stdio_dest (cinfo, *ojpeg); // Set image parameters that libjpeg needs to know about. cinfo->image_width = meta->general->sample_count; cinfo->image_height = meta->general->line_count; if (rgb) { cinfo->in_color_space = JCS_RGB; cinfo->input_components = 3; } else { cinfo->in_color_space = JCS_GRAYSCALE; cinfo->input_components = 1; } jpeg_set_defaults (cinfo); // Use default compression parameters. jpeg_set_quality(cinfo, 100, 1); // Reassure libjpeg that we will be writing a complete JPEG file. jpeg_start_compress (cinfo, TRUE); return; } void initialize_pgm_file(const char *output_file_name, meta_parameters *meta, FILE **opgm) { const int max_color_value = 255; *opgm = FOPEN (output_file_name, "w"); fprintf (*opgm, "%s\n", PGM_MAGIC_NUMBER); fprintf (*opgm, "%ld\n", (long int) meta->general->sample_count); fprintf (*opgm, "%ld\n", (long int) meta->general->line_count); fprintf (*opgm, "%d\n", max_color_value); return; } void initialize_polsarpro_file(const char *output_file_name, meta_parameters *meta, FILE **ofp) { *ofp = FOPEN(output_file_name, "wb"); char *output_header_file_name = (char *) MALLOC(sizeof(char) * strlen(output_file_name) + 5); sprintf(output_header_file_name, "%s.hdr", output_file_name); char *band_name = get_filename(output_file_name); envi_header *envi = meta2envi(meta); envi->bands = 1; char *band = stripExt(band_name); strcpy(envi->band_name, band_name); envi->byte_order = 0; // PolSARPro data is little endian by default write_envi_header(output_header_file_name, output_file_name, meta, envi); FREE(output_header_file_name); FREE(band_name); FREE(band); FREE(envi); return; } GTIF* write_tags_for_geotiff (TIFF *otif, const char *metadata_file_name, int rgb, char **band_names, int palette_color_tiff) { /* Get the image metadata. */ meta_parameters *md = meta_read (metadata_file_name); int map_projected = is_map_projected(md); int is_slant_range_image = is_slant_range(md); GTIF *ogtif; /* Semi-major and -minor ellipse axis lengths. This shows up in two different places in our metadata, we want the projected one if its available, otherwise the one from general. */ double re_major, re_minor; asfRequire (sizeof (unsigned short) == 2, "Unsigned short integer data type size is different than " "expected.\n"); asfRequire (sizeof (unsigned int) == 4, "Unsigned integer data type size is different than expected.\n"); if (!map_projected) { asfPrintWarning("Image is not map-projected or the projection type is\n" "unrecognized or unsupported.\n\n" "Exporting a non-geocoded, standard TIFF file instead...\n"); } if (is_slant_range_image) { asfPrintWarning("Image is either a SAR slant-range image or a ScanSAR\n" "along-track/cross-track projection. Exporting as a GeoTIFF is not\n" "supported for these types.\n\n" "Exporting a standard non-georeferenced/non-geocoded TIFF file instead...\n"); } /******************************************/ /* Set the GeoTIFF extension image tags. */ ogtif = GTIFNew (otif); asfRequire (ogtif != NULL, "Error opening output GeoKey file descriptor.\n"); // Common tags if (map_projected) { // Write common tags for map-projected GeoTIFFs GTIFKeySet (ogtif, GTRasterTypeGeoKey, TYPE_SHORT, 1, RasterPixelIsArea); if (md->projection->type != LAT_LONG_PSEUDO_PROJECTION) GTIFKeySet (ogtif, GTModelTypeGeoKey, TYPE_SHORT, 1, ModelTypeProjected); else GTIFKeySet (ogtif, GTModelTypeGeoKey, TYPE_SHORT, 1, ModelTypeGeographic); GTIFKeySet (ogtif, GeogLinearUnitsGeoKey, TYPE_SHORT, 1, Linear_Meter); GTIFKeySet (ogtif, GeogAngularUnitsGeoKey, TYPE_SHORT, 1, Angular_Degree); GTIFKeySet (ogtif, ProjLinearUnitsGeoKey, TYPE_SHORT, 1, Linear_Meter); GTIFKeySet (ogtif, GeogPrimeMeridianGeoKey, TYPE_SHORT, 1, PM_Greenwich); re_major = md->projection->re_major; re_minor = md->projection->re_minor; } else { // If not map-projected, then common tags are not written. If the file // is georeferenced however, then pixel scale and tie point will be // written below re_major = md->general->re_major; re_minor = md->general->re_minor; } // Pixel scale and tie points if (md->projection) { if (!(meta_is_valid_double(md->projection->startX) && meta_is_valid_double(md->projection->startY)) ) { asfPrintWarning("Metadata projection block contains invalid startX " "or startY values\n"); } // Write georeferencing data if (!is_slant_range_image) { double tie_point[6]; double pixel_scale[3]; // FIXME: Note that the following tie points are in meters, but that's // because we assume linear meters and a map-projected image. If we ever // export a geographic (lat/long) geotiff, then this code will need to // smarten-up and write the tie points in lat/long or meters depending on the // type of image data. Same thing applies to perX and perY etc etc. tie_point[0] = 0.0; tie_point[1] = 0.0; tie_point[2] = 0.0; // these are both meters tie_point[3] = md->projection->startX + md->general->start_sample * md->projection->perX; tie_point[4] = md->projection->startY + md->general->start_line * md->projection->perY; tie_point[5] = 0.0; TIFFSetField(otif, TIFFTAG_GEOTIEPOINTS, 6, tie_point); /* Set the scale of the pixels, in projection coordinates. */ if (md->projection->perX < 0.0) { asfPrintWarning("Unexpected non-positive perX in the " "projection block.\n"); } else { pixel_scale[0] = fabs(md->projection->perX); } if (md->projection->perY > 0.0) { asfPrintWarning("Unexpected non-negative perY in the " "projection block.\n"); } else { pixel_scale[1] = fabs(md->projection->perY); pixel_scale[2] = 0; } TIFFSetField (otif, TIFFTAG_GEOPIXELSCALE, 3, pixel_scale); } } // Write geocode (map projection) parameters if (map_projected) { int max_citation_length = 2048; char *citation; int citation_length; // For now, only support the Hughes ellipsoid for polar stereo if (md->projection->datum == HUGHES_DATUM && md->projection->type != POLAR_STEREOGRAPHIC) { asfPrintError("Hughes Ellipsoid is only supported for Polar Stereographic projections.\n"); } /* Write the appropriate geotiff keys for the projection type. */ switch (md->projection->type) { case UNIVERSAL_TRANSVERSE_MERCATOR: { short pcs; if ( UTM_2_PCS(&pcs, md->projection->datum, md->projection->param.utm.zone, md->projection->hem) ) { GTIFKeySet (ogtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1, pcs); GTIFKeySet (ogtif, ProjectionGeoKey, TYPE_SHORT, 1, user_defined_value_code); GTIFKeySet (ogtif, ProjCoordTransGeoKey, TYPE_SHORT, 1, CT_TransverseMercator); if (meta_is_valid_double(md->projection->param.utm.false_easting)) { GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1, md->projection->param.utm.false_easting); } else { GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1, 0.0); } if (meta_is_valid_double(md->projection->param.utm.false_northing)) { GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1, md->projection->param.utm.false_northing); } else { GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1, 0.0); } if (meta_is_valid_double(md->projection->param.utm.lat0)) { GTIFKeySet (ogtif, ProjNatOriginLatGeoKey, TYPE_DOUBLE, 1, md->projection->param.utm.lat0); } if (meta_is_valid_double(md->projection->param.utm.lon0)) { GTIFKeySet (ogtif, ProjNatOriginLongGeoKey, TYPE_DOUBLE, 1, md->projection->param.utm.lon0); } GTIFKeySet (ogtif, ProjScaleAtNatOriginGeoKey, TYPE_DOUBLE, 1, md->projection->param.utm.scale_factor); write_datum_key(ogtif, md->projection->datum); write_spheroid_key(ogtif, md->projection->spheroid, re_major, re_minor); // Write the citation char datum_str[256]; if (md->projection->datum == ITRF97_DATUM) { strcpy(datum_str, "ITRF97 (WGS 84)"); } else { pcs_2_string (datum_str, pcs); } citation = MALLOC ((max_citation_length + 1) * sizeof (char)); snprintf (citation, max_citation_length + 1, "UTM zone %d %c projected GeoTIFF on %s " "%s written by Alaska Satellite Facility tools.", md->projection->param.utm.zone, md->projection->hem, datum_str, md->projection->datum == HUGHES_DATUM ? "ellipsoid" : "datum"); append_band_names(band_names, rgb, citation, palette_color_tiff); citation_length = strlen(citation); asfRequire((citation_length >= 0) && (citation_length <= max_citation_length), "GeoTIFF citation too long" ); GTIFKeySet (ogtif, PCSCitationGeoKey, TYPE_ASCII, 1, citation); GTIFKeySet (ogtif, GTCitationGeoKey, TYPE_ASCII, 1, citation); FREE(citation); } else { asfPrintWarning("Unsupported combination of datum and hemisphere for a UTM\n" "map projection occurred.\n" "...GeoTIFF will be written but will not contain projection information\n" "other than tiepoints and pixel scales.\n"); } } break; case ALBERS_EQUAL_AREA: { GTIFKeySet (ogtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1, user_defined_value_code); GTIFKeySet (ogtif, ProjectionGeoKey, TYPE_SHORT, 1, user_defined_value_code); GTIFKeySet (ogtif, ProjCoordTransGeoKey, TYPE_SHORT, 1, CT_AlbersEqualArea); if (meta_is_valid_double(md->projection->param.albers.std_parallel1)) { GTIFKeySet (ogtif, ProjStdParallel1GeoKey, TYPE_DOUBLE, 1, md->projection->param.albers.std_parallel1); } if (meta_is_valid_double(md->projection->param.albers.std_parallel2)) { GTIFKeySet (ogtif, ProjStdParallel2GeoKey, TYPE_DOUBLE, 1, md->projection->param.albers.std_parallel2); } if (meta_is_valid_double(md->projection->param.albers.false_easting)) { GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1, md->projection->param.albers.false_easting); } else { GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1, 0.0); } if (meta_is_valid_double(md->projection->param.albers.false_northing)) { GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1, md->projection->param.albers.false_northing); } else { GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1, 0.0); } if (meta_is_valid_double(md->projection->param.albers.orig_latitude)) { GTIFKeySet (ogtif, ProjNatOriginLatGeoKey, TYPE_DOUBLE, 1, md->projection->param.albers.orig_latitude); } if (meta_is_valid_double(md->projection->param.albers.center_meridian)) { // The following is where ArcGIS looks for the center meridian GTIFKeySet (ogtif, ProjCenterLongGeoKey, TYPE_DOUBLE, 1, md->projection->param.albers.center_meridian); // The following is where the center meridian _should_ be stored GTIFKeySet (ogtif, ProjNatOriginLongGeoKey, TYPE_DOUBLE, 1, md->projection->param.albers.center_meridian); } write_datum_key(ogtif, md->projection->datum); write_spheroid_key(ogtif, md->projection->spheroid, re_major, re_minor); /* Set the citation key. */ char datum_str[256]; datum_2_string (datum_str, md->projection->datum); citation = MALLOC ((max_citation_length + 1) * sizeof (char)); snprintf (citation, max_citation_length + 1, "Albers equal-area conic projected GeoTIFF using %s " "%s written by Alaska Satellite Facility " "tools.", datum_str, md->projection->datum == HUGHES_DATUM ? "ellipsoid" : "datum"); append_band_names(band_names, rgb, citation, palette_color_tiff); citation_length = strlen(citation); asfRequire (citation_length >= 0 && citation_length <= max_citation_length, "bad citation length"); // The following is not needed for any but UTM (according to the standard) // but it appears that everybody uses it anyway... so we'll write it GTIFKeySet (ogtif, PCSCitationGeoKey, TYPE_ASCII, 1, citation); // The following is recommended by the standard GTIFKeySet (ogtif, GTCitationGeoKey, TYPE_ASCII, 1, citation); free (citation); } break; case LAMBERT_CONFORMAL_CONIC: { GTIFKeySet (ogtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1, user_defined_value_code); GTIFKeySet (ogtif, ProjectionGeoKey, TYPE_SHORT, 1, user_defined_value_code); GTIFKeySet (ogtif, ProjCoordTransGeoKey, TYPE_SHORT, 1, CT_LambertConfConic_2SP); if (meta_is_valid_double(md->projection->param.lamcc.plat1)) { GTIFKeySet (ogtif, ProjStdParallel1GeoKey, TYPE_DOUBLE, 1, md->projection->param.lamcc.plat1); } if (meta_is_valid_double(md->projection->param.lamcc.plat2)) { GTIFKeySet (ogtif, ProjStdParallel2GeoKey, TYPE_DOUBLE, 1, md->projection->param.lamcc.plat2); } if (meta_is_valid_double(md->projection->param.lamcc.false_easting)) { GTIFKeySet (ogtif, ProjFalseOriginEastingGeoKey, TYPE_DOUBLE, 1, md->projection->param.lamcc.false_easting); } else { GTIFKeySet (ogtif, ProjFalseOriginEastingGeoKey, TYPE_DOUBLE, 1, 0.0); } if (meta_is_valid_double(md->projection->param.lamcc.false_northing)) { GTIFKeySet (ogtif, ProjFalseOriginNorthingGeoKey, TYPE_DOUBLE, 1, md->projection->param.lamcc.false_northing); } else { GTIFKeySet(ogtif, ProjFalseOriginNorthingGeoKey, TYPE_DOUBLE, 1, 0.0); } if (meta_is_valid_double(md->projection->param.lamcc.lon0)) { GTIFKeySet (ogtif, ProjFalseOriginLongGeoKey, TYPE_DOUBLE, 1, md->projection->param.lamcc.lon0); } if (meta_is_valid_double(md->projection->param.lamcc.lat0)) { GTIFKeySet (ogtif, ProjFalseOriginLatGeoKey, TYPE_DOUBLE, 1, md->projection->param.lamcc.lat0); } write_datum_key(ogtif, md->projection->datum); write_spheroid_key(ogtif, md->projection->spheroid, re_major, re_minor); /* Set the citation key. */ char datum_str[256]; datum_2_string (datum_str, md->projection->datum); citation = MALLOC ((max_citation_length + 1) * sizeof (char)); snprintf (citation, max_citation_length + 1, "Lambert conformal conic projected GeoTIFF using %s " "%s written by Alaska Satellite Facility " "tools.", datum_str, md->projection->datum == HUGHES_DATUM ? "ellipsoid" : "datum"); append_band_names(band_names, rgb, citation, palette_color_tiff); citation_length = strlen(citation); asfRequire (citation_length >= 0 && citation_length <= max_citation_length, "bad citation length"); // The following is not needed for any but UTM (according to the standard) // but it appears that everybody uses it anyway... so we'll write it GTIFKeySet (ogtif, PCSCitationGeoKey, TYPE_ASCII, 1, citation); // The following is recommended by the standard GTIFKeySet (ogtif, GTCitationGeoKey, TYPE_ASCII, 1, citation); free (citation); } break; case POLAR_STEREOGRAPHIC: { GTIFKeySet (ogtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1, user_defined_value_code); GTIFKeySet (ogtif, ProjectionGeoKey, TYPE_SHORT, 1, user_defined_value_code); GTIFKeySet (ogtif, ProjCoordTransGeoKey, TYPE_SHORT, 1, CT_PolarStereographic); if (meta_is_valid_double(md->projection->param.ps.slon)) { GTIFKeySet (ogtif, ProjStraightVertPoleLongGeoKey, TYPE_DOUBLE, 1, md->projection->param.ps.slon); } if (meta_is_valid_double(md->projection->param.ps.slat)) { GTIFKeySet (ogtif, ProjNatOriginLatGeoKey, TYPE_DOUBLE, 1, md->projection->param.ps.slat); } if (meta_is_valid_double(md->projection->param.ps.false_easting)) { GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1, md->projection->param.ps.false_easting); } else { GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1, 0.0); } if (meta_is_valid_double(md->projection->param.ps.false_northing)) { GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1, md->projection->param.ps.false_northing); } else { GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1, 0.0); } GTIFKeySet(ogtif, ProjScaleAtNatOriginGeoKey, TYPE_DOUBLE, 1, 1.0); write_datum_key(ogtif, md->projection->datum); write_spheroid_key(ogtif, md->projection->spheroid, re_major, re_minor); /* Set the citation key. */ char datum_str[256]; datum_2_string (datum_str, md->projection->datum); citation = MALLOC ((max_citation_length + 1) * sizeof (char)); if (md->projection->datum != HUGHES_DATUM) { snprintf (citation, max_citation_length + 1, "Polar stereographic projected GeoTIFF using %s " "datum written by Alaska Satellite Facility " "tools", datum_str); append_band_names(band_names, rgb, citation, palette_color_tiff); citation_length = strlen(citation); asfRequire (citation_length >= 0 && citation_length <= max_citation_length, "bad citation length"); } else { // Hughes Datum // ...Since the datum is user-defined and the GeoTIFF is now delving outside the // realm of 'normal' GeoTIFFs, we put all the pertinent projection parameters // into the citation strings to help users if their s/w doesn't 'like' user-defined // datums. /* snprintf (citation, max_citation_length + 1, "Polar stereographic projected GeoTIFF using Hughes " "ellipsoid written by Alaska Satellite Facility " "tools, Natural Origin Latitude %lf, Straight Vertical " "Pole %lf.", md->projection->param.ps.slat, md->projection->param.ps.slon); append_band_names(band_names, rgb, citation, palette_color_tiff); citation_length = strlen(citation); asfRequire (citation_length >= 0 && citation_length <= max_citation_length, "bad citation length"); */ GTIFKeySet(ogtif, GeographicTypeGeoKey, TYPE_SHORT, 1, 4054); sprintf(citation, "NSIDC Sea Ice Polar Stereographic North"); } GTIFKeySet (ogtif, PCSCitationGeoKey, TYPE_ASCII, 1, citation); GTIFKeySet (ogtif, GTCitationGeoKey, TYPE_ASCII, 1, citation); free (citation); } break; case LAMBERT_AZIMUTHAL_EQUAL_AREA: { GTIFKeySet (ogtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1, user_defined_value_code); GTIFKeySet (ogtif, ProjectionGeoKey, TYPE_SHORT, 1, user_defined_value_code); GTIFKeySet (ogtif, ProjCoordTransGeoKey, TYPE_SHORT, 1, CT_LambertAzimEqualArea); if (meta_is_valid_double(md->projection->param.lamaz.center_lon)) { GTIFKeySet (ogtif, ProjCenterLongGeoKey, TYPE_DOUBLE, 1, md->projection->param.lamaz.center_lon); } if (meta_is_valid_double(md->projection->param.lamaz.center_lat)) { GTIFKeySet (ogtif, ProjCenterLatGeoKey, TYPE_DOUBLE, 1, md->projection->param.lamaz.center_lat); } if (meta_is_valid_double(md->projection->param.lamaz.false_easting)) { GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1, md->projection->param.lamaz.false_easting); } else { GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1, 0.0); } if (meta_is_valid_double(md->projection->param.lamaz.false_northing)) { GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1, md->projection->param.lamaz.false_northing); } else { GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1, 0.0); } write_datum_key(ogtif, md->projection->datum); write_spheroid_key(ogtif, md->projection->spheroid, re_major, re_minor); /* Set the citation key. */ char datum_str[256]; datum_2_string (datum_str, md->projection->datum); citation = MALLOC ((max_citation_length + 1) * sizeof (char)); snprintf (citation, max_citation_length + 1, "Lambert azimuthal equal area projected GeoTIFF using " "%s %s written by Alaska Satellite " "Facility tools.", datum_str, md->projection->datum == HUGHES_DATUM ? "ellipsoid" : "datum"); append_band_names(band_names, rgb, citation, palette_color_tiff); citation_length = strlen(citation); asfRequire (citation_length >= 0 && citation_length <= max_citation_length, "bad citation length"); // The following is not needed for any but UTM (according to the standard) // but it appears that everybody uses it anyway... so we'll write it GTIFKeySet (ogtif, PCSCitationGeoKey, TYPE_ASCII, 1, citation); // The following is recommended by the standard GTIFKeySet (ogtif, GTCitationGeoKey, TYPE_ASCII, 1, citation); free (citation); } break; case EQUI_RECTANGULAR: { GTIFKeySet (ogtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1, user_defined_value_code); GTIFKeySet (ogtif, ProjectionGeoKey, TYPE_SHORT, 1, user_defined_value_code); GTIFKeySet (ogtif, ProjCoordTransGeoKey, TYPE_SHORT, 1, CT_Equirectangular); GTIFKeySet (ogtif, ProjStdParallel1GeoKey, TYPE_DOUBLE, 1, 0.0); if (meta_is_valid_double(md->projection->param.eqr.central_meridian)) { GTIFKeySet (ogtif, ProjCenterLongGeoKey, TYPE_DOUBLE, 1, md->projection->param.eqr.central_meridian); } if (meta_is_valid_double(md->projection->param.eqr.orig_latitude)) { GTIFKeySet (ogtif, ProjCenterLatGeoKey, TYPE_DOUBLE, 1, md->projection->param.eqr.orig_latitude); } if (meta_is_valid_double(md->projection->param.eqr.false_easting)) { GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1, md->projection->param.eqr.false_easting); } else { GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1, 0.0); } if (meta_is_valid_double(md->projection->param.eqr.false_northing)) { GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1, md->projection->param.eqr.false_northing); } else { GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1, 0.0); } write_datum_key(ogtif, md->projection->datum); write_spheroid_key(ogtif, md->projection->spheroid, re_major, re_minor); /* Set the citation key. */ char datum_str[256]; datum_2_string (datum_str, md->projection->datum); citation = MALLOC ((max_citation_length + 1) * sizeof (char)); snprintf (citation, max_citation_length + 1, "Equi-rectangular projected GeoTIFF using " "%s %s written by Alaska Satellite " "Facility tools.", datum_str, md->projection->datum == HUGHES_DATUM ? "ellipsoid" : "datum"); append_band_names(band_names, rgb, citation, palette_color_tiff); citation_length = strlen(citation); asfRequire (citation_length >= 0 && citation_length <= max_citation_length, "bad citation length"); // The following is not needed for any but UTM (according to the standard) // but it appears that everybody uses it anyway... so we'll write it GTIFKeySet (ogtif, PCSCitationGeoKey, TYPE_ASCII, 1, citation); // The following is recommended by the standard GTIFKeySet (ogtif, GTCitationGeoKey, TYPE_ASCII, 1, citation); free (citation); } break; case EQUIDISTANT: { GTIFKeySet (ogtif, GeogEllipsoidGeoKey, TYPE_SHORT, 1, md->projection->spheroid); GTIFKeySet (ogtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1, user_defined_value_code); GTIFKeySet (ogtif, ProjectionGeoKey, TYPE_SHORT, 1, user_defined_value_code); GTIFKeySet (ogtif, ProjCoordTransGeoKey, TYPE_SHORT, 1, 32663); if (meta_is_valid_double(md->projection->param.eqc.central_meridian)) { GTIFKeySet (ogtif, ProjCenterLongGeoKey, TYPE_DOUBLE, 1, md->projection->param.eqc.central_meridian); } if (meta_is_valid_double(md->projection->param.eqc.orig_latitude)) { GTIFKeySet (ogtif, ProjCenterLatGeoKey, TYPE_DOUBLE, 1, md->projection->param.eqc.orig_latitude); } write_datum_key(ogtif, md->projection->datum); write_spheroid_key(ogtif, md->projection->spheroid, re_major, re_minor); /* Set the citation key. */ char datum_str[256]; datum_2_string (datum_str, md->projection->datum); citation = MALLOC ((max_citation_length + 1) * sizeof (char)); snprintf (citation, max_citation_length + 1, "WGS 84 / World Equidistant Cylindrical"); citation_length = strlen(citation); asfRequire (citation_length >= 0 && citation_length <= max_citation_length, "bad citation length"); // The following is not needed for any but UTM (according to the standard) // but it appears that everybody uses it anyway... so we'll write it GTIFKeySet (ogtif, PCSCitationGeoKey, TYPE_ASCII, 1, citation); // The following is recommended by the standard GTIFKeySet (ogtif, GTCitationGeoKey, TYPE_ASCII, 1, citation); free (citation); } break; case MERCATOR: { GTIFKeySet (ogtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1, user_defined_value_code); GTIFKeySet (ogtif, ProjectionGeoKey, TYPE_SHORT, 1, user_defined_value_code); GTIFKeySet (ogtif, ProjCoordTransGeoKey, TYPE_SHORT, 1, CT_Mercator); if (meta_is_valid_double(md->projection->param.mer.central_meridian)) { GTIFKeySet (ogtif, ProjNatOriginLongGeoKey, TYPE_DOUBLE, 1, md->projection->param.mer.central_meridian); } if (meta_is_valid_double(md->projection->param.mer.orig_latitude)) { GTIFKeySet (ogtif, ProjNatOriginLatGeoKey, TYPE_DOUBLE, 1, md->projection->param.mer.orig_latitude); } if (meta_is_valid_double(md->projection->param.mer.standard_parallel)) { // GeoTIFF only supports the scale factor version. // Hence some fancy calculation double lat = md->projection->param.mer.orig_latitude; double lat1 = md->projection->param.mer.standard_parallel; double re = md->projection->re_major; double rp = md->projection->re_minor; double e2 = sqrt(1.0 - rp*rp/(re*re)); double scale = (sqrt(1.0 - e2*sin(lat)*sin(lat))/cos(lat)) * (cos(lat1)/sqrt(1.0 - e2*sin(lat1)*sin(lat1))); GTIFKeySet (ogtif, ProjScaleAtNatOriginGeoKey, TYPE_DOUBLE, 1, scale); } if (meta_is_valid_double(md->projection->param.mer.false_easting)) { GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1, md->projection->param.mer.false_easting); } else { GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1, 0.0); } if (meta_is_valid_double(md->projection->param.mer.false_northing)) { GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1, md->projection->param.mer.false_northing); } else { GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1, 0.0); } write_datum_key(ogtif, md->projection->datum); write_spheroid_key(ogtif, md->projection->spheroid, re_major, re_minor); /* Set the citation key. */ char datum_str[256]; datum_2_string (datum_str, md->projection->datum); citation = MALLOC ((max_citation_length + 1) * sizeof (char)); snprintf (citation, max_citation_length + 1, "Mercator projected GeoTIFF using " "%s %s written by Alaska Satellite " "Facility tools.", datum_str, md->projection->datum == HUGHES_DATUM ? "ellipsoid" : "datum"); append_band_names(band_names, rgb, citation, palette_color_tiff); citation_length = strlen(citation); asfRequire (citation_length >= 0 && citation_length <= max_citation_length, "bad citation length"); // The following is not needed for any but UTM (according to the standard) // but it appears that everybody uses it anyway... so we'll write it GTIFKeySet (ogtif, PCSCitationGeoKey, TYPE_ASCII, 1, citation); // The following is recommended by the standard GTIFKeySet (ogtif, GTCitationGeoKey, TYPE_ASCII, 1, citation); free (citation); } break; case SINUSOIDAL: { GTIFKeySet (ogtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1, user_defined_value_code); GTIFKeySet (ogtif, ProjectionGeoKey, TYPE_SHORT, 1, user_defined_value_code); GTIFKeySet (ogtif, ProjCoordTransGeoKey, TYPE_SHORT, 1, CT_Sinusoidal); if (meta_is_valid_double(md->projection->param.sin.longitude_center)) GTIFKeySet (ogtif, ProjCenterLongGeoKey, TYPE_DOUBLE, 1, md->projection->param.sin.longitude_center); if (meta_is_valid_double(md->projection->param.sin.false_easting)) GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1, md->projection->param.sin.false_easting); else GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1, 0.0); if (meta_is_valid_double(md->projection->param.sin.false_northing)) GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1, md->projection->param.sin.false_northing); else GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1, 0.0); // Write spherical paramters GTIFKeySet (ogtif, GeogEllipsoidGeoKey, TYPE_SHORT, 1, user_defined_value_code); GTIFKeySet (ogtif, GeogSemiMajorAxisGeoKey, TYPE_DOUBLE, 1, md->projection->re_major); GTIFKeySet (ogtif, GeogInvFlatteningGeoKey, TYPE_DOUBLE, 1, 0.0); /* Set the citation key. */ //char datum_str[256]; //datum_2_string (datum_str, md->projection->datum); citation = MALLOC ((max_citation_length + 1) * sizeof (char)); snprintf (citation, max_citation_length + 1, "Sinusoidal projected GeoTIFF using " "sphere written by Alaska Satellite " "Facility tools."); append_band_names(band_names, rgb, citation, palette_color_tiff); citation_length = strlen(citation); asfRequire (citation_length >= 0 && citation_length <= max_citation_length, "bad citation length"); GTIFKeySet (ogtif, PCSCitationGeoKey, TYPE_ASCII, 1, citation); GTIFKeySet (ogtif, GTCitationGeoKey, TYPE_ASCII, 1, citation); free (citation); } break; case LAT_LONG_PSEUDO_PROJECTION: { write_datum_key(ogtif, md->projection->datum); write_spheroid_key(ogtif, md->projection->spheroid, re_major, re_minor); } break; default: asfPrintWarning ("Unsupported map projection found. TIFF file will not\n" "contain projection information.\n"); free(citation); break; } } // NOTE: GTIFWriteKeys() must be called to finalize the writing of geokeys // to the GeoTIFF file ...see finalize_tiff_file() ...do not insert a call // to GTIFWriteKeys() here plz. meta_free (md); return ogtif; } void finalize_tiff_file(TIFF *otif, GTIF *ogtif, int is_geotiff) { // Finalize the GeoTIFF if (is_geotiff && ogtif != NULL) { int ret; ret = GTIFWriteKeys (ogtif); asfRequire (ret, "Error writing GeoTIFF keys.\n"); GTIFFree (ogtif); } // Finalize the TIFF file if (otif != NULL) { XTIFFClose (otif); } } void finalize_jpeg_file(FILE *ojpeg, struct jpeg_compress_struct *cinfo) { jpeg_finish_compress (cinfo); FCLOSE (ojpeg); jpeg_destroy_compress (cinfo); } void finalize_png_file(FILE *opng, png_structp png_ptr, png_infop info_ptr) { png_write_end(png_ptr, NULL); png_destroy_write_struct(&png_ptr, &info_ptr); FCLOSE(opng); } void finalize_ppm_file(FILE *oppm) { FCLOSE(oppm); } // Function to determine whether the output image will be a multiband but not RGB image int multiband(char *format, char **band_name, int band_count) { int ii, nBands=0; if (strcmp_case(format, "HDF5") != 0 && strcmp_case(format, "netCDF") != 0) return FALSE; for (ii=0; ii<band_count; ii++) { if (band_name[ii] && strlen(band_name[ii]) > 0) nBands++; else break; } if (nBands > 1) return TRUE; else return FALSE; } void export_band_image (const char *metadata_file_name, const char *image_data_file_name, char *output_file_name, scale_t sample_mapping, char **band_name, int rgb, int true_color, int false_color, char *look_up_table_name, output_format_t format, int *noutputs, char ***output_names) { int map_projected; int is_geotiff = 1; TIFF *otif = NULL; // FILE* pointer for TIFF files GTIF *ogtif = NULL; FILE *ojpeg = NULL, *opgm=NULL, *opng=NULL, *ofp=NULL; struct jpeg_compress_struct cinfo; png_structp png_ptr; png_infop png_info_ptr; h5_t *h5=NULL; netcdf_t *netcdf=NULL; float *nc = NULL; float *hdf = NULL; int ii,jj; int palette_color_tiff = 0; int have_look_up_table = look_up_table_name && strlen(look_up_table_name)>0; char *lut_file = NULL; meta_parameters *md = meta_read (metadata_file_name); map_projected = is_map_projected(md); if (format == PNG_GE) meta_write(md, output_file_name); if (format == HDF && rgb) asfPrintError("Export to a color HDF format is not supported!\n"); else if (format == NC && rgb) asfPrintError("Export to a color netCDF format is not supported!\n"); if (md->general->image_data_type >= POLARIMETRIC_C2_MATRIX && md->general->image_data_type <= POLARIMETRIC_T4_MATRIX && md->general->image_data_type != POLARIMETRIC_DECOMPOSITION && format == POLSARPRO_HDR) append_ext_if_needed(output_file_name, ".bin", NULL); asfRequire( !(look_up_table_name == NULL && sample_mapping == TRUNCATE && (md->general->radiometry == r_SIGMA || md->general->radiometry == r_BETA || md->general->radiometry == r_GAMMA) ), "Downsampling a Sigma, Beta, or Gamma type image (power or dB)\n" "from floating point to byte using truncation is not supported.\n" "All values would map to black.\n"); if (md->general->data_type == BYTE && sample_mapping != TRUNCATE && sample_mapping != NONE && md->general->image_data_type != BROWSE_IMAGE) { asfPrintWarning("Using %s sample remapping on BYTE data will result in\n" "contrast expansion. If you do not want contrast expansion in\n" "your exported file, then you need to select either TRUNCATE or\n" "NONE for your sample remapping type.\n", sample_mapping2string(sample_mapping)); } if (md->general->band_count < 1 || md->general->band_count > MAX_BANDS) { asfPrintError ("Unsupported number of channels found (%d). Only 1 through\n" "%d channels are supported.\n", md->general->band_count, MAX_BANDS); } if (format == PGM && look_up_table_name != NULL && strlen(look_up_table_name) > 0) { asfPrintWarning("Cannot apply look up table to PGM format output files since\n" "color is not supported ...Ignoring the look up table and continuing.\n"); have_look_up_table = 0; } // NOTE: if the truecolorFlag or falsecolorFlag was set, then 'rgb' is true // and the band assignments are in the band_name[] array already. The true_color // and false_color parameters are provided separately just in case we decide // to do anything different, e.g. normal rgb processing plus something specific // to true_color or false_color (like contrast expansion) if (strstr(uc(md->general->bands), "POLSARPRO") != NULL && format == PGM) { asfPrintWarning( "Using PGM output for an image containing a PolSARpro classification\n" "band will result in separate greyscale images, and the PolSARpro classification\n" "will appear very DARK since all values in the image are small integers. It is\n" "best to use a viewer that can apply the appropriate classification look-up table\n" "to the image, i.e. asf_view, a part of the ASF tool set.\n"); } if (have_look_up_table) { lut_file = STRDUP(look_up_table_name); } else { // No look-up table lut_file = (char*)CALLOC(256, sizeof(char)); // Empty string if (format != PGM) { if (md->colormap) { // No look up table was provided for colormapped output ...Use the embedded // colormap that is in the metadata strcpy(lut_file, "tmp_lut_file.lut"); colormap_to_lut_file(md->colormap, lut_file); have_look_up_table = TRUE; asfPrintStatus("\nUsing the colormap embedded in the ASF metadata (%s).\n" "for applicable bands.\n\n", md->colormap->look_up_table); } } } if (rgb && !have_look_up_table) { // Initialize the selected format if (format == TIF) { is_geotiff = 0; initialize_tiff_file(&otif, &ogtif, output_file_name, metadata_file_name, is_geotiff, sample_mapping, rgb, &palette_color_tiff, band_name, lut_file, 0); } else if (format == GEOTIFF) { initialize_tiff_file(&otif, &ogtif, output_file_name, metadata_file_name, is_geotiff, sample_mapping, rgb, &palette_color_tiff, band_name, lut_file, 0); } else if (format == JPEG) { initialize_jpeg_file(output_file_name, md, &ojpeg, &cinfo, rgb); } else if (format == PNG) { initialize_png_file(output_file_name, md, &opng, &png_ptr, &png_info_ptr, rgb); } else if (format == PNG_ALPHA) { initialize_png_file_ext(output_file_name, md, &opng, &png_ptr, &png_info_ptr, rgb, TRUE); } else if (format == PNG_GE) { initialize_png_file_ext(output_file_name, md, &opng, &png_ptr, &png_info_ptr, rgb, 2); } int ignored[4] = {0, 0, 0, 0}; int red_channel=-1, green_channel=-1, blue_channel=-1; for (ii = 0; ii < 4; ii++) { if (ii < md->general->band_count) { ignored[ii] = strncmp("IGNORE", uc(band_name[ii]), 6) == 0 ? 1 : 0; } else { // Ignore bands that exceed band count ignored[ii] = 1; } } red_channel = get_band_number(md->general->bands, md->general->band_count, band_name[0]); if (!ignored[0] && !(red_channel >= 0 && red_channel < MAX_BANDS)) { asfPrintError("Band number (%d) out of range for %s channel.\n", red_channel, "red"); } green_channel = get_band_number(md->general->bands, md->general->band_count, band_name[1]); if (!ignored[1] && !(green_channel >= 0 && green_channel < MAX_BANDS)) { asfPrintError("Band number (%d) out of range for %s channel.\n", green_channel, "green"); } blue_channel = get_band_number(md->general->bands, md->general->band_count, band_name[2]); if (!ignored[2] && !(blue_channel >= 0 && blue_channel < MAX_BANDS)) { asfPrintError("Band number (%d) out of range for %s channel.\n", blue_channel, "blue"); } channel_stats_t red_stats, blue_stats, green_stats; red_stats.hist = NULL; red_stats.hist_pdf = NULL; green_stats.hist = NULL; green_stats.hist_pdf = NULL; blue_stats.hist = NULL; blue_stats.hist_pdf = NULL; if (!md->optical) { asfRequire (sizeof(unsigned char) == 1, "Size of the unsigned char data type on this machine is " "different than expected.\n"); /*** Normal straight per-channel stats (no combined-band stats) */ // Red channel statistics if (!ignored[red_channel] && // Non-blank band sample_mapping != NONE && // Float-to-byte resampling needed sample_mapping != HISTOGRAM_EQUALIZE && // A histogram is not needed md->stats != NULL && // Stats exist and are valid md->stats > 0 && meta_is_valid_string(band_name[0]) && // Band name exists and is valid strlen(band_name[0]) > 0) { // If the stats already exist, then use them int band_no = get_band_number(md->general->bands, md->general->band_count, band_name[0]); red_stats.min = md->stats->band_stats[band_no].min; red_stats.max = md->stats->band_stats[band_no].max; red_stats.mean = md->stats->band_stats[band_no].mean; red_stats.standard_deviation = md->stats->band_stats[band_no].std_deviation; red_stats.hist = NULL; red_stats.hist_pdf = NULL; if (sample_mapping == SIGMA) { double omin = red_stats.mean - 2*red_stats.standard_deviation; double omax = red_stats.mean + 2*red_stats.standard_deviation; if (omin > red_stats.min) red_stats.min = omin; if (omax < red_stats.max) red_stats.max = omax; } else if (sample_mapping == MINMAX_MEDIAN) calc_minmax_median(image_data_file_name, band_name[0], md->general->no_data, &red_stats.min, &red_stats.max); } else { // Calculate the stats if you have to... if (sample_mapping != NONE && !ignored[red_channel]) { // byte image asfPrintStatus("\nGathering red channel statistics ...\n"); calc_stats_from_file(image_data_file_name, band_name[0], md->general->no_data, &red_stats.min, &red_stats.max, &red_stats.mean, &red_stats.standard_deviation, &red_stats.hist); if (sample_mapping == SIGMA) { double omin = red_stats.mean - 2*red_stats.standard_deviation; double omax = red_stats.mean + 2*red_stats.standard_deviation; if (omin > red_stats.min) red_stats.min = omin; if (omax < red_stats.max) red_stats.max = omax; } else if ( sample_mapping == HISTOGRAM_EQUALIZE ) { red_stats.hist_pdf = gsl_histogram_pdf_alloc (256); gsl_histogram_pdf_init (red_stats.hist_pdf, red_stats.hist); } else if (sample_mapping == MINMAX_MEDIAN) calc_minmax_median(image_data_file_name, band_name[0], md->general->no_data, &red_stats.min, &red_stats.max); } } // Green channel statistics if (!ignored[green_channel] && // Non-blank band sample_mapping != NONE && // Float-to-byte resampling needed sample_mapping != HISTOGRAM_EQUALIZE && // A histogram is not needed md->stats != NULL && // Stats exist and are valid md->stats > 0 && meta_is_valid_string(band_name[1]) && // Band name exists and is valid strlen(band_name[1]) > 0) { // If the stats already exist, then use them int band_no = get_band_number(md->general->bands, md->general->band_count, band_name[1]); green_stats.min = md->stats->band_stats[band_no].min; green_stats.max = md->stats->band_stats[band_no].max; green_stats.mean = md->stats->band_stats[band_no].mean; green_stats.standard_deviation = md->stats->band_stats[band_no].std_deviation; green_stats.hist = NULL; green_stats.hist_pdf = NULL; if (sample_mapping == SIGMA) { double omin = green_stats.mean - 2*green_stats.standard_deviation; double omax = green_stats.mean + 2*green_stats.standard_deviation; if (omin > green_stats.min) green_stats.min = omin; if (omax < green_stats.max) green_stats.max = omax; } else if (sample_mapping == MINMAX_MEDIAN) calc_minmax_median(image_data_file_name, band_name[1], md->general->no_data, &green_stats.min, &green_stats.max); } else { // Calculate the stats if you have to... if (sample_mapping != NONE && !ignored[green_channel]) { // byte image asfPrintStatus("\nGathering green channel statistics ...\n"); calc_stats_from_file(image_data_file_name, band_name[1], md->general->no_data, &green_stats.min, &green_stats.max, &green_stats.mean, &green_stats.standard_deviation, &green_stats.hist); if (sample_mapping == SIGMA) { double omin = green_stats.mean - 2*green_stats.standard_deviation; double omax = green_stats.mean + 2*green_stats.standard_deviation; if (omin > green_stats.min) green_stats.min = omin; if (omax < green_stats.max) green_stats.max = omax; } else if ( sample_mapping == HISTOGRAM_EQUALIZE ) { green_stats.hist_pdf = gsl_histogram_pdf_alloc(256); gsl_histogram_pdf_init (green_stats.hist_pdf, green_stats.hist); } else if (sample_mapping == MINMAX_MEDIAN) calc_minmax_median(image_data_file_name, band_name[1], md->general->no_data, &green_stats.min, &green_stats.max); } } // Blue channel statistics if (!ignored[blue_channel] && // Non-blank band sample_mapping != NONE && // Float-to-byte resampling needed sample_mapping != HISTOGRAM_EQUALIZE && // A histogram is not needed md->stats != NULL && // Stats exist and are valid md->stats > 0 && meta_is_valid_string(band_name[2]) && // Band name exists and is valid strlen(band_name[2]) > 0) { // If the stats already exist, then use them int band_no = get_band_number(md->general->bands, md->general->band_count, band_name[2]); blue_stats.min = md->stats->band_stats[band_no].min; blue_stats.max = md->stats->band_stats[band_no].max; blue_stats.mean = md->stats->band_stats[band_no].mean; blue_stats.standard_deviation = md->stats->band_stats[band_no].std_deviation; blue_stats.hist = NULL; blue_stats.hist_pdf = NULL; if (sample_mapping == SIGMA) { double omin = blue_stats.mean - 2*blue_stats.standard_deviation; double omax = blue_stats.mean + 2*blue_stats.standard_deviation; if (omin > blue_stats.min) blue_stats.min = omin; if (omax < blue_stats.max) blue_stats.max = omax; } else if (sample_mapping == MINMAX_MEDIAN) calc_minmax_median(image_data_file_name, band_name[2], md->general->no_data, &blue_stats.min, &blue_stats.max); } else { // Calculate the stats if you have to... if (sample_mapping != NONE && !ignored[blue_channel]) { // byte image asfPrintStatus("\nGathering blue channel statistics ...\n"); calc_stats_from_file(image_data_file_name, band_name[2], md->general->no_data, &blue_stats.min, &blue_stats.max, &blue_stats.mean, &blue_stats.standard_deviation, &blue_stats.hist); if (sample_mapping == SIGMA) { double omin = blue_stats.mean - 2*blue_stats.standard_deviation; double omax = blue_stats.mean + 2*blue_stats.standard_deviation; if (omin > blue_stats.min) blue_stats.min = omin; if (omax < blue_stats.max) blue_stats.max = omax; } else if ( sample_mapping == HISTOGRAM_EQUALIZE ) { blue_stats.hist_pdf = gsl_histogram_pdf_alloc (256); gsl_histogram_pdf_init (blue_stats.hist_pdf, blue_stats.hist); } else if (sample_mapping == MINMAX_MEDIAN) calc_minmax_median(image_data_file_name, band_name[2], md->general->no_data, &blue_stats.min, &blue_stats.max); } } } float *red_float_line = NULL; float *green_float_line = NULL; float *blue_float_line = NULL; unsigned char *red_byte_line = NULL; unsigned char *green_byte_line = NULL; unsigned char *blue_byte_line = NULL; // Write the data to the file FILE *fp = FOPEN(image_data_file_name, "rb"); int sample_count = md->general->sample_count; int offset = md->general->line_count; // Allocate some memory if (md->optical || md->general->data_type == BYTE) { if (ignored[red_channel]) red_byte_line = (unsigned char *) CALLOC(sample_count, sizeof(char)); else red_byte_line = (unsigned char *) MALLOC(sample_count * sizeof(char)); if (ignored[green_channel]) green_byte_line = (unsigned char *) CALLOC(sample_count, sizeof(char)); else green_byte_line = (unsigned char *) MALLOC(sample_count * sizeof(char)); if (ignored[blue_channel]) blue_byte_line = (unsigned char *) CALLOC(sample_count, sizeof(char)); else blue_byte_line = (unsigned char *) MALLOC(sample_count * sizeof(char)); } else { // Not optical data red_float_line = (float *) MALLOC(sample_count * sizeof(float)); if (ignored[red_channel]){ for (ii=0; ii<sample_count; ++ii) { red_float_line[ii] = md->general->no_data; } } green_float_line = (float *) MALLOC(sample_count * sizeof(float)); if (ignored[green_channel]) { for (ii=0; ii<sample_count; ++ii) { green_float_line[ii] = md->general->no_data; } } blue_float_line = (float *) MALLOC(sample_count * sizeof(float)); if (ignored[blue_channel]) { for (ii=0; ii<sample_count; ++ii) { blue_float_line[ii] = md->general->no_data; } } } double r_omin=0, r_omax=0; double g_omin=0, g_omax=0; double b_omin=0, b_omax=0; if (md->optical && (true_color || false_color)) { // NOTE: Using the stats from the metadata, if available, is only valid // if no histogram is necessary, else one must be generated via the // stats functions. If true_color or false_color are selected, then sample_mapping // should NOT be HISTOGRAM_EQUALIZE in particular and should always be set // to SIGMA if (sample_mapping == NONE && (true_color || false_color)) { sample_mapping = SIGMA; } if (sample_mapping != SIGMA) { asfPrintWarning("Cannot combine true or false color options with sample mappings\n" "other than 2-sigma. You selected %s. Defaulting to 2-sigma...\n", sample_mapping == TRUNCATE ? "TRUNCATE" : sample_mapping == MINMAX ? "MINMAX" : sample_mapping == HISTOGRAM_EQUALIZE ? "HISTOGRAM_EQUALIZE" : "UNKNOWN or INVALID"); } asfPrintStatus("\nSampling color channels for 2-sigma contrast-expanded %s output...\n", true_color ? "True Color" : false_color ? "False Color" : "Unknown"); // Set up red resampling if (md->stats && md->stats->band_count >= 3 && meta_is_valid_string(band_name[0]) && strlen(band_name[0]) > 0 && sample_mapping != HISTOGRAM_EQUALIZE) { // If the stats already exist, then use them int band_no = get_band_number(md->general->bands, md->general->band_count, band_name[0]); red_stats.min = md->stats->band_stats[band_no].min; red_stats.max = md->stats->band_stats[band_no].max; red_stats.mean = md->stats->band_stats[band_no].mean; red_stats.standard_deviation = md->stats->band_stats[band_no].std_deviation; red_stats.hist = NULL; red_stats.hist_pdf = NULL; } else { asfPrintStatus("\nGathering red channel statistics...\n"); calc_stats_from_file(image_data_file_name, band_name[0], md->general->no_data, &red_stats.min, &red_stats.max, &red_stats.mean, &red_stats.standard_deviation, &red_stats.hist); } r_omin = red_stats.mean - 2*red_stats.standard_deviation; r_omax = red_stats.mean + 2*red_stats.standard_deviation; if (r_omin < red_stats.min) r_omin = red_stats.min; if (r_omax > red_stats.max) r_omax = red_stats.max; // Set up green resampling if (md->stats && md->stats->band_count >= 3 && meta_is_valid_string(band_name[1]) && strlen(band_name[1]) > 0 && sample_mapping != HISTOGRAM_EQUALIZE) { // If the stats already exist, then use them int band_no = get_band_number(md->general->bands, md->general->band_count, band_name[1]); green_stats.min = md->stats->band_stats[band_no].min; green_stats.max = md->stats->band_stats[band_no].max; green_stats.mean = md->stats->band_stats[band_no].mean; green_stats.standard_deviation = md->stats->band_stats[band_no].std_deviation; green_stats.hist = NULL; green_stats.hist_pdf = NULL; } else { asfPrintStatus("\nGathering green channel statistics...\n"); calc_stats_from_file(image_data_file_name, band_name[1], md->general->no_data, &green_stats.min, &green_stats.max, &green_stats.mean, &green_stats.standard_deviation, &green_stats.hist); } g_omin = green_stats.mean - 2*green_stats.standard_deviation; g_omax = green_stats.mean + 2*green_stats.standard_deviation; if (g_omin < green_stats.min) g_omin = green_stats.min; if (g_omax > green_stats.max) g_omax = green_stats.max; // Set up blue resampling if (md->stats && md->stats->band_count >= 3 && meta_is_valid_string(band_name[2]) && strlen(band_name[2]) > 0 && sample_mapping != HISTOGRAM_EQUALIZE) { // If the stats already exist, then use them int band_no = get_band_number(md->general->bands, md->general->band_count, band_name[2]); blue_stats.min = md->stats->band_stats[band_no].min; blue_stats.max = md->stats->band_stats[band_no].max; blue_stats.mean = md->stats->band_stats[band_no].mean; blue_stats.standard_deviation = md->stats->band_stats[band_no].std_deviation; blue_stats.hist = NULL; blue_stats.hist_pdf = NULL; } else { asfPrintStatus("\nGathering blue channel statistics...\n\n"); calc_stats_from_file(image_data_file_name, band_name[2], md->general->no_data, &blue_stats.min, &blue_stats.max, &blue_stats.mean, &blue_stats.standard_deviation, &blue_stats.hist); } b_omin = blue_stats.mean - 2*blue_stats.standard_deviation; b_omax = blue_stats.mean + 2*blue_stats.standard_deviation; if (b_omin < blue_stats.min) b_omin = blue_stats.min; if (b_omax > blue_stats.max) b_omax = blue_stats.max; asfPrintStatus("Applying 2-sigma contrast expansion to color bands...\n\n"); } for (ii=0; ii<md->general->line_count; ii++) { if (md->optical || md->general->data_type == BYTE) { // Optical images come as byte in the first place if (!ignored[red_channel]) get_byte_line(fp, md, ii+red_channel*offset, red_byte_line); if (!ignored[green_channel]) get_byte_line(fp, md, ii+green_channel*offset, green_byte_line); if (!ignored[blue_channel]) get_byte_line(fp, md, ii+blue_channel*offset, blue_byte_line); // If true or false color flag was set, then (re)sample with 2-sigma // contrast expansion if (true_color || false_color) { for (jj=0; jj<sample_count; jj++) { red_byte_line[jj] = pixel_float2byte((float)red_byte_line[jj], SIGMA, r_omin, r_omax, red_stats.hist, red_stats.hist_pdf, NAN); green_byte_line[jj] = pixel_float2byte((float)green_byte_line[jj], SIGMA, g_omin, g_omax, green_stats.hist, green_stats.hist_pdf, NAN); blue_byte_line[jj] = pixel_float2byte((float)blue_byte_line[jj], SIGMA, b_omin, b_omax, blue_stats.hist, blue_stats.hist_pdf, NAN); } } if (format == TIF || format == GEOTIFF) write_rgb_tiff_byte2byte(otif, red_byte_line, green_byte_line, blue_byte_line, ii, sample_count); else if (format == JPEG) write_rgb_jpeg_byte2byte(ojpeg, red_byte_line, green_byte_line, blue_byte_line, &cinfo, sample_count); else if (format == PNG || format == PNG_ALPHA || format == PNG_GE) write_rgb_png_byte2byte(opng, red_byte_line, green_byte_line, blue_byte_line, png_ptr, png_info_ptr, sample_count); else asfPrintError("Impossible: unexpected format %s\n", format2str(format)); } else if (sample_mapping == NONE) { // Write float->float lines if float image if (!ignored[red_channel]) get_float_line(fp, md, ii+red_channel*offset, red_float_line); if (!ignored[green_channel]) get_float_line(fp, md, ii+green_channel*offset, green_float_line); if (!ignored[blue_channel]) get_float_line(fp, md, ii+blue_channel*offset, blue_float_line); if (format == GEOTIFF || format == TIF) write_rgb_tiff_float2float(otif, red_float_line, green_float_line, blue_float_line, ii, sample_count); else asfPrintError("Impossible: unexpected format %s\n", format2str(format)); } else { // Write float->byte lines if byte image if (!ignored[red_channel]) get_float_line(fp, md, ii+red_channel*offset, red_float_line); if (!ignored[green_channel]) get_float_line(fp, md, ii+green_channel*offset, green_float_line); if (!ignored[blue_channel]) get_float_line(fp, md, ii+blue_channel*offset, blue_float_line); if (format == TIF || format == GEOTIFF) write_rgb_tiff_float2byte(otif, red_float_line, green_float_line, blue_float_line, red_stats, green_stats, blue_stats, sample_mapping, md->general->no_data, ii, sample_count); else if (format == JPEG) write_rgb_jpeg_float2byte(ojpeg, red_float_line, green_float_line, blue_float_line, &cinfo, red_stats, green_stats, blue_stats, sample_mapping, md->general->no_data, sample_count); else if (format == PNG || format == PNG_ALPHA || format == PNG_GE) write_rgb_png_float2byte(opng, red_float_line, green_float_line, blue_float_line, png_ptr, png_info_ptr, red_stats, green_stats, blue_stats, sample_mapping, md->general->no_data, sample_count); else asfPrintError("Impossible: unexpected format %s\n", format2str(format)); } asfLineMeter(ii, md->general->line_count); } // Free memory FREE(red_byte_line); FREE(green_byte_line); FREE(blue_byte_line); FREE(red_float_line); FREE(green_float_line); FREE(blue_float_line); // Finalize the chosen format if (format == TIF || format == GEOTIFF) finalize_tiff_file(otif, ogtif, is_geotiff); else if (format == JPEG) finalize_jpeg_file(ojpeg, &cinfo); else if (format == PNG || format == PNG_ALPHA || format == PNG_GE) finalize_png_file(opng, png_ptr, png_info_ptr); else asfPrintError("Impossible: unexpected format %s\n", format2str(format)); if (red_stats.hist) gsl_histogram_free(red_stats.hist); if (red_stats.hist_pdf) gsl_histogram_pdf_free(red_stats.hist_pdf); if (green_stats.hist) gsl_histogram_free(green_stats.hist); if (green_stats.hist_pdf) gsl_histogram_pdf_free(green_stats.hist_pdf); if (blue_stats.hist) gsl_histogram_free(blue_stats.hist); if (blue_stats.hist_pdf) gsl_histogram_pdf_free(blue_stats.hist_pdf); FCLOSE(fp); // set the output filename *noutputs = 1; char **outs = MALLOC(sizeof(char*)); outs[0] = STRDUP(output_file_name); *output_names = outs; } else if (multiband(format2str(format), band_name, md->general->band_count)) { // Multi-band image output (but no RGB) // This can currently only be the case for HDF5 and netCDF data hid_t h5_data; if (format == HDF) { append_ext_if_needed(output_file_name, ".h5", NULL); h5 = initialize_h5_file(output_file_name, md); hdf = (float *) MALLOC(sizeof(float)*md->general->line_count*md->general->sample_count); } else if (format == NC) { append_ext_if_needed(output_file_name, ".nc", NULL); netcdf = initialize_netcdf_file(output_file_name, md); nc = (float *) MALLOC(sizeof(float)*md->general->line_count*md->general->sample_count); } int kk, channel; int band_count = md->general->band_count; int sample_count = md->general->sample_count; int offset = md->general->line_count; FILE *fp = FOPEN(image_data_file_name, "rb"); float *float_line = (float *) MALLOC(sizeof(float) * sample_count); for (kk=0; kk<band_count; kk++) { for (ii=0; ii<md->general->line_count; ii++ ) { channel = get_band_number(md->general->bands, band_count, band_name[kk]); get_float_line(fp, md, ii+channel*offset, float_line); if (format == HDF) { int sample; for (sample=0; sample<sample_count; sample++) hdf[ii*sample_count+sample] = float_line[sample]; } else if (format == NC) { int sample; for (sample=0; sample<sample_count; sample++) { nc[ii*sample_count+sample] = float_line[sample]; } } asfLineMeter(ii, md->general->line_count); } if (format == HDF) { asfPrintStatus("Storing band '%s' ...\n", band_name[kk]); char dataset[50]; sprintf(dataset, "/data/%s_AMPLITUDE_IMAGE", band_name[kk]); h5_data = H5Dopen(h5->file, dataset, H5P_DEFAULT); H5Dwrite(h5_data, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, hdf); H5Dclose(h5_data); } else if (format == NC) { asfPrintStatus("Storing band '%s' ...\n", band_name[kk]); nc_put_var_float(netcdf->ncid, netcdf->var_id[kk], &nc[0]); } } if (format == HDF) { finalize_h5_file(h5); FREE(hdf); } else if (format == NC) { finalize_netcdf_file(netcdf, md); FREE(nc); } else asfPrintError("Impossible: unexpected format %s\n", format2str(format)); FCLOSE(fp); } else { // Single-band image output (one grayscale file for each available band) int free_band_names=FALSE; int band_count = md->general->band_count; char base_name[255]; char *bands = (char *) MALLOC(sizeof(char)*1024); strcpy(bands, md->general->bands); strcpy(base_name, output_file_name); char *matrix = (char *) MALLOC(sizeof(char)*5); char *decomposition = (char *) MALLOC(sizeof(char)*25); char *path_name = (char *) MALLOC(sizeof(char)*1024); char *out_file = NULL; if (!band_name) { // caller did not pass in the band names -- we will have // to come up with some band names ourselves if (band_count == 1) { // only one band, just call it "01" band_name = (char **) CALLOC(MAX_BANDS, sizeof(char*)); band_name[0] = (char*) MALLOC(sizeof(char)*100); strcpy(band_name[0], "01"); } else if (have_look_up_table) { // when exporting a look up table, number the bands band_name = (char **) CALLOC(MAX_BANDS, sizeof(char*)); int i; for (i=0; i<3; i++) { band_name[i] = (char*) MALLOC(sizeof(char)*100); sprintf(band_name[i], "%02d", i + 1); } } else { // get what is in the metadata int n; char *b = stripExt(image_data_file_name); band_name = find_single_band(b, "all", &n); asfRequire (n == band_count, "Band count inconsistent: %d != %d\n", n, band_count); FREE(b); } // in all three cases, we must free "band_name" // (normally not freed, it the caller's) free_band_names = TRUE; } if (md->general->image_data_type >= POLARIMETRIC_C2_MATRIX && md->general->image_data_type <= POLARIMETRIC_T4_MATRIX) { if (strstr(md->general->bands, "C44")) sprintf(matrix, "C4"); else if (strstr(md->general->bands, "C33")) sprintf(matrix, "C3"); else if (strstr(md->general->bands, "C22")) sprintf(matrix, "C2"); else if (strstr(md->general->bands, "T44")) sprintf(matrix, "T4"); else if (strstr(md->general->bands, "T33")) sprintf(matrix, "T3"); else if (strstr(md->general->bands, "T22")) sprintf(matrix, "T2"); else asfPrintError("The bands do not correspond to matrix type (%s)\n", image_data_type2str(md->general->image_data_type)); } // If we are dealing with polarimetric matrices, the output file name // becomes the name of an output directory. We need to figure out from // the bands string, what kind of matrix we have, because we need to // create the appropriate subdirectory. Otherwise, PolSARPro can't handle // the files out of the box. if (md->general->image_data_type >= POLARIMETRIC_C2_MATRIX && md->general->image_data_type <= POLARIMETRIC_T4_MATRIX && md->general->band_count != 1 && format == POLSARPRO_HDR) { char *dirName = (char *) MALLOC(sizeof(char)*1024); char *fileName = (char *) MALLOC(sizeof(char)*1024); split_dir_and_file(output_file_name, dirName, fileName); char *path = get_dirname(output_file_name); if (strlen(dirName) <= 0) { path = g_get_current_dir(); sprintf(path_name, "%s%c%s%c%s", path, DIR_SEPARATOR, output_file_name, DIR_SEPARATOR, matrix); } else sprintf(path_name, "%s%c%s%c%s", dirName, DIR_SEPARATOR, fileName, DIR_SEPARATOR, matrix); if (is_dir(path_name)) asfPrintError("Output directory (%s) already exists.\n", path_name); else if(create_dir(path_name) == -1) asfPrintError("Can't generate output directory (%s).\n", path_name); char *configFile = (char *) MALLOC(sizeof(char)*(strlen(path_name)+15)); sprintf(configFile, "%s%cconfig.txt", path_name, DIR_SEPARATOR); FILE *fpConfig = FOPEN(configFile, "w"); fprintf(fpConfig, "Nrow\n%d\n", md->general->line_count); fprintf(fpConfig, "---------\nNcol\n%d\n", md->general->sample_count); fprintf(fpConfig, "---------\nPolarCase\nmonostatic\n"); fprintf(fpConfig, "---------\nPolarType\nfull\n"); FCLOSE(fpConfig); FREE(configFile); FREE(path); FREE(dirName); FREE(fileName); } if (md->general->image_data_type == POLARIMETRIC_DECOMPOSITION) strcpy(decomposition, band_name[band_count-1]); // We treat polarimetric decompositions in a similar way. The output file // name becomes the name of an output directory again. The actual file // names can be extracted from the bands string. if (md->general->image_data_type == POLARIMETRIC_DECOMPOSITION && md->general->band_count != 1 && format == POLSARPRO_HDR) { char *dirName = (char *) MALLOC(sizeof(char)*1024); char *fileName = (char *) MALLOC(sizeof(char)*1024); split_dir_and_file(output_file_name, dirName, fileName); char *path = get_dirname(output_file_name); if (strlen(dirName) <= 0) { path = g_get_current_dir(); sprintf(path_name, "%s%c%s", path, DIR_SEPARATOR, output_file_name); } else sprintf(path_name, "%s%c%s", dirName, DIR_SEPARATOR, fileName); if (is_dir(path_name)) asfPrintError("Output directory (%s) already exists.\n", path_name); else if(create_dir(path_name) == -1) asfPrintError("Can't generate output directory (%s).\n", path_name); char *configFile = (char *) MALLOC(sizeof(char)*(strlen(path_name)+15)); sprintf(configFile, "%s%cconfig.txt", path_name, DIR_SEPARATOR); FILE *fpConfig = FOPEN(configFile, "w"); fprintf(fpConfig, "Nrow\n%d\n", md->general->line_count); fprintf(fpConfig, "---------\nNcol\n%d\n", md->general->sample_count); fprintf(fpConfig, "---------\nPolarCase\nmonostatic\n"); fprintf(fpConfig, "---------\nPolarType\nfull\n"); FCLOSE(fpConfig); FREE(configFile); FREE(path); FREE(dirName); FREE(fileName); } // store the names of the generated files here *noutputs = 0; *output_names = MALLOC(sizeof(char*) * band_count); int kk; int is_colormap_band; for (kk=0; kk<band_count; kk++) { if (band_name[kk]) { is_colormap_band = FALSE; // two ways we can be applying a colormap to this band: // (1) the metadata has an embedded colormap, and it's band_id // is this band. // (2) user used the "-lut" option -- we have the !md->colormap // here to avoid thinking we've got -lut when it was really // just the md->colormap (which sets have_look_up_table, above) int is_polsarpro = (md->general->image_data_type == POLARIMETRIC_IMAGE || md->general->image_data_type == POLARIMETRIC_SEGMENTATION || md->general->image_data_type == POLARIMETRIC_DECOMPOSITION || md->general->image_data_type == POLARIMETRIC_PARAMETER || (md->general->image_data_type >= POLARIMETRIC_C2_MATRIX && md->general->image_data_type <= POLARIMETRIC_T4_MATRIX)) ? 1 : 0; if (md->general->image_data_type == POLARIMETRIC_PARAMETER && md->colormap) is_colormap_band = TRUE; else if ((md->colormap && strcmp_case(band_name[kk], md->colormap->band_id)==0) || (!md->colormap && have_look_up_table && md->general->data_type == BYTE) || (!md->colormap && have_look_up_table && md->general->data_type != BYTE && sample_mapping != NONE)) { is_colormap_band = TRUE; sample_mapping = is_polsarpro ? TRUNCATE : sample_mapping; } // skip the 'AMP' band if we have POlSARPro data and the user wants // to apply a LUT if (strcmp_case(band_name[kk], "AMP") == 0 && is_polsarpro && band_count > 1) continue; if (format == POLSARPRO_HDR) { is_colormap_band = FALSE; sample_mapping = NONE; } if (have_look_up_table && is_colormap_band) { asfPrintStatus("\nApplying %s color look up table...\n\n", look_up_table_name); } out_file = (char *) MALLOC(sizeof(char)*1024); strcpy(out_file, output_file_name); // We enforce a byte conversion using truncate for polarimetric segmentation, regardless of // applying a look up table if (md->general->image_data_type == POLARIMETRIC_SEGMENTATION && md->colormap) sample_mapping = TRUNCATE; // Initialize the selected format // NOTE: For PolSARpro, the first band is amplitude and should be // written out as a single-band greyscale image while the second // band is a classification and should be written out as color ... // and for TIFF formats, as a palette color tiff. // The only exception to this rule are polarimetric matrices if (md->general->image_data_type >= POLARIMETRIC_C2_MATRIX && md->general->image_data_type <= POLARIMETRIC_T4_MATRIX && md->general->band_count != 1) { int ll, found_band = FALSE; int band_count; if (strcmp(matrix, "T3") == 0) band_count = 9; if (strcmp(matrix, "T4") == 0) band_count = 16; if (strcmp(matrix, "C2") == 0) band_count = 4; if (strcmp(matrix, "C3") == 0) band_count = 9; if (strcmp(matrix, "C4") == 0) band_count = 16; for (ll=0; ll<band_count; ll++) { if (strcmp(matrix, "T3") == 0 && strncmp(band_name[kk], t3_matrix[ll], strlen(band_name[kk])) == 0) found_band = TRUE; else if (strcmp(matrix, "T4") == 0 && strncmp(band_name[kk], t4_matrix[ll], strlen(band_name[kk])) == 0) found_band = TRUE; else if (strcmp(matrix, "C2") == 0 && strncmp(band_name[kk], c2_matrix[ll], strlen(band_name[kk])) == 0) found_band = TRUE; else if (strcmp(matrix, "C3") == 0 && strncmp(band_name[kk], c3_matrix[ll], strlen(band_name[kk])) == 0) found_band = TRUE; else if (strcmp(matrix, "C4") == 0 && strncmp(band_name[kk], c4_matrix[ll], strlen(band_name[kk])) == 0) found_band = TRUE; } if (!found_band) continue; if (format == POLSARPRO_HDR) { // output goes to directory sprintf(out_file, "%s%c%s", path_name, DIR_SEPARATOR, band_name[kk]); } else { // individual file names if (strcmp_case(md->general->sensor, "UAVSAR") == 0 && strcmp_case(md->general->sensor_name, "POLSAR") == 0) { char mode[5]; if (strcmp_case(md->general->mode, "GRD") == 0) strcpy(mode, "grd"); else if (strcmp_case(md->general->mode, "MLC") == 0) strcpy(mode, "mlc"); if (strcmp(mode, "grd") == 0 || strcmp(mode, "mlc") == 0) { if (strcmp_case(band_name[kk], "C11") == 0) sprintf(out_file, "%s_%sHHHH", output_file_name, mode); else if (strcmp_case(band_name[kk], "C22") == 0) sprintf(out_file, "%s_%sHVHV", output_file_name, mode); else if (strcmp_case(band_name[kk], "C33") == 0) sprintf(out_file, "%s_%sVVVV", output_file_name, mode); else if (strcmp_case(band_name[kk], "C12_real") == 0) sprintf(out_file, "%s_%sHHHV_real", output_file_name, mode); else if (strcmp_case(band_name[kk], "C12_imag") == 0) sprintf(out_file, "%s_%sHHHV_imag", output_file_name, mode); else if (strcmp_case(band_name[kk], "C13_real") == 0) sprintf(out_file, "%s_%sHHVV_real", output_file_name, mode); else if (strcmp_case(band_name[kk], "C13_imag") == 0) sprintf(out_file, "%s_%sHHVV_imag", output_file_name, mode); else if (strcmp_case(band_name[kk], "C23_real") == 0) sprintf(out_file, "%s_%sHVVV_real", output_file_name, mode); else if (strcmp_case(band_name[kk], "C23_imag") == 0) sprintf(out_file, "%s_%sHVVV_imag", output_file_name, mode); } else if (strcmp(mode, "hgt") == 0) sprintf(out_file, "%s_hgt", output_file_name); } } } else if (md->general->image_data_type == POLARIMETRIC_STOKES_MATRIX) { if (strcmp_case(md->general->sensor, "UAVSAR") == 0 && strcmp_case(md->general->sensor_name, "POLSAR") == 0 && strcmp_case(md->general->mode, "DAT") == 0) sprintf(out_file, "%s_dat%s", output_file_name, band_name[kk]); } else if (md->general->image_data_type == DEM) { if (strcmp_case(md->general->sensor, "UAVSAR") == 0 && strcmp_case(md->general->sensor_name, "POLSAR") == 0 && strcmp_case(md->general->mode, "HGT") == 0) { char *tmp = stripExt(output_file_name); sprintf(out_file, "%s_hgt.tif", tmp); FREE(tmp); } } else if (md->general->image_data_type == POLARIMETRIC_DECOMPOSITION && md->general->band_count != 1) { int ll, found_band = FALSE; int band_count; if (strcmp(decomposition, "Freeman2_Vol") == 0) band_count = 2; else if (strcmp(decomposition, "Freeman_Vol") == 0) band_count = 3; else if (strcmp(decomposition, "VanZyl3_Vol") == 0) band_count = 3; else if (strcmp(decomposition, "Yamaguchi3_Vol") == 0) band_count = 3; else if (strcmp(decomposition, "Yamaguchi4_Vol") == 0) band_count = 4; else if (strcmp(decomposition, "Krogager_Ks") == 0) band_count = 3; else if (strcmp(decomposition, "TSVM_alpha_s3") == 0) band_count = 3; else if (strcmp(decomposition, "TSVM_phi_s3") == 0) band_count = 3; else if (strcmp(decomposition, "TSVM_tau_m3") == 0) band_count = 3; else if (strcmp(decomposition, "TSVM_psi3") == 0) band_count = 3; else if (strcmp(decomposition, "TSVM_psi") == 0) band_count = 4; for (ll=0; ll<band_count; ll++) { if (strcmp(decomposition, "Freeman2_Vol") == 0 && strncmp(band_name[kk], freeman2_decomposition[ll], strlen(band_name[kk])) == 0) found_band = TRUE; else if (strcmp(decomposition, "Freeman_Vol") == 0 && strncmp(band_name[kk], freeman3_decomposition[ll], strlen(band_name[kk])) == 0) found_band = TRUE; else if (strcmp(decomposition, "VanZyl3_Vol") == 0 && strncmp(band_name[kk], vanZyl3_decomposition[ll], strlen(band_name[kk])) == 0) found_band = TRUE; else if (strcmp(decomposition, "Yamaguchi3_Vol") == 0 && strncmp(band_name[kk], yamaguchi3_decomposition[ll], strlen(band_name[kk])) == 0) found_band = TRUE; else if (strcmp(decomposition, "Yamaguchi4_Vol") == 0 && strncmp(band_name[kk], yamaguchi4_decomposition[ll], strlen(band_name[kk])) == 0) found_band = TRUE; else if (strcmp(decomposition, "Krogager_Ks") == 0 && strncmp(band_name[kk], krogager_decomposition[ll], strlen(band_name[kk])) == 0) found_band = TRUE; else if (strcmp(decomposition, "TSVM_alpha_s3") == 0 && strncmp(band_name[kk], touzi1_decomposition[ll], strlen(band_name[kk])) == 0) found_band = TRUE; else if (strcmp(decomposition, "TSVM_phi_s3") == 0 && strncmp(band_name[kk], touzi2_decomposition[ll], strlen(band_name[kk])) == 0) found_band = TRUE; else if (strcmp(decomposition, "TSVM_tau_m3") == 0 && strncmp(band_name[kk], touzi3_decomposition[ll], strlen(band_name[kk])) == 0) found_band = TRUE; else if (strcmp(decomposition, "TSVM_psi3") == 0 && strncmp(band_name[kk], touzi4_decomposition[ll], strlen(band_name[kk])) == 0) found_band = TRUE; else if (strcmp(decomposition, "TSVM_psi") == 0 && strncmp(band_name[kk], touzi5_decomposition[ll], strlen(band_name[kk])) == 0) found_band = TRUE; } if (!found_band) continue; sprintf(out_file, "%s%c%s", path_name, DIR_SEPARATOR, band_name[kk]); } else if (md->general->image_data_type == POLARIMETRIC_SEGMENTATION || md->general->image_data_type == POLARIMETRIC_PARAMETER) append_band_ext(base_name, out_file, NULL); else { if (band_count > 1) { if (strstr(band_name[kk], "INTERFEROGRAM_PHASE") && is_colormap_band) append_band_ext(base_name, out_file, "INTERFEROGRAM_RGB"); else append_band_ext(base_name, out_file, band_name[kk]); } else append_band_ext(base_name, out_file, NULL); } if (strcmp(band_name[0], MAGIC_UNSET_STRING) != 0) asfPrintStatus("\nWriting band '%s' ...\n", band_name[kk]); if (format == TIF || format == GEOTIFF) { is_geotiff = (format == GEOTIFF) ? 1 : 0; append_ext_if_needed (out_file, ".tif", ".tiff"); if (is_colormap_band && strlen(lut_file) > 0) { //sample_mapping = TRUNCATE; rgb = FALSE; initialize_tiff_file(&otif, &ogtif, out_file, metadata_file_name, is_geotiff, sample_mapping, rgb, &palette_color_tiff, band_name, lut_file, TRUE); } else { initialize_tiff_file(&otif, &ogtif, out_file, metadata_file_name, is_geotiff, sample_mapping, rgb, &palette_color_tiff, band_name, NULL, FALSE); } } else if (format == JPEG) { append_ext_if_needed (out_file, ".jpg", ".jpeg"); if (is_colormap_band) { initialize_jpeg_file(out_file, md, &ojpeg, &cinfo, TRUE); } else { initialize_jpeg_file(out_file, md, &ojpeg, &cinfo, rgb); } } else if (format == PNG) { append_ext_if_needed (out_file, ".png", NULL); if (is_colormap_band) { initialize_png_file(out_file, md, &opng, &png_ptr, &png_info_ptr, TRUE); } else { initialize_png_file(out_file, md, &opng, &png_ptr, &png_info_ptr, rgb); } } else if (format == PNG_ALPHA) { append_ext_if_needed (out_file, ".png", NULL); initialize_png_file_ext(out_file, md, &opng, &png_ptr, &png_info_ptr, FALSE, TRUE); } else if (format == PNG_GE) { append_ext_if_needed (out_file, ".png", NULL); initialize_png_file_ext(out_file, md, &opng, &png_ptr, &png_info_ptr, 1, 2); } else if (format == PGM) { append_ext_if_needed (out_file, ".pgm", ".pgm"); initialize_pgm_file(out_file, md, &opgm); } else if (format == POLSARPRO_HDR) { append_ext_if_needed (out_file, ".bin", NULL); initialize_polsarpro_file(out_file, md, &ofp); } else if (format == HDF) { append_ext_if_needed (out_file, ".h5", NULL); h5 = initialize_h5_file(out_file, md); hdf = (float *) MALLOC(sizeof(float)*md->general->line_count* md->general->sample_count); } else if (format == NC) { append_ext_if_needed (out_file, ".nc", NULL); netcdf = initialize_netcdf_file(out_file, md); nc = (float *) MALLOC(sizeof(float)*md->general->line_count* md->general->sample_count); } else { asfPrintError("Impossible: unexpected format %s\n", format2str(format)); } (*output_names)[*noutputs] = STRDUP(out_file); *noutputs += 1; // Determine which channel to read int channel; if (md->general->image_data_type > POLARIMETRIC_IMAGE && md->general->image_data_type <= POLARIMETRIC_T4_MATRIX) channel = kk; else { if (md->general->band_count == 1) channel = 0; else channel = get_band_number(bands, band_count, band_name[kk]); asfRequire(channel >= 0 && channel <= MAX_BANDS, "Band number out of range\n"); } int sample_count = md->general->sample_count; int offset = md->general->line_count; // Get the statistics if necessary channel_stats_t stats; stats.hist = NULL; stats.hist_pdf = NULL; if (sample_mapping != NONE && sample_mapping != TRUNCATE) { asfRequire (sizeof(unsigned char) == 1, "Size of the unsigned char data type on this machine is " "different than expected.\n"); if (md->stats && md->stats->band_count > 0 && meta_is_valid_double(md->stats->band_stats[channel].mean) && meta_is_valid_double(md->stats->band_stats[channel].min) && meta_is_valid_double(md->stats->band_stats[channel].max) && meta_is_valid_double(md->stats->band_stats[channel].std_deviation) && sample_mapping != HISTOGRAM_EQUALIZE) { asfPrintStatus("Using metadata statistics - skipping stats computations.\n"); stats.min = md->stats->band_stats[channel].min; stats.max = md->stats->band_stats[channel].max; stats.mean = md->stats->band_stats[channel].mean; stats.standard_deviation = md->stats->band_stats[channel].std_deviation; stats.hist = NULL; } else { asfPrintStatus("Gathering statistics ...\n"); calc_stats_from_file(image_data_file_name, band_name[kk], md->general->no_data, &stats.min, &stats.max, &stats.mean, &stats.standard_deviation, &stats.hist); } if (sample_mapping == TRUNCATE && !have_look_up_table) { if (stats.mean >= 255) asfPrintWarning("The image contains HIGH values and will turn out very\n" "bright or all-white.\n Min : %f\n Max : %f\n Mean: %f\n" "=> Consider using a sample mapping method other than TRUNCATE\n", stats.min, stats.max, stats.mean); if (stats.mean < 10) asfPrintWarning("The image contains LOW values and will turn out very\n" "dark or all-black.\n Min : %f\n Max : %f\n Mean: %f\n" "=> Consider using a sample mapping method other than TRUNCATE\n", stats.min, stats.max, stats.mean); } if (sample_mapping == SIGMA) { double omin = stats.mean - 2*stats.standard_deviation; double omax = stats.mean + 2*stats.standard_deviation; if (omin > stats.min) stats.min = omin; if (omax < stats.max) stats.max = omax; } if ( sample_mapping == HISTOGRAM_EQUALIZE ) { stats.hist_pdf = gsl_histogram_pdf_alloc (256); //NUM_HIST_BINS); gsl_histogram_pdf_init (stats.hist_pdf, stats.hist); } } // Write the output image FILE *fp = FOPEN(image_data_file_name, "rb"); float *float_line = (float *) MALLOC(sizeof(float) * sample_count); unsigned char *byte_line = MALLOC(sizeof(unsigned char) * sample_count); asfPrintStatus("Writing output file...\n"); if (is_colormap_band) { // Apply look up table for (ii=0; ii<md->general->line_count; ii++ ) { if ((md->optical || md->general->data_type == BYTE) && md->general->image_data_type != POLARIMETRIC_PARAMETER) { get_byte_line(fp, md, ii+channel*offset, byte_line); if (format == TIF || format == GEOTIFF) write_tiff_byte2lut(otif, byte_line, ii, sample_count, lut_file); else if (format == JPEG) write_jpeg_byte2lut(ojpeg, byte_line, &cinfo, sample_count, lut_file); else if (format == PNG || format == PNG_ALPHA || format == PNG_GE) write_png_byte2lut(opng, byte_line, png_ptr, png_info_ptr, sample_count, lut_file); else asfPrintError("Impossible: unexpected format %s\n", format2str(format)); } else { // Force a sample mapping of TRUNCATE for PolSARpro classifications // (They contain low integer values stored in floats ...contrast // expansion will break the look up in the look up table.) get_float_line(fp, md, ii+channel*offset, float_line); if (format == TIF || format == GEOTIFF) // Unlike the other graphics file formats, the TIFF file uses an embedded // colormap (palette) and therefore each pixel should be a single byte value // where each byte value is an index into the colormap. The other graphics // file formats use interlaced RGB lines and no index or colormap instead. write_tiff_float2byte(otif, float_line, stats, //is_colormap_band ? TRUNCATE : sample_mapping, sample_mapping, md->general->no_data, ii, sample_count); else if (format == JPEG) // Use lut to write an RGB line to the file write_jpeg_float2lut(ojpeg, float_line, &cinfo, stats, //is_colormap_band ? TRUNCATE : sample_mapping, sample_mapping, md->general->no_data, sample_count, lut_file); else if (format == PNG || format == PNG_ALPHA || format == PNG_GE) // Use lut to write an RGB line to the file write_png_float2lut(opng, float_line, png_ptr, png_info_ptr, stats, //is_colormap_band ? TRUNCATE : sample_mapping, sample_mapping, md->general->no_data, sample_count, lut_file); else if (format == PGM) { // Can't put color in a PGM file, so map it to greyscale and write that write_pgm_float2byte(opgm, float_line, stats, //is_colormap_band ? TRUNCATE : sample_mapping, sample_mapping, md->general->no_data, sample_count); } else asfPrintError("Impossible: unexpected format %s\n", format2str(format)); } asfLineMeter(ii, md->general->line_count); } } else { // Regular old single band image (no look up table applied) for (ii=0; ii<md->general->line_count; ii++ ) { if (md->optical || md->general->data_type == BYTE) { get_byte_line(fp, md, ii+channel*offset, byte_line); if (format == TIF || format == GEOTIFF) write_tiff_byte2byte(otif, byte_line, stats, sample_mapping, sample_count, ii); else if (format == JPEG) write_jpeg_byte2byte(ojpeg, byte_line, stats, sample_mapping, &cinfo, sample_count); else if (format == PNG) write_png_byte2byte(opng, byte_line, stats, sample_mapping, png_ptr, png_info_ptr, sample_count); else if (format == PNG_ALPHA) { asfPrintError("PNG_ALPHA not supported.\n"); } else if (format == PNG_GE) write_png_byte2rgbalpha(opng, byte_line, stats, sample_mapping, png_ptr, png_info_ptr, sample_count); else if (format == PGM) write_pgm_byte2byte(opgm, byte_line, stats, sample_mapping, sample_count); else asfPrintError("Impossible: unexpected format %s\n", format2str(format)); } else if (sample_mapping == NONE && !is_colormap_band) { get_float_line(fp, md, ii+channel*offset, float_line); if (format == GEOTIFF || format == TIF) { if (md->general->data_type == REAL32) write_tiff_float2float(otif, float_line, ii); else if (md->general->data_type == INTEGER16) write_tiff_float2int(otif, float_line, ii, md->general->sample_count); } else if (format == POLSARPRO_HDR) { int sample; for (sample=0; sample<sample_count; sample++) ieee_lil32(float_line[sample]); fwrite(float_line,4,sample_count,ofp); } else if (format == HDF) { int sample; for (sample=0; sample<sample_count; sample++) hdf[ii*sample_count+sample] = float_line[sample]; } else if (format == NC) { int sample; for (sample=0; sample<sample_count; sample++) { nc[ii*sample_count+sample] = float_line[sample]; } } else asfPrintError("Impossible: unexpected format %s\n", format2str(format)); } else { get_float_line(fp, md, ii+channel*offset, float_line); if (format == TIF || format == GEOTIFF) write_tiff_float2byte(otif, float_line, stats, //is_colormap_band ? TRUNCATE : sample_mapping, sample_mapping, md->general->no_data, ii, sample_count); else if (format == JPEG) write_jpeg_float2byte(ojpeg, float_line, &cinfo, stats, //is_colormap_band ? TRUNCATE : sample_mapping, sample_mapping, md->general->no_data, sample_count); else if (format == PNG || format == PNG_ALPHA || format == PNG_GE) write_png_float2byte(opng, float_line, png_ptr, png_info_ptr, stats, //is_colormap_band ? TRUNCATE : sample_mapping, sample_mapping, md->general->no_data, sample_count); else if (format == PGM) write_pgm_float2byte(opgm, float_line, stats, //is_colormap_band ? TRUNCATE : sample_mapping, sample_mapping, md->general->no_data, sample_count); else if (format == POLSARPRO_HDR) { int sample; for (sample=0; sample<sample_count; sample++) ieee_lil32(float_line[sample]); fwrite(float_line,4,sample_count,ofp); } else asfPrintError("Impossible: unexpected format %s\n", format2str(format)); } asfLineMeter(ii, md->general->line_count); } // End for each line } // End if multi or single band // Free memory FREE(float_line); FREE(byte_line); if (stats.hist) gsl_histogram_free(stats.hist); if (stats.hist_pdf) gsl_histogram_pdf_free(stats.hist_pdf); // Finalize the chosen format if (format == TIF || format == GEOTIFF) finalize_tiff_file(otif, ogtif, is_geotiff); else if (format == JPEG) finalize_jpeg_file(ojpeg, &cinfo); else if (format == PNG || format == PNG_ALPHA || format == PNG_GE) finalize_png_file(opng, png_ptr, png_info_ptr); else if (format == PGM) finalize_ppm_file(opgm); else if (format == POLSARPRO_HDR) FCLOSE(ofp); else if (format == HDF) { asfPrintStatus("Storing band '%s' ...\n", band_name[kk]); char dataset[50]; sprintf(dataset, "/data/%s_AMPLITUDE_IMAGE", band_name[kk]); hid_t h5_data = H5Dopen(h5->file, dataset, H5P_DEFAULT); H5Dwrite(h5_data, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, hdf); H5Dclose(h5_data); } else if (format == NC) { asfPrintStatus("Storing band '%s' ...\n", band_name[kk]); nc_put_var_float(netcdf->ncid, netcdf->var_id[kk], &nc[0]); } FCLOSE(fp); } } // End for each band (kk is band number) if (hdf) { finalize_h5_file(h5); FREE(hdf); } if (nc) { finalize_netcdf_file(netcdf, md); FREE(nc); } if (free_band_names) { for (ii=0; ii<band_count; ++ii) FREE(band_name[ii]); FREE(band_name); } FREE(path_name); FREE(matrix); FREE(decomposition); FREE(out_file); } if (lut_file && strstr(lut_file, "tmp_lut_file.lut") && fileExists(lut_file)) { // If a temporary look-up table was generated (from an embedded colormap in the // metadata) then remove it now. remove(lut_file); } FREE(lut_file); meta_free (md); } void append_band_names(char **band_names, int rgb, char *citation, int palette_color_tiff) { char band_name[256]; int i=0; sprintf(citation, "%s, %s: ", citation, BAND_ID_STRING); if (band_names) { if (rgb && !palette_color_tiff) { // RGB tiffs that do not use a color index (palette) have 3 bands, but // palette color tiffs have a single band and an RGB look-up table (TIFFTAG_COLORMAP) // // When the image uses a look-up table, then meta->general->bands lists the look-up table // name rather than a list of individual band names. band_names[] will therefore only have // a single entry. // // When a color image does not use a look-up table, then meta->general->bands contains // the list of band names, one for each band, separated by commas. It's safe to expect // the band_names[] array to contain 3 bands in this case. for (i=0; i<2; i++) { // First 2 bands have a comma after the band name if (band_names[i] != NULL && strlen(band_names[i]) > 0 && strncmp(band_names[i], MAGIC_UNSET_STRING, strlen(MAGIC_UNSET_STRING)) != 0) { sprintf(band_name, "%s,", strncmp("IGNORE", uc(band_names[i]), 6) == 0 ? "Empty" : band_names[i]); strcat(citation, band_name); } else { sprintf(band_name, "%02d,", i + 1); strcat(citation, band_name); } } if (band_names[i] != NULL && strlen(band_names[i]) > 0 && strncmp(band_names[i], MAGIC_UNSET_STRING, strlen(MAGIC_UNSET_STRING)) != 0) { strcat(citation, strncmp("IGNORE", uc(band_names[i]), 6) == 0 ? "Empty" : band_names[i]); } else { sprintf(band_name, "%02d", i + 1); strcat(citation, band_name); } } else { // Single band image or a palette color image if (palette_color_tiff) { strcat(citation, band_names[0]); } else { if (band_names[0] != NULL && strlen(band_names[0]) > 0 && strncmp(band_names[i], MAGIC_UNSET_STRING, strlen(MAGIC_UNSET_STRING)) != 0) { strcat(citation, strncmp("IGNORE", uc(band_names[0]), 6) == 0 ? "Empty" : band_names[0]); } else { strcat(citation, "01"); } } } } else { if (rgb && !palette_color_tiff) strcat(citation, "01,02,03"); else strcat(citation, "01"); } } // lut_to_tiff_palette() converts an ASF-style look-up table (text file) into // a TIFF standard RGB palette (indexed color map for TIFFTAG_COLORMAP) int lut_to_tiff_palette(unsigned short **colors, int map_size, char *look_up_table_name) { int i, max_lut_dn; unsigned char *lut = NULL; float r, g, b; asfRequire(map_size >= 1, "TIFF palette color map size less than 1 element\n"); asfRequire(look_up_table_name != NULL && strlen(look_up_table_name) > 0, "Invalid look up table name\n"); // Use CALLOC so the entire look up table is initialized to zero lut = (unsigned char *)CALLOC(MAX_LUT_DN * 3, sizeof(unsigned char)); // Read the look up table from the file. It will be 3-color and have MAX_LUT_DN*3 elements // in the array, in packed format <rgbrgbrgb...rgb>, and values range from 0 to 255 max_lut_dn = read_lut(look_up_table_name, lut); if (max_lut_dn > map_size) { FREE(lut); asfPrintError("Look-up table too large (%d) for TIFF. Maximum TIFF\n" "look-up table size for the data type is %d elements long.\n", max_lut_dn, map_size); } *colors = (unsigned short *)_TIFFmalloc(sizeof(unsigned short) * 3 * map_size); asfRequire(*colors != NULL, "Could not allocate TIFF palette.\n"); for (i = 0; i < 3 * map_size; i++) (*colors)[i] = (unsigned short)0; // Init to all zeros // Normalize the look-up table values into the range specified by the TIFF standard // (0 through 65535 ...the maximum unsigned short value) for (i=0; i<max_lut_dn; i++) { // TIFF color map structure is a one-row array, all the reds, then all the // greens, then all the blues, i.e. <all reds><all greens><all blues>, each // section 'map_size' elements long // // Grab rgb values from the lut r = (float)lut[i*3 ]; g = (float)lut[i*3+1]; b = (float)lut[i*3+2]; // Normalize the lut values to the 0-65535 range as specified by the TIFF standard for // color maps / palettes (*colors)[i ] = (unsigned short) ((r/(float)MAX_RGB)*(float)USHORT_MAX + 0.5); (*colors)[i + map_size] = (unsigned short) ((g/(float)MAX_RGB)*(float)USHORT_MAX + 0.5); (*colors)[i + 2*map_size] = (unsigned short) ((b/(float)MAX_RGB)*(float)USHORT_MAX + 0.5); } return max_lut_dn; } // Assumes the color map is made from unsigned shorts (uint16 or equiv). a) This is mandated // by v6 of the TIFF standard regardless of data type in the tiff, b) The only valid // data types for a colormap TIFF is i) 4-bit unsigned integer, or ii) 8-bit unsigned integer, // and c) the values in a TIFF colormap range from 0 to 65535 (max uint16) and must be normalized // to 0-255 as for display (the range 0-255 is normalize to 0-65535 when creating the colormap // in the first place.) void dump_palette_tiff_color_map(unsigned short *colors, int map_size) { int i; asfRequire(map_size <= 256, "Map size too large.\n"); fprintf(stderr, "\n\nColor Map (DN: red green blue):\n"); for (i=0; i<map_size; i++){ fprintf(stderr, "%d:\t%d\t%d\t%d\n", i, (int)((float)colors[i + 0]*((float)MAX_RGB/(float)USHORT_MAX) + 0.5), (int)((float)colors[i + map_size]*((float)MAX_RGB/(float)USHORT_MAX) + 0.5), (int)((float)colors[i + 2*map_size]*((float)MAX_RGB/(float)USHORT_MAX) + 0.5)); } } int meta_colormap_to_tiff_palette(unsigned short **tiff_palette, int *byte_image, meta_colormap *colormap) { int i, size; unsigned short r, g, b; meta_colormap *cm = colormap; // Convenience ptr asfRequire(colormap != NULL, "Unallocated colormap.\n"); size = cm->num_elements; *tiff_palette = (unsigned short *)CALLOC(3*size, sizeof(unsigned short)); // A TIFF palette is a one dimensional array ...all the reds, then all the greens, then all the blues // Create TIFF palette by normalizing 0-255 range into 0-65535 and storing in the band sequential // array. for (i=0; i<size; i++) { r = cm->rgb[i].red; g = cm->rgb[i].green; b = cm->rgb[i].blue; (*tiff_palette)[i + 0] = (unsigned short) (((float)r/(float)MAX_RGB)*(float)USHORT_MAX + 0.5); (*tiff_palette)[i + size] = (unsigned short) (((float)g/(float)MAX_RGB)*(float)USHORT_MAX + 0.5); (*tiff_palette)[i + 2*size] = (unsigned short) (((float)b/(float)MAX_RGB)*(float)USHORT_MAX + 0.5); } return size; } char *sample_mapping2string(scale_t sample_mapping) { switch(sample_mapping) { case TRUNCATE: return "TRUNCATE"; break; case MINMAX: return "MIN-MAX"; break; case SIGMA: return "2-SIGMA"; break; case HISTOGRAM_EQUALIZE: return "HISTOGRAM EQUALIZE"; break; case NONE: return "NONE"; break; default: return "UNKNOWN or UNRECOGNIZED"; break; } } void colormap_to_lut_file(meta_colormap *cm, const char *lut_file) { int i; char line[256]; FILE *fp = FOPEN(lut_file, "wt"); fprintf(fp, "# Temporary look-up table file for asf_export\n"); fprintf(fp, "# Look-up table : %s\n", cm->look_up_table); fprintf(fp, "# Number of elements: %d\n", cm->num_elements); fprintf(fp, "# Index Red Green Blue\n"); for (i=0; i<cm->num_elements; i++) { sprintf(line, "%d %d %d %d\n", i, cm->rgb[i].red, cm->rgb[i].green, cm->rgb[i].blue); fprintf(fp, line); } FCLOSE(fp); }
{ "alphanum_fraction": 0.6051783567, "avg_line_length": 42.9875947622, "ext": "c", "hexsha": "7faebdfad2f292b32a9bb2e9d4a061631e8dfbb7", "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_export/export_band.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_export/export_band.c", "max_line_length": 108, "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_export/export_band.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": 32121, "size": 124750 }
/** * \file RIAAFilter.h * Filters for RIAA correction */ #ifndef ATK_EQ_RIAAFILTER_H #define ATK_EQ_RIAAFILTER_H #include <gsl/gsl> #include <ATK/EQ/SecondOrderFilter.h> namespace ATK { /// RIAA coefficients used for RIAA correction template<typename DataType_> class RIAACoefficients : public SecondOrderCoreCoefficients<DataType_> { public: /// Simplify parent calls using Parent = SecondOrderCoreCoefficients<DataType_>; using typename Parent::AlignedScalarVector; using typename Parent::DataType; using CoeffDataType = typename TypeTraits<DataType>::Scalar; using Parent::input_sampling_rate; using Parent::output_sampling_rate; using Parent::setup; protected: using Parent::in_order; using Parent::out_order; using Parent::coefficients_in; using Parent::coefficients_out; void setup() override; public: /*! * @brief Constructor * @param nb_channels is the number of input and output channels */ explicit RIAACoefficients(gsl::index nb_channels = 1); }; /// RIAA coefficients used to create the inverse compensation (for mastering engineers) template<typename DataType_> class InverseRIAACoefficients : public SecondOrderCoreCoefficients<DataType_> { public: /// Simplify parent calls using Parent = SecondOrderCoreCoefficients<DataType_>; using typename Parent::AlignedScalarVector; using typename Parent::DataType; using CoeffDataType = typename TypeTraits<DataType>::Scalar; using Parent::input_sampling_rate; using Parent::output_sampling_rate; using Parent::setup; protected: using Parent::in_order; using Parent::out_order; using Parent::coefficients_in; using Parent::coefficients_out; void setup() override; public: /*! * @brief Constructor * @param nb_channels is the number of input and output channels */ explicit InverseRIAACoefficients(gsl::index nb_channels = 1); }; } #endif
{ "alphanum_fraction": 0.7232232232, "avg_line_length": 26.64, "ext": "h", "hexsha": "323419467b1e127b7e16ed6b24b38b5f42d02876", "lang": "C", "max_forks_count": 48, "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:33:07.000Z", "max_forks_repo_forks_event_min_datetime": "2015-08-15T12:08:13.000Z", "max_forks_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "D-J-Roberts/AudioTK", "max_forks_repo_path": "ATK/EQ/RIAAFilter.h", "max_issues_count": 22, "max_issues_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_issues_repo_issues_event_max_datetime": "2020-07-11T14:18:19.000Z", "max_issues_repo_issues_event_min_datetime": "2015-07-28T15:20:24.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "D-J-Roberts/AudioTK", "max_issues_repo_path": "ATK/EQ/RIAAFilter.h", "max_line_length": 89, "max_stars_count": 249, "max_stars_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "D-J-Roberts/AudioTK", "max_stars_repo_path": "ATK/EQ/RIAAFilter.h", "max_stars_repo_stars_event_max_datetime": "2022-03-15T18:47:46.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-05T13:36:26.000Z", "num_tokens": 470, "size": 1998 }
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* ** ** ** 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. ** ** ** **~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/ #ifndef __StgFEM_Discretisation_Discretisation_h__ #define __StgFEM_Discretisation_Discretisation_h__ #include "types.h" #include <petsc.h> #include <petscvec.h> #include <petscmat.h> #include <petscksp.h> #if( (PETSC_VERSION_MAJOR==3 && PETSC_VERSION_MINOR==0) || (PETSC_VERSION_MAJOR<3) ) #include <petscmg.h> #endif #include <petscsnes.h> #include "PETScErrorChecking.h" #include "FeMesh_Algorithms.h" #include "FeMesh_ElementType.h" #include "ElementType.h" #include "ElementType_Register.h" #include "ConstantElementType.h" #include "LinearElementType.h" #include "BilinearElementType.h" #include "TrilinearElementType.h" #include "Biquadratic.h" #include "Triquadratic.h" #include "LinearTriangleElementType.h" #include "BilinearInnerElType.h" #include "TrilinearInnerElType.h" #include "dQ13DElementType.h" #include "dQ12DElementType.h" #include "dQ1Generator.h" #include "Element.h" #include "FeMesh.h" #include "C0Generator.h" #include "C2Generator.h" #include "Inner2DGenerator.h" #include "LinkedDofInfo.h" #include "FeEquationNumber.h" #include "FeVariable.h" #include "IrregularMeshGaussLayout.h" #include "Init.h" #include "Finalise.h" #endif /* __StgFEM_Discretisation_Discretisation_h__ */
{ "alphanum_fraction": 0.5736118186, "avg_line_length": 33.2711864407, "ext": "h", "hexsha": "63a9a010a5bdf5a005dc78b6273ad7e31b03703b", "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/StgFEM/Discretisation/src/Discretisation.h", "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/StgFEM/Discretisation/src/Discretisation.h", "max_line_length": 87, "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/StgFEM/Discretisation/src/Discretisation.h", "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": 590, "size": 1963 }
#include <gsl/gsl_vector.h> #include "icp.h" #include "../csm_all.h" int compatible(struct sm_params*params, int i, int j); int compatible(struct sm_params*params, int i, int j) { if(!params->do_alpha_test) return 1; double theta0 = 0; /* FIXME */ if((params->laser_sens->alpha_valid[i]==0) || (params->laser_ref->alpha_valid[j]==0)) return 1; double alpha_i = params->laser_sens->alpha[i]; double alpha_j = params->laser_ref->alpha[j]; double tolerance = deg2rad(params->do_alpha_test_thresholdDeg); /** FIXME remove alpha test */ double theta = angleDiff(alpha_j, alpha_i); if(fabs(angleDiff(theta,theta0))> tolerance+deg2rad(params->max_angular_correction_deg)) { return 0; } else { return 1; } } void find_correspondences(struct sm_params*params) { const LDP laser_ref = params->laser_ref; const LDP laser_sens = params->laser_sens; int i; for(i=0;i<laser_sens->nrays;i++) { if(!ld_valid_ray(laser_sens,i)) { /* sm_debug("dumb: i %d is invalid \n", i);*/ ld_set_null_correspondence(laser_sens, i); continue; } double *p_i_w = laser_sens->points_w[i].p; int j1 = -1; double best_dist = 10000; int from; int to; int start_cell; possible_interval(p_i_w, laser_ref, params->max_angular_correction_deg, params->max_linear_correction, &from, &to, &start_cell); /* sm_debug("dumb: i %d from %d to %d \n", i, from, to); */ int j; for(j=from;j<=to;j++) { if(!ld_valid_ray(laser_ref,j)) { /* sm_debug("dumb: i %d j %d invalid\n", i, j);*/ continue; } double dist = distance_squared_d(p_i_w, laser_ref->points[j].p); /* sm_debug("dumb: i %d j1 %d j %d d %f\n", i,j1,j,dist);*/ if(dist>square(params->max_correspondence_dist)) continue; if( (-1 == j1) || (dist < best_dist) ) { if(compatible(params, i, j)) { j1 = j; best_dist = dist; } } } if(j1==-1) {/* no match */ ld_set_null_correspondence(laser_sens, i); continue; } /* Do not match with extrema*/ if(j1==0 || (j1 == (laser_ref->nrays-1))) {/* no match */ ld_set_null_correspondence(laser_sens, i); continue; } int j2; int j2up = ld_next_valid_up (laser_ref, j1); int j2down = ld_next_valid_down (laser_ref, j1); if((j2up==-1)&&(j2down==-1)) { ld_set_null_correspondence(laser_sens, i); continue; } if(j2up ==-1) { j2 = j2down; } else if(j2down==-1) { j2 = j2up; } else { double dist_up = distance_squared_d(p_i_w, laser_ref->points[j2up ].p); double dist_down = distance_squared_d(p_i_w, laser_ref->points[j2down].p); j2 = dist_up < dist_down ? j2up : j2down; } ld_set_correspondence(laser_sens, i, j1, j2); laser_sens->corr[i].dist2_j1 = best_dist; laser_sens->corr[i].type = params->use_point_to_line_distance ? corr_pl : corr_pp; } }
{ "alphanum_fraction": 0.6495543672, "avg_line_length": 27.2330097087, "ext": "c", "hexsha": "025b89ab5bf3484bf99ca613482ce64aa12d89fd", "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": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "alecone/ROS_project", "max_forks_repo_path": "src/csm/sm/csm/icp/icp_corr_dumb.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "alecone/ROS_project", "max_issues_repo_path": "src/csm/sm/csm/icp/icp_corr_dumb.c", "max_line_length": 77, "max_stars_count": null, "max_stars_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "alecone/ROS_project", "max_stars_repo_path": "src/csm/sm/csm/icp/icp_corr_dumb.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 950, "size": 2805 }
/* # # * The source code in this file is developed independently by NEC Corporation. # # # NLCPy License # # # Copyright (c) 2020-2021 NEC Corporation # 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. # * Neither NEC Corporation nor the names of its contributors may be # used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # */ #include <cblas.h> #include "nlcpy.h" uint64_t wrapper_cblas_sdot(ve_arguments *args, int32_t *psw) { #ifdef _OPENMP #pragma omp single #endif /* _OPENMP */ { ve_array *x = &(args->binary.x); ve_array *y = &(args->binary.y); ve_array *z = &(args->binary.z); float *px = (float *)x->ve_adr; if (px == NULL) { px = (float *)nlcpy__get_scalar(x); if (px == NULL) { return NLCPY_ERROR_MEMORY; } } float *py = (float *)y->ve_adr; if (py == NULL) { py = (float *)nlcpy__get_scalar(y); if (py == NULL) { return NLCPY_ERROR_MEMORY; } } float *pz = (float *)z->ve_adr; if (pz == NULL) { return (uint64_t)NLCPY_ERROR_MEMORY; } assert(x->ndim <= 1); assert(y->ndim <= 1); assert(z->ndim <= 1); assert(x->size == y->size); *pz = cblas_sdot(x->size, px, x->strides[0] / x->itemsize, py, y->strides[0] / y->itemsize); } /* omp single */ retrieve_fpe_flags(psw); return (uint64_t)NLCPY_ERROR_OK; } uint64_t wrapper_cblas_ddot(ve_arguments *args, int32_t *psw) { #ifdef _OPENMP #pragma omp single #endif /* _OPENMP */ { ve_array *x = &(args->binary.x); ve_array *y = &(args->binary.y); ve_array *z = &(args->binary.z); double *px = (double *)x->ve_adr; if (px == NULL) { px = (double *)nlcpy__get_scalar(x); if (px == NULL) { return NLCPY_ERROR_MEMORY; } } double *py = (double *)y->ve_adr; if (py == NULL) { py = (double *)nlcpy__get_scalar(y); if (py == NULL) { return NLCPY_ERROR_MEMORY; } } double *pz = (double *)z->ve_adr; if (pz == NULL) { return (uint64_t)NLCPY_ERROR_MEMORY; } assert(x->ndim <= 1); assert(y->ndim <= 1); assert(z->ndim <= 1); assert(x->size == y->size); *pz = cblas_ddot(x->size, px, x->strides[0] / x->itemsize, py, y->strides[0] / y->itemsize); } /* omp single */ retrieve_fpe_flags(psw); return (uint64_t)NLCPY_ERROR_OK; } uint64_t wrapper_cblas_cdotu_sub(ve_arguments *args, int32_t *psw) { #ifdef _OPENMP #pragma omp single #endif /* _OPENMP */ { ve_array *x = &(args->binary.x); ve_array *y = &(args->binary.y); ve_array *z = &(args->binary.z); float _Complex *px = (float _Complex *)x->ve_adr; if (px == NULL) { px = (float _Complex *)nlcpy__get_scalar(x); if (px == NULL) { return NLCPY_ERROR_MEMORY; } } float _Complex *py = (float _Complex *)y->ve_adr; if (py == NULL) { py = (float _Complex *)nlcpy__get_scalar(y); if (py == NULL) { return NLCPY_ERROR_MEMORY; } } float _Complex *pz = (float _Complex *)z->ve_adr; if (pz == NULL) { return (uint64_t)NLCPY_ERROR_MEMORY; } assert(x->ndim <= 1); assert(y->ndim <= 1); assert(z->ndim <= 1); assert(x->size == y->size); cblas_cdotu_sub(x->size, px, x->strides[0] / x->itemsize, py, y->strides[0] / y->itemsize, pz); } /* omp single */ retrieve_fpe_flags(psw); return (uint64_t)NLCPY_ERROR_OK; } uint64_t wrapper_cblas_zdotu_sub(ve_arguments *args, int32_t *psw) { #ifdef _OPENMP #pragma omp single #endif /* _OPENMP */ { ve_array *x = &(args->binary.x); ve_array *y = &(args->binary.y); ve_array *z = &(args->binary.z); double _Complex *px = (double _Complex *)x->ve_adr; if (px == NULL) { px = (double _Complex *)nlcpy__get_scalar(x); if (px == NULL) { return NLCPY_ERROR_MEMORY; } } double _Complex *py = (double _Complex *)y->ve_adr; if (py == NULL) { py = (double _Complex *)nlcpy__get_scalar(y); if (py == NULL) { return NLCPY_ERROR_MEMORY; } } double _Complex *pz = (double _Complex *)z->ve_adr; if (pz == NULL) { return (uint64_t)NLCPY_ERROR_MEMORY; } assert(x->ndim <= 1); assert(y->ndim <= 1); assert(z->ndim <= 1); assert(x->size == y->size); cblas_zdotu_sub(x->size, px, x->strides[0] / x->itemsize, py, y->strides[0] / y->itemsize, pz); } /* omp single */ retrieve_fpe_flags(psw); return (uint64_t)NLCPY_ERROR_OK; } uint64_t wrapper_cblas_sgemm(ve_arguments *args, int32_t *psw) { const int32_t order = args->gemm.order; const int32_t transA = args->gemm.transA; const int32_t transB = args->gemm.transB; const int32_t m = args->gemm.m; const int32_t n = args->gemm.n; const int32_t k = args->gemm.k; const float alpha = *((float *)nlcpy__get_scalar(&(args->gemm.alpha))); float* const a = (float *)args->gemm.a.ve_adr; const int32_t lda = args->gemm.lda; float* const b = (float *)args->gemm.b.ve_adr; const int32_t ldb = args->gemm.ldb; const float beta = *((float *)nlcpy__get_scalar(&(args->gemm.beta))); float* const c = (float *)args->gemm.c.ve_adr; const int32_t ldc = args->gemm.ldc; if (a == NULL || b == NULL || c == NULL) { return NLCPY_ERROR_MEMORY; } #ifdef _OPENMP const int32_t nt = omp_get_num_threads(); const int32_t it = omp_get_thread_num(); #else const int32_t nt = 1; const int32_t it = 0; #endif /* _OPENMP */ const int32_t m_s = m * it / nt; const int32_t m_e = m * (it + 1) / nt; const int32_t m_d = m_e - m_s; const int32_t n_s = n * it / nt; const int32_t n_e = n * (it + 1) / nt; const int32_t n_d = n_e - n_s; int32_t mode = 1; if ( n > nt ) { mode = 2; } int32_t iar, iac, ibr, ibc, icr, icc; if (transA == CblasNoTrans ) { iar = 1; iac = lda; } else { iar = lda; iac = 1; } if (transB == CblasNoTrans ) { ibr = 1; ibc = ldb; } else { ibr = ldb; ibc = 1; } if (order == CblasColMajor ) { icr = 1; icc = ldc; } else { icr = ldc; icc = 1; } if (order == CblasColMajor) { if ( mode == 1 ) { // split 'm' cblas_sgemm(order, transA, transB, m_d, n, k, alpha, a + m_s * iar, lda, b, ldb, beta, c + m_s * icr, ldc); } else { // split 'n' cblas_sgemm(order, transA, transB, m, n_d, k, alpha, a, lda, b + n_s * ibc, ldb, beta, c + n_s * icc, ldc); } } else { if ( mode == 1 ) { // split 'm' cblas_sgemm(order, transA, transB, m_d, n, k, alpha, a + m_s * iac, lda, b, ldb, beta, c + m_s * icr, ldc); } else { // split 'n' cblas_sgemm(order, transA, transB, m, n_d, k, alpha, a, lda, b + n_s * ibr, ldb, beta, c + n_s * icc, ldc); } } retrieve_fpe_flags(psw); return (uint64_t)NLCPY_ERROR_OK; } uint64_t wrapper_cblas_dgemm(ve_arguments *args, int32_t *psw) { const int32_t order = args->gemm.order; const int32_t transA = args->gemm.transA; const int32_t transB = args->gemm.transB; const int32_t m = args->gemm.m; const int32_t n = args->gemm.n; const int32_t k = args->gemm.k; const double alpha = *((double *)nlcpy__get_scalar(&(args->gemm.alpha))); double* const a = (double *)args->gemm.a.ve_adr; const int32_t lda = args->gemm.lda; double* const b = (double *)args->gemm.b.ve_adr; const int32_t ldb = args->gemm.ldb; const double beta = *((double *)nlcpy__get_scalar(&(args->gemm.beta))); double* const c = (double *)args->gemm.c.ve_adr; const int32_t ldc = args->gemm.ldc; if (a == NULL || b == NULL || c == NULL) { return NLCPY_ERROR_MEMORY; } #ifdef _OPENMP const int32_t nt = omp_get_num_threads(); const int32_t it = omp_get_thread_num(); #else const int32_t nt = 1; const int32_t it = 0; #endif /* _OPENMP */ const int32_t m_s = m * it / nt; const int32_t m_e = m * (it + 1) / nt; const int32_t m_d = m_e - m_s; const int32_t n_s = n * it / nt; const int32_t n_e = n * (it + 1) / nt; const int32_t n_d = n_e - n_s; int32_t mode = 1; if ( n > nt ) { mode = 2; } int32_t iar, iac, ibr, ibc, icr, icc; if (transA == CblasNoTrans ) { iar = 1; iac = lda; } else { iar = lda; iac = 1; } if (transB == CblasNoTrans ) { ibr = 1; ibc = ldb; } else { ibr = ldb; ibc = 1; } if (order == CblasColMajor ) { icr = 1; icc = ldc; } else { icr = ldc; icc = 1; } if (order == CblasColMajor) { if ( mode == 1 ) { // split 'm' cblas_dgemm(order, transA, transB, m_d, n, k, alpha, a + m_s * iar, lda, b, ldb, beta, c + m_s * icr, ldc); } else { // split 'n' cblas_dgemm(order, transA, transB, m, n_d, k, alpha, a, lda, b + n_s * ibc, ldb, beta, c + n_s * icc, ldc); } } else { if ( mode == 1 ) { // split 'm' cblas_dgemm(order, transA, transB, m_d, n, k, alpha, a + m_s * iac, lda, b, ldb, beta, c + m_s * icr, ldc); } else { // split 'n' cblas_dgemm(order, transA, transB, m, n_d, k, alpha, a, lda, b + n_s * ibr, ldb, beta, c + n_s * icc, ldc); } } retrieve_fpe_flags(psw); return (uint64_t)NLCPY_ERROR_OK; } uint64_t wrapper_cblas_cgemm(ve_arguments *args, int32_t *psw) { const int32_t order = args->gemm.order; const int32_t transA = args->gemm.transA; const int32_t transB = args->gemm.transB; const int32_t m = args->gemm.m; const int32_t n = args->gemm.n; const int32_t k = args->gemm.k; const void *alpha = (void *)nlcpy__get_scalar(&(args->gemm.alpha)); if (alpha == NULL) return (uint64_t)NLCPY_ERROR_MEMORY; float _Complex* const a = (float _Complex *)args->gemm.a.ve_adr; const int32_t lda = args->gemm.lda; float _Complex* const b = (float _Complex *)args->gemm.b.ve_adr; const int32_t ldb = args->gemm.ldb; const void *beta = (void *)nlcpy__get_scalar(&(args->gemm.beta)); if (beta == NULL) return (uint64_t)NLCPY_ERROR_MEMORY; float _Complex* const c = (float _Complex *)args->gemm.c.ve_adr; const int32_t ldc = args->gemm.ldc; if (a == NULL || b == NULL || c == NULL) { return NLCPY_ERROR_MEMORY; } #ifdef _OPENMP const int32_t nt = omp_get_num_threads(); const int32_t it = omp_get_thread_num(); #else const int32_t nt = 1; const int32_t it = 0; #endif /* _OPENMP */ const int32_t m_s = m * it / nt; const int32_t m_e = m * (it + 1) / nt; const int32_t m_d = m_e - m_s; const int32_t n_s = n * it / nt; const int32_t n_e = n * (it + 1) / nt; const int32_t n_d = n_e - n_s; int32_t mode = 1; if ( n > nt ) { mode = 2; } int32_t iar, iac, ibr, ibc, icr, icc; if (transA == CblasNoTrans ) { iar = 1; iac = lda; } else { iar = lda; iac = 1; } if (transB == CblasNoTrans ) { ibr = 1; ibc = ldb; } else { ibr = ldb; ibc = 1; } if (order == CblasColMajor ) { icr = 1; icc = ldc; } else { icr = ldc; icc = 1; } if (order == CblasColMajor) { if ( mode == 1 ) { // split 'm' cblas_cgemm(order, transA, transB, m_d, n, k, alpha, a + m_s * iar, lda, b, ldb, beta, c + m_s * icr, ldc); } else { // split 'n' cblas_cgemm(order, transA, transB, m, n_d, k, alpha, a, lda, b + n_s * ibc, ldb, beta, c + n_s * icc, ldc); } } else { if ( mode == 1 ) { // split 'm' cblas_cgemm(order, transA, transB, m_d, n, k, alpha, a + m_s * iac, lda, b, ldb, beta, c + m_s * icr, ldc); } else { // split 'n' cblas_cgemm(order, transA, transB, m, n_d, k, alpha, a, lda, b + n_s * ibr, ldb, beta, c + n_s * icc, ldc); } } retrieve_fpe_flags(psw); return (uint64_t)NLCPY_ERROR_OK; } uint64_t wrapper_cblas_zgemm(ve_arguments *args, int32_t *psw) { const int32_t order = args->gemm.order; const int32_t transA = args->gemm.transA; const int32_t transB = args->gemm.transB; const int32_t m = args->gemm.m; const int32_t n = args->gemm.n; const int32_t k = args->gemm.k; const void *alpha = (void *)nlcpy__get_scalar(&(args->gemm.alpha)); if (alpha == NULL) return (uint64_t)NLCPY_ERROR_MEMORY; double _Complex* const a = (double _Complex *)args->gemm.a.ve_adr; const int32_t lda = args->gemm.lda; double _Complex* const b = (double _Complex *)args->gemm.b.ve_adr; const int32_t ldb = args->gemm.ldb; const void *beta = (void *)nlcpy__get_scalar(&(args->gemm.beta)); if (beta == NULL) return (uint64_t)NLCPY_ERROR_MEMORY; double _Complex* const c = (double _Complex *)args->gemm.c.ve_adr; const int32_t ldc = args->gemm.ldc; if (a == NULL || b == NULL || c == NULL) { return NLCPY_ERROR_MEMORY; } #ifdef _OPENMP const int32_t nt = omp_get_num_threads(); const int32_t it = omp_get_thread_num(); #else const int32_t nt = 1; const int32_t it = 0; #endif /* _OPENMP */ const int32_t m_s = m * it / nt; const int32_t m_e = m * (it + 1) / nt; const int32_t m_d = m_e - m_s; const int32_t n_s = n * it / nt; const int32_t n_e = n * (it + 1) / nt; const int32_t n_d = n_e - n_s; int32_t mode = 1; if ( n > nt ) { mode = 2; } int32_t iar, iac, ibr, ibc, icr, icc; if (transA == CblasNoTrans ) { iar = 1; iac = lda; } else { iar = lda; iac = 1; } if (transB == CblasNoTrans ) { ibr = 1; ibc = ldb; } else { ibr = ldb; ibc = 1; } if (order == CblasColMajor ) { icr = 1; icc = ldc; } else { icr = ldc; icc = 1; } if (order == CblasColMajor) { if ( mode == 1 ) { // split 'm' cblas_zgemm(order, transA, transB, m_d, n, k, alpha, a + m_s * iar, lda, b, ldb, beta, c + m_s * icr, ldc); } else { // split 'n' cblas_zgemm(order, transA, transB, m, n_d, k, alpha, a, lda, b + n_s * ibc, ldb, beta, c + n_s * icc, ldc); } } else { if ( mode == 1 ) { // split 'm' cblas_zgemm(order, transA, transB, m_d, n, k, alpha, a + m_s * iac, lda, b, ldb, beta, c + m_s * icr, ldc); } else { // split 'n' cblas_zgemm(order, transA, transB, m, n_d, k, alpha, a, lda, b + n_s * ibr, ldb, beta, c + n_s * icc, ldc); } } retrieve_fpe_flags(psw); return (uint64_t)NLCPY_ERROR_OK; }
{ "alphanum_fraction": 0.555622297, "avg_line_length": 30.1048824593, "ext": "c", "hexsha": "8b952d2151ef859cfef0e26b4663f0a39c98ef23", "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": "0a53eec8778073bc48b12687b7ce37ab2bf2b7e0", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "SX-Aurora/nlcpy", "max_forks_repo_path": "nlcpy/ve_kernel/cblas_wrapper.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0a53eec8778073bc48b12687b7ce37ab2bf2b7e0", "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": "SX-Aurora/nlcpy", "max_issues_repo_path": "nlcpy/ve_kernel/cblas_wrapper.c", "max_line_length": 121, "max_stars_count": 11, "max_stars_repo_head_hexsha": "0a53eec8778073bc48b12687b7ce37ab2bf2b7e0", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "SX-Aurora/nlcpy", "max_stars_repo_path": "nlcpy/ve_kernel/cblas_wrapper.c", "max_stars_repo_stars_event_max_datetime": "2022-03-10T03:12:11.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-31T02:21:55.000Z", "num_tokens": 5413, "size": 16648 }
/* Modified Cholesky Decomposition * * Copyright (C) 2016 Patrick Alken * * This 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, or (at your option) any * later version. * * This source is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_permute_vector.h> #include "cholesky_common.c" /* * This module contains routines related to the Modified Cholesky * Decomposition, which factors a symmetric indefinite matrix A as * * P (A + E) P^T = L D L^T * * where: * P: permutation matrix * E: small, non-negative diagonal matrix * L: unit lower triangular matrix * D: strictly positive diagonal matrix * * These routines follow these works closely: * * [1] P. E. Gill, W. Murray, M. H. Wright, Practical Optimization, * Academic Press, 1981. * * [2] Dennis and Schnabel, Numerical Methods for Unconstrained Optimization * and Nonlinear Equations, SIAM, 1996 */ static size_t mcholesky_maxabs(const gsl_vector * v, double *maxabs); /* gsl_linalg_mcholesky_decomp() Perform Pivoted Modified Cholesky LDLT decomposition of a symmetric positive indefinite matrix: P (A + E) P^T = L D L^T Inputs: A - (input) symmetric, positive indefinite matrix, stored in lower triangle (output) lower triangle contains L; diagonal contains D p - (output) permutation matrix P E - (output) perturbation matrix E Return: success/error Notes: 1) Based on algorithm 4.2.2 (Outer Product LDLT with Pivoting) of Golub and Van Loan, Matrix Computations (4th ed), with modifications described in [1] and [2] 2) E can be set to NULL if not required */ int gsl_linalg_mcholesky_decomp (gsl_matrix * A, gsl_permutation * p, gsl_vector * E) { const size_t N = A->size1; if (N != A->size2) { GSL_ERROR("LDLT decomposition requires square matrix", GSL_ENOTSQR); } else if (p->size != N) { GSL_ERROR ("permutation length must match matrix size", GSL_EBADLEN); } else { const double delta = GSL_DBL_EPSILON; double beta; double gamma = 0.0; double xi = 0.0; gsl_vector_view diag = gsl_matrix_diagonal(A); size_t i, j; /* save a copy of A in upper triangle (for later rcond calculation) */ gsl_matrix_transpose_tricpy('L', 0, A, A); gsl_permutation_init(p); /* compute: * gamma = max | A_{ii} | * xi = max_{i \ne j} | A_{ij} | */ for (i = 0; i < N; ++i) { double aii = gsl_matrix_get(A, i, i); gamma = GSL_MAX(gamma, fabs(aii)); for (j = 0; j < i; ++j) { double aij = gsl_matrix_get(A, i, j); xi = GSL_MAX(xi, fabs(aij)); } } /* compute: * beta = sqrt[ max { gamma, xi/nu, eps } ] * with: nu = max{ sqrt(N^2 - 1), 1 } */ if (N == 1) { beta = GSL_MAX(GSL_MAX(gamma, xi), GSL_DBL_EPSILON); } else { double nu = sqrt(N*N - 1.0); beta = GSL_MAX(GSL_MAX(gamma, xi / nu), GSL_DBL_EPSILON); } beta = sqrt(beta); for (j = 0; j < N; ++j) { double ajj, thetaj, u, alpha, alphainv; gsl_vector_view w; size_t q; /* compute q = max_idx { A_jj, ..., A_nn } */ w = gsl_vector_subvector(&diag.vector, j, N - j); q = mcholesky_maxabs(&w.vector, NULL) + j; gsl_permutation_swap(p, q, j); cholesky_swap_rowcol(A, q, j); /* theta_j = max_{j+1 <= i <= n} |A_{ij}| */ if (j < N - 1) { w = gsl_matrix_subcolumn(A, j, j + 1, N - j - 1); mcholesky_maxabs(&w.vector, &thetaj); } else { thetaj = 0.0; } u = thetaj / beta; /* compute alpha = d_j */ ajj = gsl_matrix_get(A, j, j); alpha = GSL_MAX(GSL_MAX(delta, fabs(ajj)), u * u); alphainv = 1.0 / alpha; if (j < N - 1) { /* v = A(j+1:n, j) */ gsl_vector_view v = gsl_matrix_subcolumn(A, j, j + 1, N - j - 1); /* m = A(j+1:n, j+1:n) */ gsl_matrix_view m = gsl_matrix_submatrix(A, j + 1, j + 1, N - j - 1, N - j - 1); /* m = m - v v^T / alpha */ gsl_blas_dsyr(CblasLower, -alphainv, &v.vector, &m.matrix); /* v = v / alpha */ gsl_vector_scale(&v.vector, alphainv); } if (E) gsl_vector_set(E, j, alpha - ajj); gsl_matrix_set(A, j, j, alpha); } if (E) { /* we currently have: P A P^T + E = L D L^T, permute E * so that we have: P (A + E) P^T = L D L^T */ gsl_permute_vector_inverse(p, E); } return GSL_SUCCESS; } } int gsl_linalg_mcholesky_solve(const gsl_matrix * LDLT, const gsl_permutation * p, const gsl_vector * b, gsl_vector * x) { int status = gsl_linalg_pcholesky_solve(LDLT, p, b, x); return status; } int gsl_linalg_mcholesky_svx(const gsl_matrix * LDLT, const gsl_permutation * p, gsl_vector * x) { int status = gsl_linalg_pcholesky_svx(LDLT, p, x); return status; } int gsl_linalg_mcholesky_rcond (const gsl_matrix * LDLT, const gsl_permutation * p, double * rcond, gsl_vector * work) { int status = gsl_linalg_pcholesky_rcond(LDLT, p, rcond, work); return status; } int gsl_linalg_mcholesky_invert(const gsl_matrix * LDLT, const gsl_permutation * p, gsl_matrix * Ainv) { int status = gsl_linalg_pcholesky_invert(LDLT, p, Ainv); return status; } /* mcholesky_maxabs() Compute: val = max_i |v_i| Inputs: v - vector maxabs - (output) max abs value Return: index corresponding to max_i |v_i| */ static size_t mcholesky_maxabs(const gsl_vector * v, double *maxabs) { const size_t n = v->size; size_t i; size_t idx = 0; double max = gsl_vector_get(v, idx); for (i = 1; i < n; ++i) { double vi = gsl_vector_get(v, i); double absvi = fabs(vi); if (absvi > max) { max = absvi; idx = i; } } if (maxabs) *maxabs = max; return idx; }
{ "alphanum_fraction": 0.5637564618, "avg_line_length": 25.6029411765, "ext": "c", "hexsha": "e02b5aceba625b0ea420da99ea77863f04f4466b", "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": "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/linalg/mcholesky.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "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": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/linalg/mcholesky.c", "max_line_length": 94, "max_stars_count": 1, "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/linalg/mcholesky.c", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "num_tokens": 1998, "size": 6964 }
/* vector/gsl_vector_double.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 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 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_VECTOR_DOUBLE_H__ #define __GSL_VECTOR_DOUBLE_H__ #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/block/gsl_check_range.h> #include <gsl/block/gsl_block_double.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size; //the number of elements in this vector size_t stride; //in the block pointer, this indicates the spacing between elements double *data; //a pointer to the data in this vector gsl_block *block; //a pointer to the block that the data belongs to int owner; //if this is 1 it means that this vector is the owner of this block, otherwise it means it inherited it from somewhere else and it shouldn't be deallocated with the vector } gsl_vector; typedef struct { gsl_vector vector; } _gsl_vector_view; typedef _gsl_vector_view gsl_vector_view; typedef struct { gsl_vector vector; } _gsl_vector_const_view; typedef const _gsl_vector_const_view gsl_vector_const_view; /* Allocation */ GSL_FUNC gsl_vector *gsl_vector_alloc (const size_t n); GSL_FUNC gsl_vector *gsl_vector_calloc (const size_t n); GSL_FUNC gsl_vector *gsl_vector_alloc_from_block (gsl_block * b, const size_t offset, const size_t n, const size_t stride); GSL_FUNC gsl_vector *gsl_vector_alloc_from_vector (gsl_vector * v, const size_t offset, const size_t n, const size_t stride); GSL_FUNC void gsl_vector_free (gsl_vector * v); /* Views */ GSL_FUNC _gsl_vector_view gsl_vector_view_array (double *v, size_t n); GSL_FUNC _gsl_vector_view gsl_vector_view_array_with_stride (double *base, size_t stride, size_t n); GSL_FUNC _gsl_vector_const_view gsl_vector_const_view_array (const double *v, size_t n); GSL_FUNC _gsl_vector_const_view gsl_vector_const_view_array_with_stride (const double *base, size_t stride, size_t n); GSL_FUNC _gsl_vector_view gsl_vector_subvector (gsl_vector *v, size_t i, size_t n); GSL_FUNC _gsl_vector_view gsl_vector_subvector_with_stride (gsl_vector *v, size_t i, size_t stride, size_t n); GSL_FUNC _gsl_vector_const_view gsl_vector_const_subvector (const gsl_vector *v, size_t i, size_t n); GSL_FUNC _gsl_vector_const_view gsl_vector_const_subvector_with_stride (const gsl_vector *v, size_t i, size_t stride, size_t n); /* Operations */ GSL_FUNC double gsl_vector_get (const gsl_vector * v, const size_t i); GSL_FUNC void gsl_vector_set (gsl_vector * v, const size_t i, double x); GSL_FUNC double *gsl_vector_ptr (gsl_vector * v, const size_t i); GSL_FUNC const double *gsl_vector_const_ptr (const gsl_vector * v, const size_t i); GSL_FUNC void gsl_vector_set_zero (gsl_vector * v); GSL_FUNC void gsl_vector_set_all (gsl_vector * v, double x); GSL_FUNC int gsl_vector_set_basis (gsl_vector * v, size_t i); GSL_FUNC int gsl_vector_fread (FILE * stream, gsl_vector * v); GSL_FUNC int gsl_vector_fwrite (FILE * stream, const gsl_vector * v); GSL_FUNC int gsl_vector_fscanf (FILE * stream, gsl_vector * v); GSL_FUNC int gsl_vector_fprintf (FILE * stream, const gsl_vector * v, const char *format); GSL_FUNC int gsl_vector_memcpy (gsl_vector * dest, const gsl_vector * src); GSL_FUNC int gsl_vector_reverse (gsl_vector * v); GSL_FUNC int gsl_vector_swap (gsl_vector * v, gsl_vector * w); GSL_FUNC int gsl_vector_swap_elements (gsl_vector * v, const size_t i, const size_t j); GSL_FUNC double gsl_vector_max (const gsl_vector * v); GSL_FUNC double gsl_vector_min (const gsl_vector * v); GSL_FUNC void gsl_vector_minmax (const gsl_vector * v, double * min_out, double * max_out); GSL_FUNC size_t gsl_vector_max_index (const gsl_vector * v); GSL_FUNC size_t gsl_vector_min_index (const gsl_vector * v); GSL_FUNC void gsl_vector_minmax_index (const gsl_vector * v, size_t * imin, size_t * imax); GSL_FUNC int gsl_vector_add (gsl_vector * a, const gsl_vector * b); GSL_FUNC int gsl_vector_sub (gsl_vector * a, const gsl_vector * b); GSL_FUNC int gsl_vector_mul (gsl_vector * a, const gsl_vector * b); GSL_FUNC int gsl_vector_div (gsl_vector * a, const gsl_vector * b); GSL_FUNC int gsl_vector_scale (gsl_vector * a, const double x); GSL_FUNC int gsl_vector_add_constant (gsl_vector * a, const double x); GSL_FUNC int gsl_vector_isnull (const gsl_vector * v); GSL_FUNC int gsl_vector_ispos (const gsl_vector * v); GSL_FUNC int gsl_vector_isneg (const gsl_vector * v); #ifdef HAVE_INLINE extern inline double gsl_vector_get (const gsl_vector * v, const size_t i) { #if GSL_RANGE_CHECK if (i >= v->size) { GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0); } #endif return v->data[i * v->stride]; } extern inline void gsl_vector_set (gsl_vector * v, const size_t i, double x) { #if GSL_RANGE_CHECK if (i >= v->size) { GSL_ERROR_VOID ("index out of range", GSL_EINVAL); } #endif v->data[i * v->stride] = x; } extern inline double * gsl_vector_ptr (gsl_vector * v, const size_t i) { #if GSL_RANGE_CHECK if (i >= v->size) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return (double *) (v->data + i * v->stride); } extern inline const double * gsl_vector_const_ptr (const gsl_vector * v, const size_t i) { #if GSL_RANGE_CHECK if (i >= v->size) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return (const double *) (v->data + i * v->stride); } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_VECTOR_DOUBLE_H__ */
{ "alphanum_fraction": 0.6633019912, "avg_line_length": 31.7192982456, "ext": "h", "hexsha": "436283bfa40c1e8487c1e2c9c9b65ae9e9ef13a5", "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": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/gsl_vector_double.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "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": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/gsl_vector_double.h", "max_line_length": 185, "max_stars_count": null, "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/gsl_vector_double.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1763, "size": 7232 }
#define _GNU_SOURCE #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 <gsl/gsl_rng.h> #include <gsl/gsl_math.h> #include <gsl/gsl_integration.h> #include "../core_allvars.h" #define LUV_LOOKUPTABLE_MASS 1e6 int32_t init_UVlookup(void) { // For calcUVmag == 1 we must explicitly track the stellar ages of a galaxy. // Then we determine the UV magnitude using the age of the stellar population. // Using STARBURST99 it was determined that the 1600A Luminosty depends on the mass // of stars formed and the time since the starburst. Furthermore, the UV luminosity linearly with the mass of stars formed. // That is, a starburst that forms 6.0e11Msun worth of stars will exhibit 10 times the UV luminosity as a starburst that forms 6.0e10Msun worth of stars. // So if we read in a table that contains the number of ionizing photons emitted from a starburst for a 6.0e10Msun episode, then we can scale our values to this lookup table // using log10 LUV(Msun, t) = (log10 M* - 6.0) + log10 LUV(6.0, t). #define MAXBINS 10000 char fname[MAX_STRING_LEN]; FILE *LUVtable; int32_t num_lines = 0; float t, lambda, LUV, norm_spec; snprintf(fname, MAX_STRING_LEN - 1, ROOT_DIR "/extra/LUV_table.txt"); LUVtable = fopen(fname, "r"); if (LUVtable == NULL) { fprintf(stderr, "Could not open file %s\n", fname); return EXIT_FAILURE; } stars_LUV = calloc(MAXBINS, sizeof(*(stars_LUV))); if (stars_LUV == NULL) { fprintf(stderr, "Could not allocate memory for the UV luminosity bins for the tracking of stellar populations.\n"); return EXIT_FAILURE; } while (fscanf(LUVtable, "%f %f %f %f", &t, &lambda, &LUV, &norm_spec) == 4) { stars_LUV[num_lines] = LUV; ++num_lines; if (num_lines == MAXBINS - 1) { fprintf(stderr, "Exceeding the maximum bins for the tracking of stellar populations.\n"); return EXIT_FAILURE; } } fclose(LUVtable); // Check that the Nion lookup table had enough datapoints to cover the time we're tracking the ages for. if (t / 1.0e6 < STELLAR_TRACKING_TIME) { fprintf(stderr, "The final time specified in the UV luminosity lookup table is %.4f Myr. However we specified to track stellar ages over %d Myr.\n", t / 1.0e6, STELLAR_TRACKING_TIME); fprintf(stderr, "Either update the UV luminosity lookup table or reduce the value of STELLAR_TRACKING_TIME in `core_allvars.h`.\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; #undef MAXBINS } /* Calculates the UV Luminosity (i.e., at 1600A) for a given galaxy at a specified snapshot. **Important** See Units. Parameters ---------- g: struct GALAXY pointer. See `core_allvars.h` for the struct architecture. Pointer to the galaxy that we are calculating UV luminosity. *LUV: Float Pointer. Pointer that will store the UV luminosity. Returns ---------- EXIT_SUCCESS or EXIT_FAILURE. If the UV luminosity is negative, EXIT_FAILURE is returned. Otherwise EXIT_SUCCESS is returned. Pointer Updates ---------- *LUV. Units ---------- The UV luminosty is returned in units of 1.0e50 erg s^-1 A^-1 */ int32_t calc_LUV(struct GALAXY *g, float *LUV) { double t; int32_t i, lookup_idx; // We ran STARBURST99 for a single mass and scale our results. // First convert the mass to internal code units. const double code_LUV_lookuptable_mass = LUV_LOOKUPTABLE_MASS*1.0e-10*Hubble_h; *LUV = 0.0; // Then go through the previous 100Myr worth of SF and sum up the UV luminosity. for (i = 0; i < StellarTracking_Len - 1; ++i) { if (g->Stellar_Stars[i] < 1e-10) continue; t = (i + 1) * TimeResolutionStellar; // (i + 1) because 0th entry will be at TimeResolutionSN. lookup_idx = t; // Find the index in the lookup table. *LUV += exp10(log10(g->Stellar_Stars[i] / code_LUV_lookuptable_mass) + stars_LUV[lookup_idx] - 50.0); //printf("t %.4f\tlookup_idx %d\tg->Stellar_Stars[i] %.4e\tstars_LUV[lookup_idx] %.4e\tRunningTotal %.4e\n", t, lookup_idx, g->Stellar_Stars[i], stars_LUV[lookup_idx], *LUV); } // The units of LUV are 1.0e50 erg s^-1 A^-1. Hence a negative value is not allowed. if (*LUV < 0.0) { fprintf(stderr, "Got an LUV value of %.4e. This MUST be a positive value.\nPrinting out information for every element used to calculate LUV.\n", *LUV); // Print out information for every element of the array so we can try identify the problem. for (i = 0; i < StellarTracking_Len; ++i) { t = (i + 1) * TimeResolutionStellar; // (i + 1) because 0th entry will be at TimeResolutionSN. lookup_idx = (t / 0.1); // Find the index in the lookup table. double total = 0.0; total += exp10(log10(g->Stellar_Stars[i] / code_LUV_lookuptable_mass) + stars_LUV[lookup_idx] - 50.0); printf("t %.4f\tlookup_idx %d\tg->Stellar_Stars[i] %.4e\tstars_LUV[lookup_idx] %.4e\tRunningTotal %.4e\n", t, lookup_idx, g->Stellar_Stars[i], stars_LUV[lookup_idx], total); } return EXIT_FAILURE; } return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.6944552909, "avg_line_length": 32.8333333333, "ext": "c", "hexsha": "2021fa795c7ac6bbe27e754d9ce299f042c2cbd3", "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": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jacobseiler/rsage", "max_forks_repo_path": "src/sage/UVmag/UVmag.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_issues_repo_issues_event_max_datetime": "2019-01-16T05:40:16.000Z", "max_issues_repo_issues_event_min_datetime": "2018-08-17T05:04:57.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jacobseiler/rsage", "max_issues_repo_path": "src/sage/UVmag/UVmag.c", "max_line_length": 187, "max_stars_count": 1, "max_stars_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jacobseiler/rsage", "max_stars_repo_path": "src/sage/UVmag/UVmag.c", "max_stars_repo_stars_event_max_datetime": "2019-05-23T04:11:32.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-23T04:11:32.000Z", "num_tokens": 1530, "size": 5122 }
/* * Copyright (C) 2021 FISCO BCOS. * SPDX-License-Identifier: Apache-2.0 * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @brief interface of Table * @file Table.h * @author: xingqiangbai * @date: 2021-04-07 */ #pragma once #include "Common.h" #include "StorageInterface.h" #include <future> #include <gsl/span> namespace bcos { namespace storage { class Table { public: Table(StorageInterface* _db, TableInfo::ConstPtr _tableInfo) : m_storage(_db), m_tableInfo(std::move(_tableInfo)) {} Table(const Table&) = default; Table(Table&&) = default; Table& operator=(const Table&) = default; Table& operator=(Table&&) = default; ~Table() {} std::optional<Entry> getRow(std::string_view _key); std::vector<std::optional<Entry>> getRows( const std::variant<const gsl::span<std::string_view const>, const gsl::span<std::string const>>& _keys); std::vector<std::string> getPrimaryKeys(const std::optional<const Condition>& _condition); void setRow(std::string_view _key, Entry _entry); void asyncGetPrimaryKeys(std::optional<const Condition> const& _condition, std::function<void(Error::UniquePtr, std::vector<std::string>)> _callback) noexcept; void asyncGetRow(std::string_view _key, std::function<void(Error::UniquePtr, std::optional<Entry>)> _callback) noexcept; void asyncGetRows(const std::variant<const gsl::span<std::string_view const>, const gsl::span<std::string const>>& _keys, std::function<void(Error::UniquePtr, std::vector<std::optional<Entry>>)> _callback) noexcept; void asyncSetRow( std::string_view key, Entry entry, std::function<void(Error::UniquePtr)> callback) noexcept; TableInfo::ConstPtr tableInfo() const { return m_tableInfo; } Entry newEntry() { return Entry(m_tableInfo); } Entry newDeletedEntry() { auto deletedEntry = newEntry(); deletedEntry.setStatus(Entry::DELETED); return deletedEntry; } protected: StorageInterface* m_storage; TableInfo::ConstPtr m_tableInfo; }; } // namespace storage } // namespace bcos
{ "alphanum_fraction": 0.6859165425, "avg_line_length": 32.3373493976, "ext": "h", "hexsha": "9e066cf6b5634cb08ff26846711c60c2faf7fcfe", "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": "e9cc29151c90dd1f4634f4d52ba773bb216700ac", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "chuwen95/FISCO-BCOS", "max_forks_repo_path": "bcos-framework/interfaces/storage/Table.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e9cc29151c90dd1f4634f4d52ba773bb216700ac", "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": "chuwen95/FISCO-BCOS", "max_issues_repo_path": "bcos-framework/interfaces/storage/Table.h", "max_line_length": 100, "max_stars_count": 1, "max_stars_repo_head_hexsha": "e9cc29151c90dd1f4634f4d52ba773bb216700ac", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "chuwen95/FISCO-BCOS", "max_stars_repo_path": "bcos-framework/interfaces/storage/Table.h", "max_stars_repo_stars_event_max_datetime": "2022-03-06T10:46:12.000Z", "max_stars_repo_stars_event_min_datetime": "2022-03-06T10:46:12.000Z", "num_tokens": 656, "size": 2684 }
/* ode-initval2/rk1imp.c * * Copyright (C) 2009, 2010 Tuomo Keskitalo * * 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. */ /* Implicit Euler a.k.a backward Euler method. */ /* Reference: Ascher, U.M., Petzold, L.R., Computer methods for ordinary differential and differential-algebraic equations, SIAM, Philadelphia, 1998. */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_odeiv2.h> #include "odeiv_util.h" #include "rksubs.c" #include "modnewton1.c" /* Stage of method */ #define RK1IMP_STAGE 1 typedef struct { gsl_matrix *A; /* Runge-Kutta coefficients */ double *y_onestep; /* Result with one step */ double *y_twostep; /* Result with two half steps */ double *ytmp; /* Temporary work space */ double *y_save; /* Backup space */ double *YZ; /* Runge-Kutta points */ double *fYZ; /* Derivatives at YZ */ gsl_matrix *dfdy; /* Jacobian matrix */ double *dfdt; /* time derivative of f */ modnewton1_state_t *esol; /* nonlinear equation solver */ double *errlev; /* desired error level of y */ const gsl_odeiv2_driver *driver; /* pointer to driver object */ } rk1imp_state_t; static void * rk1imp_alloc (size_t dim) { rk1imp_state_t *state = (rk1imp_state_t *) malloc (sizeof (rk1imp_state_t)); if (state == 0) { GSL_ERROR_NULL ("failed to allocate space for rk1imp_state", GSL_ENOMEM); } state->A = gsl_matrix_alloc (RK1IMP_STAGE, RK1IMP_STAGE); if (state->A == 0) { free (state); GSL_ERROR_NULL ("failed to allocate space for A", GSL_ENOMEM); } state->y_onestep = (double *) malloc (dim * sizeof (double)); if (state->y_onestep == 0) { gsl_matrix_free (state->A); free (state); GSL_ERROR_NULL ("failed to allocate space for y_onestep", GSL_ENOMEM); } state->y_twostep = (double *) malloc (dim * sizeof (double)); if (state->y_twostep == 0) { free (state->y_onestep); gsl_matrix_free (state->A); free (state); GSL_ERROR_NULL ("failed to allocate space for y_onestep", GSL_ENOMEM); } state->ytmp = (double *) malloc (dim * sizeof (double)); if (state->ytmp == 0) { free (state->y_twostep); free (state->y_onestep); gsl_matrix_free (state->A); free (state); GSL_ERROR_NULL ("failed to allocate space for ytmp", GSL_ENOMEM); } state->y_save = (double *) malloc (dim * sizeof (double)); if (state->y_save == 0) { free (state->ytmp); free (state->y_twostep); free (state->y_onestep); gsl_matrix_free (state->A); free (state); GSL_ERROR_NULL ("failed to allocate space for y_save", GSL_ENOMEM); } state->YZ = (double *) malloc (dim * RK1IMP_STAGE * sizeof (double)); if (state->YZ == 0) { free (state->y_save); free (state->ytmp); free (state->y_twostep); free (state->y_onestep); gsl_matrix_free (state->A); free (state); GSL_ERROR_NULL ("failed to allocate space for YZ", GSL_ENOMEM); } state->fYZ = (double *) malloc (dim * RK1IMP_STAGE * sizeof (double)); if (state->fYZ == 0) { free (state->YZ); free (state->y_save); free (state->ytmp); free (state->y_twostep); free (state->y_onestep); gsl_matrix_free (state->A); free (state); GSL_ERROR_NULL ("failed to allocate space for fYZ", GSL_ENOMEM); } state->dfdt = (double *) malloc (dim * sizeof (double)); if (state->dfdt == 0) { free (state->fYZ); free (state->YZ); free (state->y_save); free (state->ytmp); free (state->y_twostep); free (state->y_onestep); gsl_matrix_free (state->A); free (state); GSL_ERROR_NULL ("failed to allocate space for dfdt", GSL_ENOMEM); } state->dfdy = gsl_matrix_alloc (dim, dim); if (state->dfdy == 0) { free (state->dfdt); free (state->fYZ); free (state->YZ); free (state->y_save); free (state->ytmp); free (state->y_twostep); free (state->y_onestep); gsl_matrix_free (state->A); free (state); GSL_ERROR_NULL ("failed to allocate space for dfdy", GSL_ENOMEM); } state->esol = modnewton1_alloc (dim, RK1IMP_STAGE); if (state->esol == 0) { gsl_matrix_free (state->dfdy); free (state->dfdt); free (state->fYZ); free (state->YZ); free (state->y_save); free (state->ytmp); free (state->y_twostep); free (state->y_onestep); gsl_matrix_free (state->A); free (state); GSL_ERROR_NULL ("failed to allocate space for esol", GSL_ENOMEM); } state->errlev = (double *) malloc (dim * sizeof (double)); if (state->errlev == 0) { modnewton1_free (state->esol); gsl_matrix_free (state->dfdy); free (state->dfdt); free (state->fYZ); free (state->YZ); free (state->y_save); free (state->ytmp); free (state->y_twostep); free (state->y_onestep); gsl_matrix_free (state->A); free (state); GSL_ERROR_NULL ("failed to allocate space for errlev", GSL_ENOMEM); } state->driver = NULL; return state; } static int rk1imp_apply (void *vstate, size_t dim, double t, double h, double y[], double yerr[], const double dydt_in[], double dydt_out[], const gsl_odeiv2_system * sys) { /* Makes an implicit Euler step with size h and estimates the local error of the step by step doubling. */ rk1imp_state_t *state = (rk1imp_state_t *) vstate; double *const y_onestep = state->y_onestep; double *const y_twostep = state->y_twostep; double *const ytmp = state->ytmp; double *const y_save = state->y_save; double *const YZ = state->YZ; double *const fYZ = state->fYZ; gsl_matrix *const dfdy = state->dfdy; double *const dfdt = state->dfdt; double *const errlev = state->errlev; const modnewton1_state_t *esol = state->esol; /* Runge-Kutta coefficients */ gsl_matrix *A = state->A; const double b[] = { 1.0 }; const double c[] = { 1.0 }; gsl_matrix_set (A, 0, 0, 1.0); if (esol == NULL) { GSL_ERROR ("no non-linear equation solver speficied", GSL_EINVAL); } /* Get desired error levels via gsl_odeiv2_control object through driver object, which is a requirement for this stepper. */ if (state->driver == NULL) { return GSL_EFAULT; } else { size_t i; for (i = 0; i < dim; i++) { if (dydt_in != NULL) { gsl_odeiv2_control_errlevel (state->driver->c, y[i], dydt_in[i], h, i, &errlev[i]); } else { gsl_odeiv2_control_errlevel (state->driver->c, y[i], 0.0, h, i, &errlev[i]); } } } /* Evaluate Jacobian for modnewton1 */ { int s = GSL_ODEIV_JA_EVAL (sys, t, y, dfdy->data, dfdt); if (s != GSL_SUCCESS) { return s; } } /* Calculate a single step with size h */ { int s = modnewton1_init ((void *) esol, A, h, dfdy, sys); if (s != GSL_SUCCESS) { return s; } } { int s = modnewton1_solve ((void *) esol, A, c, t, h, y, sys, YZ, errlev); if (s != GSL_SUCCESS) { return s; } } { int s = GSL_ODEIV_FN_EVAL (sys, t + c[0] * h, YZ, fYZ); if (s != GSL_SUCCESS) { return s; } } { int s = rksubs (y_onestep, h, y, fYZ, b, RK1IMP_STAGE, dim); if (s != GSL_SUCCESS) return s; } /* Error estimation by step doubling */ { int s = modnewton1_init ((void *) esol, A, h / 2.0, dfdy, sys); if (s != GSL_SUCCESS) { return s; } } /* 1st half step */ { int s = modnewton1_solve ((void *) esol, A, c, t, h / 2.0, y, sys, YZ, errlev); if (s != GSL_SUCCESS) { return s; } } { int s = GSL_ODEIV_FN_EVAL (sys, t + c[0] * h / 2.0, YZ, fYZ); if (s != GSL_SUCCESS) { return s; } } { int s = rksubs (ytmp, h / 2.0, y, fYZ, b, RK1IMP_STAGE, dim); if (s != GSL_SUCCESS) return s; } /* Save original y values in case of error */ DBL_MEMCPY (y_save, y, dim); /* 2nd half step */ { int s = modnewton1_solve ((void *) esol, A, c, t + h / 2.0, h / 2.0, ytmp, sys, YZ, errlev); if (s != GSL_SUCCESS) { return s; } } { int s = GSL_ODEIV_FN_EVAL (sys, t + h / 2.0 + c[0] * h / 2.0, YZ, fYZ); if (s != GSL_SUCCESS) { return s; } } { /* Note: rk1imp returns y using the results from two half steps instead of the single step since the results are freely available and more precise. */ int s = rksubs (y_twostep, h / 2.0, ytmp, fYZ, b, RK1IMP_STAGE, dim); if (s != GSL_SUCCESS) { DBL_MEMCPY (y, y_save, dim); return s; } } DBL_MEMCPY (y, y_twostep, dim); /* Error estimation */ { size_t i; for (i = 0; i < dim; i++) { yerr[i] = ODEIV_ERR_SAFETY * 0.5 * fabs (y_twostep[i] - y_onestep[i]); } } /* Derivatives at output */ if (dydt_out != NULL) { int s = GSL_ODEIV_FN_EVAL (sys, t + h, y, dydt_out); if (s != GSL_SUCCESS) { /* Restore original values */ DBL_MEMCPY (y, y_save, dim); return s; } } return GSL_SUCCESS; } static int rk1imp_set_driver (void *vstate, const gsl_odeiv2_driver * d) { rk1imp_state_t *state = (rk1imp_state_t *) vstate; state->driver = d; return GSL_SUCCESS; } static int rk1imp_reset (void *vstate, size_t dim) { rk1imp_state_t *state = (rk1imp_state_t *) vstate; DBL_ZERO_MEMSET (state->y_onestep, dim); DBL_ZERO_MEMSET (state->y_twostep, dim); DBL_ZERO_MEMSET (state->ytmp, dim); DBL_ZERO_MEMSET (state->y_save, dim); DBL_ZERO_MEMSET (state->YZ, dim); DBL_ZERO_MEMSET (state->fYZ, dim); return GSL_SUCCESS; } static unsigned int rk1imp_order (void *vstate) { rk1imp_state_t *state = (rk1imp_state_t *) vstate; state = 0; /* prevent warnings about unused parameters */ return 1; } static void rk1imp_free (void *vstate) { rk1imp_state_t *state = (rk1imp_state_t *) vstate; free (state->errlev); modnewton1_free (state->esol); gsl_matrix_free (state->dfdy); free (state->dfdt); free (state->fYZ); free (state->YZ); free (state->y_save); free (state->ytmp); free (state->y_twostep); free (state->y_onestep); gsl_matrix_free (state->A); free (state); } static const gsl_odeiv2_step_type rk1imp_type = { "rk1imp", /* name */ 1, /* can use dydt_in? */ 1, /* gives exact dydt_out? */ &rk1imp_alloc, &rk1imp_apply, &rk1imp_set_driver, &rk1imp_reset, &rk1imp_order, &rk1imp_free }; const gsl_odeiv2_step_type *gsl_odeiv2_step_rk1imp = &rk1imp_type;
{ "alphanum_fraction": 0.5758305648, "avg_line_length": 24.08, "ext": "c", "hexsha": "a0a8b1f2864f1e9bd0f3bab95e4c9bde9e6b611e", "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/ode-initval2/rk1imp.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/ode-initval2/rk1imp.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/ode-initval2/rk1imp.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": 3598, "size": 12040 }
/* eigen/nonsymmv.c * * Copyright (C) 2006 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 <math.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_math.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_vector_complex.h> #include <gsl/gsl_matrix.h> /* * This module computes the eigenvalues and eigenvectors of a real * nonsymmetric matrix. * * This file contains routines based on original code from LAPACK * which is distributed under the modified BSD license. The LAPACK * routines used are DTREVC and DLALN2. */ #define GSL_NONSYMMV_SMLNUM (2.0 * GSL_DBL_MIN) #define GSL_NONSYMMV_BIGNUM ((1.0 - GSL_DBL_EPSILON) / GSL_NONSYMMV_SMLNUM) static void nonsymmv_get_right_eigenvectors(gsl_matrix *T, gsl_matrix *Z, gsl_vector_complex *eval, gsl_matrix_complex *evec, gsl_eigen_nonsymmv_workspace *w); static void nonsymmv_normalize_eigenvectors(gsl_vector_complex *eval, gsl_matrix_complex *evec); /* gsl_eigen_nonsymmv_alloc() Allocate a workspace for solving the nonsymmetric eigenvalue problem. The size of this workspace is O(5n). Inputs: n - size of matrices Return: pointer to workspace */ gsl_eigen_nonsymmv_workspace * gsl_eigen_nonsymmv_alloc(const size_t n) { gsl_eigen_nonsymmv_workspace *w; if (n == 0) { GSL_ERROR_NULL ("matrix dimension must be positive integer", GSL_EINVAL); } w = (gsl_eigen_nonsymmv_workspace *) calloc (1, sizeof (gsl_eigen_nonsymmv_workspace)); if (w == 0) { GSL_ERROR_NULL ("failed to allocate space for workspace", GSL_ENOMEM); } w->size = n; w->Z = NULL; w->nonsymm_workspace_p = gsl_eigen_nonsymm_alloc(n); if (w->nonsymm_workspace_p == 0) { gsl_eigen_nonsymmv_free(w); GSL_ERROR_NULL ("failed to allocate space for nonsymm workspace", GSL_ENOMEM); } /* * set parameters to compute the full Schur form T and balance * the matrices */ gsl_eigen_nonsymm_params(1, 1, w->nonsymm_workspace_p); w->work = gsl_vector_alloc(n); w->work2 = gsl_vector_alloc(n); w->work3 = gsl_vector_alloc(n); if (w->work == 0 || w->work2 == 0 || w->work3 == 0) { gsl_eigen_nonsymmv_free(w); GSL_ERROR_NULL ("failed to allocate space for nonsymmv additional workspace", GSL_ENOMEM); } return (w); } /* gsl_eigen_nonsymmv_alloc() */ /* gsl_eigen_nonsymmv_free() Free workspace w */ void gsl_eigen_nonsymmv_free (gsl_eigen_nonsymmv_workspace * w) { RETURN_IF_NULL (w); if (w->nonsymm_workspace_p) gsl_eigen_nonsymm_free(w->nonsymm_workspace_p); if (w->work) gsl_vector_free(w->work); if (w->work2) gsl_vector_free(w->work2); if (w->work3) gsl_vector_free(w->work3); free(w); } /* gsl_eigen_nonsymmv_free() */ /* gsl_eigen_nonsymmv() Solve the nonsymmetric eigensystem problem A x = \lambda x for the eigenvalues \lambda and right eigenvectors x Inputs: A - general real matrix eval - where to store eigenvalues evec - where to store eigenvectors w - workspace Return: success or error */ int gsl_eigen_nonsymmv (gsl_matrix * A, gsl_vector_complex * eval, gsl_matrix_complex * evec, gsl_eigen_nonsymmv_workspace * w) { const size_t N = A->size1; /* check matrix and vector sizes */ if (N != A->size2) { GSL_ERROR ("matrix must be square to compute eigenvalues", GSL_ENOTSQR); } else if (eval->size != N) { GSL_ERROR ("eigenvalue vector must match matrix size", GSL_EBADLEN); } else if (evec->size1 != evec->size2) { GSL_ERROR ("eigenvector matrix must be square", GSL_ENOTSQR); } else if (evec->size1 != N) { GSL_ERROR ("eigenvector matrix has wrong size", GSL_EBADLEN); } else { int s; gsl_matrix Z; /* * We need a place to store the Schur vectors, so we will * treat evec as a real matrix and store them in the left * half - the factor of 2 in the tda corresponds to the * complex multiplicity */ Z.size1 = N; Z.size2 = N; Z.tda = 2 * N; Z.data = evec->data; Z.block = 0; Z.owner = 0; /* compute eigenvalues, Schur form, and Schur vectors */ s = gsl_eigen_nonsymm_Z(A, eval, &Z, w->nonsymm_workspace_p); if (w->Z) { /* * save the Schur vectors in user supplied matrix, since * they will be destroyed when computing eigenvectors */ gsl_matrix_memcpy(w->Z, &Z); } /* only compute eigenvectors if we found all eigenvalues */ if (s == GSL_SUCCESS) { /* compute eigenvectors */ nonsymmv_get_right_eigenvectors(A, &Z, eval, evec, w); /* normalize so that Euclidean norm is 1 */ nonsymmv_normalize_eigenvectors(eval, evec); } return s; } } /* gsl_eigen_nonsymmv() */ /* gsl_eigen_nonsymmv_Z() Compute eigenvalues and eigenvectors of a real nonsymmetric matrix and also save the Schur vectors. See comments in gsl_eigen_nonsymm_Z for more information. Inputs: A - real nonsymmetric matrix eval - where to store eigenvalues evec - where to store eigenvectors Z - where to store Schur vectors w - nonsymmv workspace Return: success or error */ int gsl_eigen_nonsymmv_Z (gsl_matrix * A, gsl_vector_complex * eval, gsl_matrix_complex * evec, gsl_matrix * Z, gsl_eigen_nonsymmv_workspace * w) { /* check matrix and vector sizes */ if (A->size1 != A->size2) { GSL_ERROR ("matrix must be square to compute eigenvalues/eigenvectors", GSL_ENOTSQR); } else if (eval->size != A->size1) { GSL_ERROR ("eigenvalue vector must match matrix size", GSL_EBADLEN); } else if (evec->size1 != evec->size2) { GSL_ERROR ("eigenvector matrix must be square", GSL_ENOTSQR); } else if (evec->size1 != A->size1) { GSL_ERROR ("eigenvector matrix has wrong size", GSL_EBADLEN); } else if ((Z->size1 != Z->size2) || (Z->size1 != A->size1)) { GSL_ERROR ("Z matrix has wrong dimensions", GSL_EBADLEN); } else { int s; w->Z = Z; s = gsl_eigen_nonsymmv(A, eval, evec, w); w->Z = NULL; return s; } } /* gsl_eigen_nonsymmv_Z() */ /******************************************** * INTERNAL ROUTINES * ********************************************/ /* nonsymmv_get_right_eigenvectors() Compute the right eigenvectors of the Schur form T and then backtransform them using the Schur vectors to get right eigenvectors of the original matrix. Inputs: T - Schur form Z - Schur vectors eval - where to store eigenvalues (to ensure that the correct eigenvalue is stored in the same position as the eigenvectors) evec - where to store eigenvectors w - nonsymmv workspace Return: none Notes: 1) based on LAPACK routine DTREVC - the algorithm used is backsubstitution on the upper quasi triangular system T followed by backtransformation by Z to get vectors of the original matrix. 2) The Schur vectors in Z are destroyed and replaced with eigenvectors stored with the same storage scheme as DTREVC. The eigenvectors are also stored in 'evec' 3) The matrix T is unchanged on output 4) Each eigenvector is normalized so that the element of largest magnitude has magnitude 1; here the magnitude of a complex number (x,y) is taken to be |x| + |y| */ static void nonsymmv_get_right_eigenvectors(gsl_matrix *T, gsl_matrix *Z, gsl_vector_complex *eval, gsl_matrix_complex *evec, gsl_eigen_nonsymmv_workspace *w) { const size_t N = T->size1; const double smlnum = GSL_DBL_MIN * N / GSL_DBL_EPSILON; const double bignum = (1.0 - GSL_DBL_EPSILON) / smlnum; int i; /* looping */ size_t iu, /* looping */ ju, ii; gsl_complex lambda; /* current eigenvalue */ double lambda_re, /* Re(lambda) */ lambda_im; /* Im(lambda) */ gsl_matrix_view Tv, /* temporary views */ Zv; gsl_vector_view y, /* temporary views */ y2, ev, ev2; double dat[4], /* scratch arrays */ dat_X[4]; double scale; /* scale factor */ double xnorm; /* |X| */ gsl_vector_complex_view ecol, /* column of evec */ ecol2; int complex_pair; /* complex eigenvalue pair? */ double smin; /* * Compute 1-norm of each column of upper triangular part of T * to control overflow in triangular solver */ gsl_vector_set(w->work3, 0, 0.0); for (ju = 1; ju < N; ++ju) { gsl_vector_set(w->work3, ju, 0.0); for (iu = 0; iu < ju; ++iu) { gsl_vector_set(w->work3, ju, gsl_vector_get(w->work3, ju) + fabs(gsl_matrix_get(T, iu, ju))); } } for (i = (int) N - 1; i >= 0; --i) { iu = (size_t) i; /* get current eigenvalue and store it in lambda */ lambda_re = gsl_matrix_get(T, iu, iu); if (iu != 0 && gsl_matrix_get(T, iu, iu - 1) != 0.0) { lambda_im = sqrt(fabs(gsl_matrix_get(T, iu, iu - 1))) * sqrt(fabs(gsl_matrix_get(T, iu - 1, iu))); } else { lambda_im = 0.0; } GSL_SET_COMPLEX(&lambda, lambda_re, lambda_im); smin = GSL_MAX(GSL_DBL_EPSILON * (fabs(lambda_re) + fabs(lambda_im)), smlnum); smin = GSL_MAX(smin, GSL_NONSYMMV_SMLNUM); if (lambda_im == 0.0) { int k, l; gsl_vector_view bv, xv; /* real eigenvector */ /* * The ordering of eigenvalues in 'eval' is arbitrary and * does not necessarily follow the Schur form T, so store * lambda in the right slot in eval to ensure it corresponds * to the eigenvector we are about to compute */ gsl_vector_complex_set(eval, iu, lambda); /* * We need to solve the system: * * (T(1:iu-1, 1:iu-1) - lambda*I)*X = -T(1:iu-1,iu) */ /* construct right hand side */ for (k = 0; k < i; ++k) { gsl_vector_set(w->work, (size_t) k, -gsl_matrix_get(T, (size_t) k, iu)); } gsl_vector_set(w->work, iu, 1.0); for (l = i - 1; l >= 0; --l) { size_t lu = (size_t) l; if (lu == 0) complex_pair = 0; else complex_pair = gsl_matrix_get(T, lu, lu - 1) != 0.0; if (!complex_pair) { double x; /* * 1-by-1 diagonal block - solve the system: * * (T_{ll} - lambda)*x = -T_{l(iu)} */ Tv = gsl_matrix_submatrix(T, lu, lu, 1, 1); bv = gsl_vector_view_array(dat, 1); gsl_vector_set(&bv.vector, 0, gsl_vector_get(w->work, lu)); xv = gsl_vector_view_array(dat_X, 1); gsl_schur_solve_equation(1.0, &Tv.matrix, lambda_re, 1.0, 1.0, &bv.vector, &xv.vector, &scale, &xnorm, smin); /* scale x to avoid overflow */ x = gsl_vector_get(&xv.vector, 0); if (xnorm > 1.0) { if (gsl_vector_get(w->work3, lu) > bignum / xnorm) { x /= xnorm; scale /= xnorm; } } if (scale != 1.0) { gsl_vector_view wv; wv = gsl_vector_subvector(w->work, 0, iu + 1); gsl_blas_dscal(scale, &wv.vector); } gsl_vector_set(w->work, lu, x); if (lu > 0) { gsl_vector_view v1, v2; /* update right hand side */ v1 = gsl_matrix_subcolumn(T, lu, 0, lu); v2 = gsl_vector_subvector(w->work, 0, lu); gsl_blas_daxpy(-x, &v1.vector, &v2.vector); } /* if (l > 0) */ } /* if (!complex_pair) */ else { double x11, x21; /* * 2-by-2 diagonal block */ Tv = gsl_matrix_submatrix(T, lu - 1, lu - 1, 2, 2); bv = gsl_vector_view_array(dat, 2); gsl_vector_set(&bv.vector, 0, gsl_vector_get(w->work, lu - 1)); gsl_vector_set(&bv.vector, 1, gsl_vector_get(w->work, lu)); xv = gsl_vector_view_array(dat_X, 2); gsl_schur_solve_equation(1.0, &Tv.matrix, lambda_re, 1.0, 1.0, &bv.vector, &xv.vector, &scale, &xnorm, smin); /* scale X(1,1) and X(2,1) to avoid overflow */ x11 = gsl_vector_get(&xv.vector, 0); x21 = gsl_vector_get(&xv.vector, 1); if (xnorm > 1.0) { double beta; beta = GSL_MAX(gsl_vector_get(w->work3, lu - 1), gsl_vector_get(w->work3, lu)); if (beta > bignum / xnorm) { x11 /= xnorm; x21 /= xnorm; scale /= xnorm; } } /* scale if necessary */ if (scale != 1.0) { gsl_vector_view wv; wv = gsl_vector_subvector(w->work, 0, iu + 1); gsl_blas_dscal(scale, &wv.vector); } gsl_vector_set(w->work, lu - 1, x11); gsl_vector_set(w->work, lu, x21); /* update right hand side */ if (lu > 1) { gsl_vector_view v1, v2; v1 = gsl_matrix_subcolumn(T, lu - 1, 0, lu - 1); v2 = gsl_vector_subvector(w->work, 0, lu - 1); gsl_blas_daxpy(-x11, &v1.vector, &v2.vector); v1 = gsl_matrix_subcolumn(T, lu, 0, lu - 1); gsl_blas_daxpy(-x21, &v1.vector, &v2.vector); } --l; } /* if (complex_pair) */ } /* for (l = i - 1; l >= 0; --l) */ /* * At this point, w->work is an eigenvector of the * Schur form T. To get an eigenvector of the original * matrix, we multiply on the left by Z, the matrix of * Schur vectors */ ecol = gsl_matrix_complex_column(evec, iu); y = gsl_matrix_column(Z, iu); if (iu > 0) { gsl_vector_view x; Zv = gsl_matrix_submatrix(Z, 0, 0, N, iu); x = gsl_vector_subvector(w->work, 0, iu); /* compute Z * w->work and store it in Z(:,iu) */ gsl_blas_dgemv(CblasNoTrans, 1.0, &Zv.matrix, &x.vector, gsl_vector_get(w->work, iu), &y.vector); } /* if (iu > 0) */ /* store eigenvector into evec */ ev = gsl_vector_complex_real(&ecol.vector); ev2 = gsl_vector_complex_imag(&ecol.vector); scale = 0.0; for (ii = 0; ii < N; ++ii) { double a = gsl_vector_get(&y.vector, ii); /* store real part of eigenvector */ gsl_vector_set(&ev.vector, ii, a); /* set imaginary part to 0 */ gsl_vector_set(&ev2.vector, ii, 0.0); if (fabs(a) > scale) scale = fabs(a); } if (scale != 0.0) scale = 1.0 / scale; /* scale by magnitude of largest element */ gsl_blas_dscal(scale, &ev.vector); } /* if (GSL_IMAG(lambda) == 0.0) */ else { gsl_vector_complex_view bv, xv; size_t k; int l; gsl_complex lambda2; /* complex eigenvector */ /* * Store the complex conjugate eigenvalues in the right * slots in eval */ GSL_SET_REAL(&lambda2, GSL_REAL(lambda)); GSL_SET_IMAG(&lambda2, -GSL_IMAG(lambda)); gsl_vector_complex_set(eval, iu - 1, lambda); gsl_vector_complex_set(eval, iu, lambda2); /* * First solve: * * [ T(i:i+1,i:i+1) - lambda*I ] * X = 0 */ if (fabs(gsl_matrix_get(T, iu - 1, iu)) >= fabs(gsl_matrix_get(T, iu, iu - 1))) { gsl_vector_set(w->work, iu - 1, 1.0); gsl_vector_set(w->work2, iu, lambda_im / gsl_matrix_get(T, iu - 1, iu)); } else { gsl_vector_set(w->work, iu - 1, -lambda_im / gsl_matrix_get(T, iu, iu - 1)); gsl_vector_set(w->work2, iu, 1.0); } gsl_vector_set(w->work, iu, 0.0); gsl_vector_set(w->work2, iu - 1, 0.0); /* construct right hand side */ for (k = 0; k < iu - 1; ++k) { gsl_vector_set(w->work, k, -gsl_vector_get(w->work, iu - 1) * gsl_matrix_get(T, k, iu - 1)); gsl_vector_set(w->work2, k, -gsl_vector_get(w->work2, iu) * gsl_matrix_get(T, k, iu)); } /* * We must solve the upper quasi-triangular system: * * [ T(1:i-2,1:i-2) - lambda*I ] * X = s*(work + i*work2) */ for (l = i - 2; l >= 0; --l) { size_t lu = (size_t) l; if (lu == 0) complex_pair = 0; else complex_pair = gsl_matrix_get(T, lu, lu - 1) != 0.0; if (!complex_pair) { gsl_complex bval; gsl_complex x; /* * 1-by-1 diagonal block - solve the system: * * (T_{ll} - lambda)*x = work + i*work2 */ Tv = gsl_matrix_submatrix(T, lu, lu, 1, 1); bv = gsl_vector_complex_view_array(dat, 1); xv = gsl_vector_complex_view_array(dat_X, 1); GSL_SET_COMPLEX(&bval, gsl_vector_get(w->work, lu), gsl_vector_get(w->work2, lu)); gsl_vector_complex_set(&bv.vector, 0, bval); gsl_schur_solve_equation_z(1.0, &Tv.matrix, &lambda, 1.0, 1.0, &bv.vector, &xv.vector, &scale, &xnorm, smin); if (xnorm > 1.0) { if (gsl_vector_get(w->work3, lu) > bignum / xnorm) { gsl_blas_zdscal(1.0/xnorm, &xv.vector); scale /= xnorm; } } /* scale if necessary */ if (scale != 1.0) { gsl_vector_view wv; wv = gsl_vector_subvector(w->work, 0, iu + 1); gsl_blas_dscal(scale, &wv.vector); wv = gsl_vector_subvector(w->work2, 0, iu + 1); gsl_blas_dscal(scale, &wv.vector); } x = gsl_vector_complex_get(&xv.vector, 0); gsl_vector_set(w->work, lu, GSL_REAL(x)); gsl_vector_set(w->work2, lu, GSL_IMAG(x)); /* update the right hand side */ if (lu > 0) { gsl_vector_view v1, v2; v1 = gsl_matrix_subcolumn(T, lu, 0, lu); v2 = gsl_vector_subvector(w->work, 0, lu); gsl_blas_daxpy(-GSL_REAL(x), &v1.vector, &v2.vector); v2 = gsl_vector_subvector(w->work2, 0, lu); gsl_blas_daxpy(-GSL_IMAG(x), &v1.vector, &v2.vector); } /* if (lu > 0) */ } /* if (!complex_pair) */ else { gsl_complex b1, b2, x1, x2; /* * 2-by-2 diagonal block - solve the system */ Tv = gsl_matrix_submatrix(T, lu - 1, lu - 1, 2, 2); bv = gsl_vector_complex_view_array(dat, 2); xv = gsl_vector_complex_view_array(dat_X, 2); GSL_SET_COMPLEX(&b1, gsl_vector_get(w->work, lu - 1), gsl_vector_get(w->work2, lu - 1)); GSL_SET_COMPLEX(&b2, gsl_vector_get(w->work, lu), gsl_vector_get(w->work2, lu)); gsl_vector_complex_set(&bv.vector, 0, b1); gsl_vector_complex_set(&bv.vector, 1, b2); gsl_schur_solve_equation_z(1.0, &Tv.matrix, &lambda, 1.0, 1.0, &bv.vector, &xv.vector, &scale, &xnorm, smin); x1 = gsl_vector_complex_get(&xv.vector, 0); x2 = gsl_vector_complex_get(&xv.vector, 1); if (xnorm > 1.0) { double beta; beta = GSL_MAX(gsl_vector_get(w->work3, lu - 1), gsl_vector_get(w->work3, lu)); if (beta > bignum / xnorm) { gsl_blas_zdscal(1.0/xnorm, &xv.vector); scale /= xnorm; } } /* scale if necessary */ if (scale != 1.0) { gsl_vector_view wv; wv = gsl_vector_subvector(w->work, 0, iu + 1); gsl_blas_dscal(scale, &wv.vector); wv = gsl_vector_subvector(w->work2, 0, iu + 1); gsl_blas_dscal(scale, &wv.vector); } gsl_vector_set(w->work, lu - 1, GSL_REAL(x1)); gsl_vector_set(w->work, lu, GSL_REAL(x2)); gsl_vector_set(w->work2, lu - 1, GSL_IMAG(x1)); gsl_vector_set(w->work2, lu, GSL_IMAG(x2)); /* update right hand side */ if (lu > 1) { gsl_vector_view v1, v2, v3, v4; v1 = gsl_matrix_subcolumn(T, lu - 1, 0, lu - 1); v4 = gsl_matrix_subcolumn(T, lu, 0, lu - 1); v2 = gsl_vector_subvector(w->work, 0, lu - 1); v3 = gsl_vector_subvector(w->work2, 0, lu - 1); gsl_blas_daxpy(-GSL_REAL(x1), &v1.vector, &v2.vector); gsl_blas_daxpy(-GSL_REAL(x2), &v4.vector, &v2.vector); gsl_blas_daxpy(-GSL_IMAG(x1), &v1.vector, &v3.vector); gsl_blas_daxpy(-GSL_IMAG(x2), &v4.vector, &v3.vector); } /* if (lu > 1) */ --l; } /* if (complex_pair) */ } /* for (l = i - 2; l >= 0; --l) */ /* * At this point, work + i*work2 is an eigenvector * of T - backtransform to get an eigenvector of the * original matrix */ y = gsl_matrix_column(Z, iu - 1); y2 = gsl_matrix_column(Z, iu); if (iu > 1) { gsl_vector_view x; /* compute real part of eigenvectors */ Zv = gsl_matrix_submatrix(Z, 0, 0, N, iu - 1); x = gsl_vector_subvector(w->work, 0, iu - 1); gsl_blas_dgemv(CblasNoTrans, 1.0, &Zv.matrix, &x.vector, gsl_vector_get(w->work, iu - 1), &y.vector); /* now compute the imaginary part */ x = gsl_vector_subvector(w->work2, 0, iu - 1); gsl_blas_dgemv(CblasNoTrans, 1.0, &Zv.matrix, &x.vector, gsl_vector_get(w->work2, iu), &y2.vector); } else { gsl_blas_dscal(gsl_vector_get(w->work, iu - 1), &y.vector); gsl_blas_dscal(gsl_vector_get(w->work2, iu), &y2.vector); } /* * Now store the eigenvectors into evec - the real parts * are Z(:,iu - 1) and the imaginary parts are * +/- Z(:,iu) */ /* get views of the two eigenvector slots */ ecol = gsl_matrix_complex_column(evec, iu - 1); ecol2 = gsl_matrix_complex_column(evec, iu); /* * save imaginary part first as it may get overwritten * when copying the real part due to our storage scheme * in Z/evec */ ev = gsl_vector_complex_imag(&ecol.vector); ev2 = gsl_vector_complex_imag(&ecol2.vector); scale = 0.0; for (ii = 0; ii < N; ++ii) { double a = gsl_vector_get(&y2.vector, ii); scale = GSL_MAX(scale, fabs(a) + fabs(gsl_vector_get(&y.vector, ii))); gsl_vector_set(&ev.vector, ii, a); gsl_vector_set(&ev2.vector, ii, -a); } /* now save the real part */ ev = gsl_vector_complex_real(&ecol.vector); ev2 = gsl_vector_complex_real(&ecol2.vector); for (ii = 0; ii < N; ++ii) { double a = gsl_vector_get(&y.vector, ii); gsl_vector_set(&ev.vector, ii, a); gsl_vector_set(&ev2.vector, ii, a); } if (scale != 0.0) scale = 1.0 / scale; /* scale by largest element magnitude */ gsl_blas_zdscal(scale, &ecol.vector); gsl_blas_zdscal(scale, &ecol2.vector); /* * decrement i since we took care of two eigenvalues at * the same time */ --i; } /* if (GSL_IMAG(lambda) != 0.0) */ } /* for (i = (int) N - 1; i >= 0; --i) */ } /* nonsymmv_get_right_eigenvectors() */ /* nonsymmv_normalize_eigenvectors() Normalize eigenvectors so that their Euclidean norm is 1 Inputs: eval - eigenvalues evec - eigenvectors */ static void nonsymmv_normalize_eigenvectors(gsl_vector_complex *eval, gsl_matrix_complex *evec) { const size_t N = evec->size1; size_t i; /* looping */ gsl_complex ei; gsl_vector_complex_view vi; gsl_vector_view re, im; double scale; /* scaling factor */ for (i = 0; i < N; ++i) { ei = gsl_vector_complex_get(eval, i); vi = gsl_matrix_complex_column(evec, i); re = gsl_vector_complex_real(&vi.vector); if (GSL_IMAG(ei) == 0.0) { scale = 1.0 / gsl_blas_dnrm2(&re.vector); gsl_blas_dscal(scale, &re.vector); } else if (GSL_IMAG(ei) > 0.0) { im = gsl_vector_complex_imag(&vi.vector); scale = 1.0 / gsl_hypot(gsl_blas_dnrm2(&re.vector), gsl_blas_dnrm2(&im.vector)); gsl_blas_zdscal(scale, &vi.vector); vi = gsl_matrix_complex_column(evec, i + 1); gsl_blas_zdscal(scale, &vi.vector); } } } /* nonsymmv_normalize_eigenvectors() */
{ "alphanum_fraction": 0.4636971047, "avg_line_length": 32.3353909465, "ext": "c", "hexsha": "9a87a74a0a6262bfc3c5da1f0f9ffa3a37d3b8a0", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "skair39/structured", "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/eigen/nonsymmv.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "skair39/structured", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/eigen/nonsymmv.c", "max_line_length": 96, "max_stars_count": 14, "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_path": "folding_libs/gsl-1.14/eigen/nonsymmv.c", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "num_tokens": 7689, "size": 31430 }
#include <bindings.cmacros.h> #include <gsl/gsl_odeiv2.h> BC_INLINE4(GSL_ODEIV_FN_EVAL,gsl_odeiv2_system*,double,double*,double*,int) BC_INLINE5(GSL_ODEIV_JA_EVAL,gsl_odeiv2_system*,double,double*,double*,double*,int)
{ "alphanum_fraction": 0.8219178082, "avg_line_length": 36.5, "ext": "c", "hexsha": "93e4e76f5c8b358a32ce3e86ebf9234f6e3e3539", "lang": "C", "max_forks_count": 19, "max_forks_repo_forks_event_max_datetime": "2021-09-10T19:31:38.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-03T20:43:08.000Z", "max_forks_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "flip111/bindings-dsl", "max_forks_repo_path": "bindings-gsl/src/Bindings/Gsl/OrdinaryDifferentialEquations.c", "max_issues_count": 23, "max_issues_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_issues_repo_issues_event_max_datetime": "2021-04-07T09:49:12.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-04T06:32:10.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "flip111/bindings-dsl", "max_issues_repo_path": "bindings-gsl/src/Bindings/Gsl/OrdinaryDifferentialEquations.c", "max_line_length": 83, "max_stars_count": 25, "max_stars_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "flip111/bindings-dsl", "max_stars_repo_path": "bindings-gsl/src/Bindings/Gsl/OrdinaryDifferentialEquations.c", "max_stars_repo_stars_event_max_datetime": "2022-02-06T09:29:03.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-29T00:31:20.000Z", "num_tokens": 72, "size": 219 }
/* test.c * * Copyright (C) 2012-2014 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_test.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_spmatrix.h> /* create_random_sparse() Create a random sparse matrix with approximately M*N*density non-zero entries Inputs: M - number of rows N - number of columns density - sparse density \in [0,1] 0 = no non-zero entries 1 = all m*n entries are filled r - random number generator Return: pointer to sparse matrix in triplet format (must be freed by caller) Notes: 1) non-zero matrix entries are uniformly distributed in [0,1] */ static gsl_spmatrix * create_random_sparse(const size_t M, const size_t N, const double density, const gsl_rng *r) { size_t nnzwanted = (size_t) floor(M * N * GSL_MIN(density, 1.0)); gsl_spmatrix *m = gsl_spmatrix_alloc_nzmax(M, N, nnzwanted, GSL_SPMATRIX_TRIPLET); while (gsl_spmatrix_nnz(m) < nnzwanted) { /* generate a random row and column */ size_t i = gsl_rng_uniform(r) * M; size_t j = gsl_rng_uniform(r) * N; /* generate random m_{ij} and add it */ double x = gsl_rng_uniform(r); gsl_spmatrix_set(m, i, j, x); } return m; } /* create_random_sparse() */ static void test_getset(const size_t M, const size_t N, const gsl_rng *r) { int status; size_t i, j; /* test triplet versions of _get and _set */ { size_t k = 0; gsl_spmatrix *m = gsl_spmatrix_alloc(M, N); status = 0; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { double x = (double) ++k; double y; gsl_spmatrix_set(m, i, j, x); y = gsl_spmatrix_get(m, i, j); if (x != y) status = 1; } } gsl_test(status, "test_getset: M=%zu N=%zu _get != _set", M, N); /* test setting an element to 0 */ gsl_spmatrix_set(m, 0, 0, 1.0); gsl_spmatrix_set(m, 0, 0, 0.0); status = gsl_spmatrix_get(m, 0, 0) != 0.0; gsl_test(status, "test_getset: M=%zu N=%zu m(0,0) = %f", M, N, gsl_spmatrix_get(m, 0, 0)); /* test gsl_spmatrix_set_zero() */ gsl_spmatrix_set(m, 0, 0, 1.0); gsl_spmatrix_set_zero(m); status = gsl_spmatrix_get(m, 0, 0) != 0.0; gsl_test(status, "test_getset: M=%zu N=%zu set_zero m(0,0) = %f", M, N, gsl_spmatrix_get(m, 0, 0)); /* resassemble matrix to ensure nz is calculated correctly */ k = 0; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { double x = (double) ++k; gsl_spmatrix_set(m, i, j, x); } } status = gsl_spmatrix_nnz(m) != M * N; gsl_test(status, "test_getset: M=%zu N=%zu set_zero nz = %zu", M, N, gsl_spmatrix_nnz(m)); gsl_spmatrix_free(m); } /* test duplicate values are handled correctly */ { size_t min = GSL_MIN(M, N); size_t expected_nnz = min; size_t nnz; size_t k = 0; gsl_spmatrix *m = gsl_spmatrix_alloc(M, N); status = 0; for (i = 0; i < min; ++i) { for (j = 0; j < 5; ++j) { double x = (double) ++k; double y; gsl_spmatrix_set(m, i, i, x); y = gsl_spmatrix_get(m, i, i); if (x != y) status = 1; } } gsl_test(status, "test_getset: duplicate test M=%zu N=%zu _get != _set", M, N); nnz = gsl_spmatrix_nnz(m); status = nnz != expected_nnz; gsl_test(status, "test_getset: duplicate test M=%zu N=%zu nnz=%zu, expected=%zu", M, N, nnz, expected_nnz); gsl_spmatrix_free(m); } /* test compressed version of gsl_spmatrix_get() */ { gsl_spmatrix *T = create_random_sparse(M, N, 0.3, r); gsl_spmatrix *C = gsl_spmatrix_compcol(T); status = 0; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { double Tij = gsl_spmatrix_get(T, i, j); double Cij = gsl_spmatrix_get(C, i, j); if (Tij != Cij) status = 1; } } gsl_test(status, "test_getset: M=%zu N=%zu compressed _get", M, N); gsl_spmatrix_free(T); gsl_spmatrix_free(C); } } /* test_getset() */ static void test_memcpy(const size_t M, const size_t N, const gsl_rng *r) { int status; { gsl_spmatrix *at = create_random_sparse(M, N, 0.2, r); gsl_spmatrix *ac = gsl_spmatrix_compcol(at); gsl_spmatrix *bt, *bc; bt = gsl_spmatrix_alloc(M, N); gsl_spmatrix_memcpy(bt, at); status = gsl_spmatrix_equal(at, bt) != 1; gsl_test(status, "test_memcpy: _memcpy M=%zu N=%zu triplet format", M, N); bc = gsl_spmatrix_alloc_nzmax(M, N, ac->nzmax, GSL_SPMATRIX_CCS); gsl_spmatrix_memcpy(bc, ac); status = gsl_spmatrix_equal(ac, bc) != 1; gsl_test(status, "test_memcpy: _memcpy M=%zu N=%zu compressed column format", M, N); gsl_spmatrix_free(at); gsl_spmatrix_free(ac); gsl_spmatrix_free(bt); gsl_spmatrix_free(bc); } /* test transpose_memcpy */ { gsl_spmatrix *A = create_random_sparse(M, N, 0.3, r); gsl_spmatrix *B = gsl_spmatrix_compcol(A); gsl_spmatrix *AT = gsl_spmatrix_alloc(N, M); gsl_spmatrix *BT = gsl_spmatrix_alloc_nzmax(N, M, 1, GSL_SPMATRIX_CCS); size_t i, j; gsl_spmatrix_transpose_memcpy(AT, A); gsl_spmatrix_transpose_memcpy(BT, B); status = 0; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { double Aij = gsl_spmatrix_get(A, i, j); double ATji = gsl_spmatrix_get(AT, j, i); double Bij = gsl_spmatrix_get(B, i, j); double BTji = gsl_spmatrix_get(BT, j, i); if ((Aij != ATji) || (Bij != BTji) || (Aij != Bij)) status = 1; } } gsl_test(status, "test_memcpy: _transpose_memcpy M=%zu N=%zu triplet format", M, N); gsl_spmatrix_free(A); gsl_spmatrix_free(AT); gsl_spmatrix_free(B); gsl_spmatrix_free(BT); } } /* test_memcpy() */ static void test_ops(const size_t M, const size_t N, const gsl_rng *r) { size_t i, j; int status; /* test gsl_spmatrix_add */ { gsl_spmatrix *Ta = create_random_sparse(M, N, 0.2, r); gsl_spmatrix *Tb = create_random_sparse(M, N, 0.2, r); gsl_spmatrix *a = gsl_spmatrix_compcol(Ta); gsl_spmatrix *b = gsl_spmatrix_compcol(Tb); gsl_spmatrix *c = gsl_spmatrix_alloc_nzmax(M, N, 1, GSL_SPMATRIX_CCS); gsl_spmatrix_add(c, a, b); status = 0; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { double aij = gsl_spmatrix_get(a, i, j); double bij = gsl_spmatrix_get(b, i, j); double cij = gsl_spmatrix_get(c, i, j); if (aij + bij != cij) status = 1; } } gsl_test(status, "test_ops: _add M=%zu N=%zu compressed format", M, N); gsl_spmatrix_free(Ta); gsl_spmatrix_free(Tb); gsl_spmatrix_free(a); gsl_spmatrix_free(b); gsl_spmatrix_free(c); } } /* test_ops() */ int main() { gsl_rng *r = gsl_rng_alloc(gsl_rng_default); test_memcpy(10, 10, r); test_memcpy(10, 15, r); test_memcpy(53, 213, r); test_memcpy(920, 2, r); test_memcpy(2, 920, r); test_getset(20, 20, r); test_getset(30, 20, r); test_getset(15, 210, r); test_ops(20, 20, r); test_ops(50, 20, r); test_ops(20, 50, r); test_ops(76, 43, r); gsl_rng_free(r); exit (gsl_test_summary()); } /* main() */
{ "alphanum_fraction": 0.581379069, "avg_line_length": 26.7009345794, "ext": "c", "hexsha": "c59fcda2e3bedf5b1a74b4ccdcd05810243a81d7", "lang": "C", "max_forks_count": 224, "max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z", "max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z", "max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "utdsimmons/ohpc", "max_forks_repo_path": "tests/libs/gsl/tests/spmatrix/test.c", "max_issues_count": 1096, "max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z", "max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "utdsimmons/ohpc", "max_issues_repo_path": "tests/libs/gsl/tests/spmatrix/test.c", "max_line_length": 88, "max_stars_count": 692, "max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "utdsimmons/ohpc", "max_stars_repo_path": "tests/libs/gsl/tests/spmatrix/test.c", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z", "max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z", "num_tokens": 2711, "size": 8571 }
/* Copyright (c) 2015, Patrick Weltevrede All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <gsl/gsl_sort.h> #include "psrsalsa.h" int main(int argc, char **argv) { int read_log, centered_at_zero, file_column1, file_column2, colspecified, polspecified, filename, truncate, cdf, select; long ndata, i, j, k, nrbins, nrbinsy, *distr; float *cmap, *distr_float; double *data_x, *data_y, min_x_data, max_x_data, min_y_data, max_y_data; double min_x, max_x, min_y, max_y, dx, dy, x, y, s, rangex_min, rangex_max, rangey_min, rangey_max, extra_phase, select1, select2; int nrbins_specified, dx_specified, dy_specified, output_sigma, output_fraction, nrbins_specifiedy, twoDmode, showGraphics, rangex_set, rangey_set, plotlog, file_column2_defined, xlabelset, linewidth; char title[500], *filename_ptr, output_suffix[100], *oname; FILE *ofile; double min, max; psrsalsaApplication application; datafile_definition datain; pgplot_options_definition pgplot_options; pgplot_clear_options(&pgplot_options); initApplication(&application, "pdist", "[options] inputfile(s)"); application.switch_verbose = 1; application.switch_debug = 1; application.switch_iformat = 1; application.switch_formatlist = 1; application.switch_device = 1; application.switch_cmap = 1; application.switch_cmaplist = 1; nrbins_specified = 0; nrbins_specifiedy = 0; dx_specified = 0; dy_specified = 0; output_sigma = 0; output_fraction = 0; read_log = 0; twoDmode = 0; centered_at_zero = 1; extra_phase = 0; showGraphics = 0; xlabelset = 0; sprintf(title, "Distribution"); rangex_set = 0; rangey_set = 0; file_column1 = 1; file_column2 = 2; colspecified = 0; polspecified = 0; plotlog = 0; file_column2_defined = 1; application.cmap = PPGPLOT_HEAT; strcpy(output_suffix, "hist"); filename = 0; truncate = 0; cdf = 0; select = 0; linewidth = 1; if(argc < 2) { printf("Program to generate or plot a histogram by binning data. Also a cummulative\n"); printf("distribution can be generated. Usage:\n\n"); printApplicationHelp(&application); printf("Input options:\n"); printf("-2 Turn on 2D mode: Read in two columns of data, resulting in the\n"); printf(" distribution N(x,y) rathern than N(x).\n"); printf("-col \"c1 c2\" Specify two column numbers (counting from 1) to be used.\n"); printf(" Without the -2 option only one value needs to be specified.\n"); printf(" This option implies the input files are ascii files with each\n"); printf(" line having an equal number of columns. Lines starting with a #\n"); printf(" will be ignored.\n"); printf("-pol \"p1 p2\" This option implies that the input file is recognized as a\n"); printf(" pulsar format. Polarization p1 (and p2 in 2D mode), counting\n"); printf(" from zero, are used (all bins, freqs and subints). The default\n"); printf(" default is \"0 1\", or the integrated onpulse pulse energy for\n"); printf(" penergy output files in mode 1.\n"); printf("\nOutput options:\n"); printf("-ext Specify suffix, default is '%s'\n", output_suffix); printf("-output filename Write output to this file [def=.%s extension].\n", output_suffix); printf("-frac Output fraction of counts per bin rather than counts.\n"); printf("-sigma Generate extra column with the sqrt of the nr of counts.\n"); printf("\nDistribution options:\n"); printf("-cdf The cummulative distribution is generated. Use no -dx or -n.\n"); printf("-dx value Specify bin width (can also use -n).\n"); printf("-dy value Specify bin width used for the second column if -2 is used.\n"); printf("-log The base-10 log of the input values is used.\n"); printf("-n nr The range of input values is divided in nr bins.\n"); printf("-nx nr Same as -n\n"); printf("-ny nr Similar to -nx, but now for the second column if -2 is used.\n"); printf("-rangex \"x1 x2\" The range of bins produced in output will cover x1..x2, which\n"); printf(" should include all input values (see also -trunc). It therefore\n"); printf(" allows more bins to be generated than strictly necessary.\n"); printf("-rangey As -rangex, but now for second input column.\n"); printf("-select \"v1 v2\" Enabling this option will no longer result in a distribution.\n"); printf(" Instead all samples within the range of values specified with\n"); printf(" v1 and v2 will be outputted as two columns: the sample number\n"); printf(" and the value.\n"); printf("-trunc Modifies behaviour of -rangex and -rangey. Values outside the\n"); printf(" specified range are set to the extremes of the range.\n"); printf("-zero By default one of the bins will be centred at zero. This option\n"); printf(" results in the edge of a bin to coincides with zero. In both\n"); printf(" cases the reported locations of the bins are their centres.\n"); printf(" This means that in gnuplot you want to use \"with histeps\".\n"); printf("-zeroshift off Put in an extra offset off to where zero would fall with\n"); printf(" respect to a bin. -zero is equivalent to -zeroshift 0.5. \n"); printf("\nPlot options:\n"); printf("-plot Plot the distribution rather than writing output to file.\n"); printf("-plotlog The log10 of the counts is plotted (implies -plot and bins with\n"); printf(" zero counts are set to 1).\n"); printf("-overplot Like plot, but multiple input files are overplotted. The ranges\n"); printf(" are determined by first input file.\n"); printf("-title 'title' Set the title of the plot.\n"); printf("-xlabel 'label' Set label on horizontal axis.\n"); printf("-labels \"label_ch label_lw label_f box_ch box_lw box_f\"\n"); printf(" default is \"%.1f %d %d %.1f %d %d\"\n", pgplot_options.box.label_ch, pgplot_options.box.label_lw, pgplot_options.box.label_f, pgplot_options.box.box_labelsize, pgplot_options.box.box_lw, pgplot_options.box.box_f); printf("-lw Set line width of the histogram.\n"); printf("-vp \"left right bottom top\"\n"); printf(" Modify the dimensions of the plot. Default is \"%.2f %.2f %.2f %.2f\"\n", pgplot_options.viewport.dxplot, pgplot_options.viewport.xsize, pgplot_options.viewport.dyplot, pgplot_options.viewport.ysize); printf("\n"); printf("Please use the appropriate citation when using results of this software in your publications:\n\n"); printf("More information about fitting distributions (in the context of pulse energies) can be found in:\n"); printf(" - Weltevrede et al. 2006, A&A, 458, 269\n\n"); printCitationInfo(); terminateApplication(&application); return 0; }else { for(i = 1; i < argc; i++) { int index; index = i; if(processCommandLine(&application, argc, argv, &index)) { i = index; }else if(strcmp(argv[i], "-2") == 0) { twoDmode = 1; }else if(strcmp(argv[i], "-plot") == 0) { showGraphics = 1; }else if(strcmp(argv[i], "-overplot") == 0) { showGraphics = 2; }else if(strcmp(argv[i], "-plotlog") == 0) { plotlog = 1; if(showGraphics == 0) showGraphics = 1; }else if(strcmp(argv[i], "-xlabel") == 0) { xlabelset = i+1; i++; }else if(strcmp(argv[i], "-title") == 0) { strcpy(title, argv[i+1]); i++; }else if(strcmp(argv[i], "-output") == 0) { filename = i+1; i++; }else if(strcmp(argv[i], "-ext") == 0) { strcpy(output_suffix, argv[i+1]); i++; }else if(strcmp(argv[i], "-labels") == 0) { if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%f %d %d %f %d %d", &(pgplot_options.box.label_ch), &(pgplot_options.box.label_lw), &(pgplot_options.box.label_f), &(pgplot_options.box.box_labelsize), &(pgplot_options.box.box_lw), &(pgplot_options.box.box_f), NULL) == 0) { printerror(application.verbose_state.debug, "ERROR pdist: Cannot parse '%s' option.", argv[i]); return 0; } i++; }else if(strcmp(argv[i], "-lw") == 0) { if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%d", &linewidth, NULL) == 0) { printerror(application.verbose_state.debug, "ERROR pdist: Cannot parse '%s' option.", argv[i]); return 0; } i++; }else if(strcmp(argv[i], "-vp") == 0) { if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%f %f %f %f", &(pgplot_options.viewport.dxplot), &(pgplot_options.viewport.xsize), &(pgplot_options.viewport.dyplot), &(pgplot_options.viewport.ysize), NULL) == 0) { printerror(application.verbose_state.debug, "ERROR pdist: Cannot parse '%s' option.", argv[i]); return 0; } i++; }else if(strcmp(argv[i], "-col") == 0 || strcmp(argv[i], "-pol") == 0) { if(strcmp(argv[i], "-pol") == 0) polspecified = 1; else colspecified = 1; int ret; ret = parse_command_string(application.verbose_state, argc, argv, i+1, 0, 1, "%d %d", &file_column1, &file_column2, NULL); file_column2_defined = 0; if(ret == 2) { file_column2_defined = 1; }else if(ret == 0) { printerror(application.verbose_state.debug, "ERROR pdist: Cannot parse %s option, need 1 or 2 integer values.\n", argv[i]); return 0; } i++; }else if(strcmp(argv[i], "-n") == 0 || strcmp(argv[i], "-nx") == 0) { if(dx_specified) { printerror(application.verbose_state.debug, "Cannot use -n and -dx option simultaniously.\n"); return 0; } nrbins_specified = 1; if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%ld", &nrbins, NULL) == 0) { printerror(application.verbose_state.debug, "ERROR pdist: Cannot parse '%s' option.", argv[i]); return 0; } i++; }else if(strcmp(argv[i], "-ny") == 0) { if(dy_specified) { printerror(application.verbose_state.debug, "Cannot use -ny and -dy option simultaniously.\n"); return 0; } nrbins_specifiedy = 1; if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%ld", &nrbinsy, NULL) == 0) { printerror(application.verbose_state.debug, "ERROR pdist: Cannot parse '%s' option.", argv[i]); return 0; } i++; }else if(strcmp(argv[i], "-dx") == 0) { if(nrbins_specified) { printerror(application.verbose_state.debug, "Cannot use -n and -dx option simultaniously.\n"); return 0; } dx_specified = 1; if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%lf", &dx, NULL) == 0) { printerror(application.verbose_state.debug, "ERROR pdist: Cannot parse '%s' option.", argv[i]); return 0; } i++; }else if(strcmp(argv[i], "-dy") == 0) { if(nrbins_specifiedy) { printerror(application.verbose_state.debug, "Cannot use -ny and -dy option simultaniously.\n"); return 0; } dy_specified = 1; if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%lf", &dy, NULL) == 0) { printerror(application.verbose_state.debug, "ERROR pdist: Cannot parse '%s' option.", argv[i]); return 0; } i++; }else if(strcmp(argv[i], "-rangex") == 0) { rangex_set = 1; if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%lf %lf", &rangex_min, &rangex_max, NULL) == 0) { printerror(application.verbose_state.debug, "ERROR pdist: Cannot parse '%s' option.", argv[i]); return 0; } i++; }else if(strcmp(argv[i], "-rangey") == 0) { rangey_set = 1; if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%lf %lf", &rangey_min, &rangey_max, NULL) == 0) { printerror(application.verbose_state.debug, "ERROR pdist: Cannot parse '%s' option.", argv[i]); return 0; } i++; }else if(strcmp(argv[i], "-select") == 0) { select = 1; if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%lf %lf", &select1, &select2, NULL) == 0) { printerror(application.verbose_state.debug, "ERROR pdist: Cannot parse '%s' option.", argv[i]); return 0; } i++; }else if(strcmp(argv[i], "-trunc") == 0) { truncate = 1; }else if(strcmp(argv[i], "-sigma") == 0) { output_sigma = 1; }else if(strcmp(argv[i], "-log") == 0) { read_log = 1; }else if(strcmp(argv[i], "-zero") == 0) { centered_at_zero = 0; }else if(strcmp(argv[i], "-zeroshift") == 0) { if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%lf", &extra_phase, NULL) == 0) { printerror(application.verbose_state.debug, "ERROR pdist: Cannot parse '%s' option.", argv[i]); return 0; } i++; }else if(strcmp(argv[i], "-frac") == 0) { output_fraction = 1; }else if(strcmp(argv[i], "-cdf") == 0) { cdf = 1; }else { if(argv[i][0] == '-') { printerror(application.verbose_state.debug, "pdist: Unknown option: %s\n\nRun pdist without command line arguments to show help", argv[i]); terminateApplication(&application); return 0; }else { if(applicationAddFilename(i, application.verbose_state) == 0) return 0; } } } } if(applicationFilenameList_checkConsecutive(argv, application.verbose_state) == 0) { return 0; } if(numberInApplicationFilenameList(&application, argv, application.verbose_state) == 0) { printerror(application.verbose_state.debug, "ERROR pdist: No files specified"); return 0; } if(select) { if(twoDmode) { printerror(application.verbose_state.debug, "ERROR pdist: The -2 option cannot be used with -select.\n"); return 0; } if(cdf) { printerror(application.verbose_state.debug, "ERROR pdist: The -cdf option cannot be used with -select.\n"); return 0; } if(showGraphics) { printerror(application.verbose_state.debug, "ERROR pdist: No plots can be generated when using -select.\n"); return 0; } if(output_fraction) { printerror(application.verbose_state.debug, "ERROR pdist: The -frac option cannot be used with -select.\n"); return 0; } if(output_sigma) { printerror(application.verbose_state.debug, "ERROR pdist: The -sigma option cannot be used with -select.\n"); return 0; } } if(cdf) { if(nrbins_specified || dx_specified) { printerror(application.verbose_state.debug, "ERROR pdist: For a cdf -n and -dx should not be used.\n"); return 0; } if(twoDmode) { printerror(application.verbose_state.debug, "ERROR pdist: For a cdf only one input column is expected.\n"); return 0; } if(output_sigma) { printerror(application.verbose_state.debug, "ERROR pdist: For a cdf -sigma is not supported.\n"); return 0; } if(rangex_set || rangey_set || truncate) { printerror(application.verbose_state.debug, "ERROR pdist: For a cdf the -rangex and -rangey options are not supported.\n"); return 0; } }else { if(select == 0) { if(nrbins_specified == 0 && dx_specified == 0) { printerror(application.verbose_state.debug, "ERROR pdist: Specify resolution with the -n or -dx option.\n"); return 0; } if(twoDmode) { if(nrbins_specifiedy == 0 && dy_specified == 0) { printerror(application.verbose_state.debug, "ERROR pdist: Specify resolution with the -ny or -dy option.\n"); return 0; } } } } int initial_iformat, currentfile; currentfile = 1; initial_iformat = application.iformat; while((filename_ptr = getNextFilenameFromList(&application, argv, application.verbose_state)) != NULL) { application.iformat = initial_iformat; if(application.iformat <= 0 && colspecified == 0) { application.iformat = guessPSRData_format(filename_ptr, 1, application.verbose_state); if(application.iformat == -2 || application.iformat == -3) return 0; } if(colspecified) application.iformat = -1; if(polspecified && application.iformat <= 0) { printerror(application.verbose_state.debug, "ERROR pdist: Input file cannot be opened. Please check if file %s exists and otherwise specify the correct input format with the -iformat option if the format is supported, but not automatically recognized. Data is not recognized as pulsar data, but -pol was used. Use -col for ascii files.\n", filename_ptr); return 0; } if(application.iformat > 0) { verbose_definition verbose; cleanVerboseState(&verbose); copyVerboseState(application.verbose_state, &verbose); if(application.iformat == PSRCHIVE_ASCII_format) { if(verbose.debug == 0) verbose.verbose = 0; } i = openPSRData(&datain, filename_ptr, application.iformat, 0, 1, 1, verbose); if(i == 0) { printerror(application.verbose_state.debug, "ERROR pdist: Error opening data"); return 0; } if(polspecified == 0) { file_column1 = 0; file_column2 = 1; } if(application.iformat == PSRCHIVE_ASCII_format && datain.gentype == GENTYPE_PENERGY) { if(application.verbose_state.verbose) printf("The file is a penergy file generated in mode 1.\n"); if(polspecified == 0) { printwarning(application.verbose_state.debug, "WARNING pdist: -pol not specified, default in the integrated on-pulse energy (-pol 2)"); file_column1 = 2; } } if(application.verbose_state.verbose) printf("Loading %ld points", datain.NrSubints*datain.NrFreqChan*datain.NrBins); if(twoDmode) printf(" times two input polarizations"); printf("\n"); data_x = malloc(datain.NrSubints*datain.NrFreqChan*datain.NrBins*sizeof(double)); data_y = malloc(datain.NrSubints*datain.NrFreqChan*datain.NrBins*sizeof(double)); if(data_x == NULL || data_y == NULL) { printerror(application.verbose_state.debug, "ERROR pdist: Memory allocation error.\n"); return 0; } long subintnr, freqnr, binnr; long double total_x, total_y; ndata = 0; total_x = 0; total_y = 0; min_x_data = max_x_data = 0; for(subintnr = 0; subintnr < datain.NrSubints; subintnr++) { for(freqnr = 0; freqnr < datain.NrFreqChan; freqnr++) { for(binnr = 0; binnr < datain.NrBins; binnr++) { float dummy_float; if(readPulsePSRData(&datain, subintnr, file_column1, freqnr, binnr, 1, &dummy_float, application.verbose_state) == 0) { printerror(application.verbose_state.debug, "ERROR pdist: Read error, shouldn't happen.\n"); return 0; } data_x[ndata] = dummy_float; if(read_log) { if(data_x[ndata] <= 0) { printerror(application.verbose_state.debug, "ERROR pdist: Cannot take logarithm of a value <= 0.\n"); return 0; } data_x[ndata] = log10(data_x[ndata]); } if(data_x[ndata] > max_x_data || ndata == 0) { max_x_data = data_x[ndata]; } if(data_x[ndata] < min_x_data || ndata == 0) { min_x_data = data_x[ndata]; } total_x += data_x[ndata]; if(twoDmode) { if(readPulsePSRData(&datain, subintnr, file_column2, freqnr, binnr, 1, &dummy_float, application.verbose_state) == 0) { printerror(application.verbose_state.debug, "ERROR pdist: Read error, shouldn't happen.\n"); return 0; } data_y[ndata] = dummy_float; if(read_log) { if(data_y[ndata] <= 0) { printerror(application.verbose_state.debug, "ERROR pdist: Cannot take logarithm of a value <= 0.\n"); return 0; } data_y[ndata] = log10(data_y[ndata]); } if(ndata == 0) { max_y_data = data_y[ndata]; min_y_data = data_y[ndata]; } if(data_y[ndata] > max_y_data) { max_y_data = data_y[ndata]; } if(data_y[ndata] < min_y_data) { min_y_data = data_y[ndata]; } total_y += data_y[ndata]; } ndata++; } } } if(application.verbose_state.verbose) { printf("xrange = %e ... %e\n", min_x_data, max_x_data); printf("average = %Le\n", total_x/(long double)ndata); if(twoDmode) { printf("yrange = %e ... %e\n", min_y_data, max_y_data); printf("average = %Le\n", total_y/(long double)ndata); } } closePSRData(&datain, 0, application.verbose_state); }else { int skiplines = 0; if(twoDmode) { if(application.verbose_state.verbose) fprintf(stdout, "Loading x values from ascii file\n"); if(read_ascii_column_double(filename_ptr, skiplines, '#', -1, 1, &ndata, file_column1, 1.0, read_log, &data_x, &min_x_data, &max_x_data, NULL, application.verbose_state, 1) == 0) { printerror(application.verbose_state.debug, "ERROR pdist: cannot load file.\n"); if(colspecified) { printwarning(application.verbose_state.debug, "WARNING pdist: Using the -col option implies the input file is a simple ascii file. For penergy output (in mode 1), or an other recognized pulsar format, use the -pol option instead.\n"); } return 0; } if(application.verbose_state.verbose) fprintf(stdout, "Loading y values from ascii file\n"); if(file_column2_defined == 0) { printerror(application.verbose_state.debug, "In 2D mode, two input columns should be specified with the -col option.\n"); return 0; } if(read_ascii_column_double(filename_ptr, skiplines, '#', -1, 1, &ndata, file_column2, 1.0, read_log, &data_y, &min_y_data, &max_y_data, NULL, application.verbose_state, 1) == 0) { printerror(application.verbose_state.debug, "ERROR pdist: cannot load file.\n"); if(colspecified) { printwarning(application.verbose_state.debug, "WARNING pdist: Using the -col option implies the input file is a simple ascii file. For penergy output (in mode 1), or an other recognized pulsar format, use the -pol option instead.\n"); } return 0; } }else { if(application.verbose_state.verbose) fprintf(stdout, "Loading values from ascii file\n"); if(read_ascii_column_double(filename_ptr, skiplines, '#', -1, 1, &ndata, file_column1, 1.0, read_log, &data_x, &min_x_data, &max_x_data, NULL, application.verbose_state, 1) == 0) { printerror(application.verbose_state.debug, "ERROR pdist: cannot load file.\n"); if(colspecified) { printwarning(application.verbose_state.debug, "WARNING pdist: Using the -col option implies the input file is a simple ascii file. For penergy output (in mode 1), or an other recognized pulsar format, use the -pol option instead.\n"); } return 0; } data_y = malloc(ndata*sizeof(double)); if(data_y == NULL) { printerror(application.verbose_state.debug, "ERROR pdist: Memory allocation error.\n"); return 0; } } } if(cdf == 0 && select == 0) { switch(set_binning_histogram(min_x_data, max_x_data, rangex_set, rangex_min, rangex_max, nrbins_specified, nrbins, centered_at_zero, extra_phase, &min_x, &max_x, &dx, application.verbose_state)) { case 0: break; case 1: case 2: return 0; default: { printerror(application.verbose_state.debug, "ERROR pdist: Unknown return value for call to set_binning_histogram.\n"); return 0; } } if(rangex_set) { if(min_x > min_x_data || max_x < max_x_data) { if(truncate == 0) { printerror(application.verbose_state.debug, "ERROR pdist: Values are outside specified -rangex option. You may want to use -trunc?\n"); return 0; } } } if(twoDmode) { switch(set_binning_histogram(min_y_data, max_y_data, rangey_set, rangey_min, rangey_max, nrbins_specifiedy, nrbinsy, centered_at_zero, extra_phase, &min_y, &max_y, &dy, application.verbose_state)) { case 0: break; case 1: case 2: return 0; default: { printerror(application.verbose_state.debug, "ERROR pdist: Unknown return value for call to set_binning_histogram.\n"); return 0; } } if(application.verbose_state.verbose) { fprintf(stdout, "Going to use binsize dx=%e and dy=%e.\n", dx, dy); } } if(rangey_set) { if(min_y > min_y_data || max_y < max_y_data) { if(truncate == 0) { printerror(application.verbose_state.debug, "ERROR pdist: Values are outside specified -rangey option. You may want to use -trunc?\n"); return 0; } } } } if(cdf == 0) { if(truncate) { if(rangex_set) { for(i = 0; i < ndata; i++) { if(data_x[i] < min_x) data_x[i] = min_x; if(data_x[i] > max_x) data_x[i] = max_x; } } if(rangey_set) { for(i = 0; i < ndata; i++) { if(data_y[i] < min_y) data_y[i] = min_y; if(data_y[i] > max_y) data_y[i] = max_y; } } } } if(cdf == 0 && select == 0) nrbins = calculate_bin_number(max_x, dx, min_x, centered_at_zero, extra_phase) + 1; else nrbins = ndata; if(select == 0) fprintf(stdout, "Distribution will have %ld bins.\n", nrbins); if(twoDmode) { nrbinsy = calculate_bin_number(max_y, dy, min_y, centered_at_zero, extra_phase)+ 1; fprintf(stdout, "Distribution will have %ld y-bins.\n", nrbinsy); }else { nrbinsy = 1; } distr = (long *)malloc(nrbins*nrbinsy*sizeof(long)); if(distr == NULL) { printerror(application.verbose_state.debug, "ERROR pdist: Cannot allocate memory.\n"); return 0; } for(i = 0; i < nrbins*nrbinsy; i++) distr[i] = 0; if(showGraphics) { pgplot_options.box.drawtitle = 1; strcpy(pgplot_options.box.title, title); if(xlabelset) { strcpy(pgplot_options.box.xlabel, argv[xlabelset]); }else { if(read_log) strcpy(pgplot_options.box.xlabel, "log X"); else strcpy(pgplot_options.box.xlabel, "X"); } if(twoDmode) { if(read_log) strcpy(pgplot_options.box.ylabel, "log Y"); else strcpy(pgplot_options.box.ylabel, "Y"); }else { if(plotlog) strcpy(pgplot_options.box.ylabel, "log N"); else strcpy(pgplot_options.box.ylabel, "N"); } strcpy(pgplot_options.viewport.plotDevice, application.pgplotdevice); if(showGraphics == 2) { pgplot_options.viewport.dontclose = 1; } if(currentfile > 1 && showGraphics == 2) { pgplot_options.viewport.noclear = 1; pgplot_options.viewport.dontopen = 1; pgplot_options.box.drawbox = 0; pgplot_options.box.drawtitle = 0; pgplot_options.box.drawlabels = 0; } }else { if(filename != 0) { oname = (char *) calloc(strlen(argv[filename])+1, 1); }else { oname = (char *) calloc(strlen(filename_ptr)+strlen(output_suffix)+2, 1); } if(oname == NULL) { printerror(application.verbose_state.debug, "ERROR pdist: Memory allocation error.\n"); return 0; } if(filename != 0) { strcpy(oname, argv[filename]); }else { sprintf(oname,"%s.%s", filename_ptr, output_suffix); } printf("Output Ascii to %s\n",oname); ofile = fopen(oname,"w+"); if(ofile == NULL) { printerror(application.verbose_state.debug, "ERROR pdist: Cannot open '%s'", oname); perror(""); return 0; } } if(twoDmode) { for(i = 0; i < ndata; i++) { j = calculate_bin_number(data_x[i], dx, min_x, centered_at_zero, extra_phase); k = calculate_bin_number(data_y[i], dy, min_y, centered_at_zero, extra_phase); if(j < 0 || j >= nrbins) { printerror(application.verbose_state.debug, "BUG!\n"); return 0; } if(k < 0 || k >= nrbinsy) { printerror(application.verbose_state.debug, "BUG!\n"); return 0; } distr[k*nrbins+j] += 1; } for(i = 0; i < nrbins; i++) { for(j = 0; j < nrbinsy; j++) { x = calculate_bin_location(i, dx, min_x, centered_at_zero, extra_phase); y = calculate_bin_location(j, dy, min_y, centered_at_zero, extra_phase); if(!showGraphics) { fprintf(ofile, "%e %e", x, y); if(!output_fraction) fprintf(ofile, " %ld", distr[j*nrbins+i]); else fprintf(ofile, " %e", distr[j*nrbins+i]/(double)ndata); if(output_sigma) { if(distr[j*nrbins+i] == 0) s = 1; else s = sqrt(distr[j*nrbins+i]); if(output_fraction) s /= (double)ndata; fprintf(ofile, " %e", s); } } if(!showGraphics) { fprintf(ofile, "\n"); } } } if(showGraphics) { cmap = (float *)malloc(nrbins*nrbinsy*sizeof(float)); if(cmap == NULL) { printerror(application.verbose_state.debug, "Cannot allocate memory.\n"); return 0; } if(plotlog) { if(distr[0] > 0) { min = log10(distr[0]); max = log10(distr[0]); }else { min = max = 0; } }else { min = distr[0]; max = distr[0]; } for(i = 0; i < nrbins; i++) { for(j = 0; j <nrbinsy; j++) { if(plotlog) { if(distr[i*nrbinsy+j] > 0) cmap[i*nrbinsy+j] = log10(distr[i*nrbinsy+j]); else cmap[i*nrbinsy+j] = 0; } else cmap[i*nrbinsy+j] = distr[i*nrbinsy+j]; if(cmap[i*nrbinsy+j] > max) max = cmap[i*nrbinsy+j]; if(cmap[i*nrbinsy+j] < min) min = cmap[i*nrbinsy+j]; } } printf("Count range: %f to %f\n", min, max); int showwedge = 0; if(pgplotMap(&pgplot_options, cmap, nrbins, nrbinsy, calculate_bin_location(0, dx, min_x, centered_at_zero, extra_phase), calculate_bin_location(0, dx, max_x, centered_at_zero, extra_phase), calculate_bin_location(0, dx, min_x, centered_at_zero, extra_phase)-0.5*dx, calculate_bin_location(0, dx, max_x, centered_at_zero, extra_phase)+0.5*dx, calculate_bin_location(0, dy, min_y, centered_at_zero, extra_phase), calculate_bin_location(0, dy, max_y, centered_at_zero, extra_phase), calculate_bin_location(0, dy, min_y, centered_at_zero, extra_phase)-0.5*dy, calculate_bin_location(0, dy, max_y, centered_at_zero, extra_phase)+0.5*dy, application.cmap, 0, 0, 0, NULL, 0, 0, 1.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, showwedge, 0, 0, application.verbose_state) == 0) { printerror(application.verbose_state.debug, "ERROR pdist: Plotting failed.\n"); return 0; } free(cmap); } }else { if(select) { nrbins = 0; for(i = 0; i < ndata; i++) { if(data_x[i] >= select1 && data_x[i] <= select2) { nrbins++; } } j = 0; for(i = 0; i < ndata; i++) { if(data_x[i] >= select1 && data_x[i] <= select2) { distr[j] = i; data_y[j] = data_x[i]; j++; } } }else { if(cdf == 0) { for(i = 0; i < ndata; i++) { j = calculate_bin_number(data_x[i], dx, min_x, centered_at_zero, extra_phase); if(j < 0 || j >= nrbins) { printerror(application.verbose_state.debug, "BUG! bin number %ld outside range.\n", j); exit(0); } distr[j] += 1; } }else { gsl_sort(data_x, 1, ndata); for(i = 0; i < ndata; i++) { data_y[i] = (i+1)/(double)(ndata); } } } if(!showGraphics) { for(i = 0; i < nrbins; i++) { x = i*dx; if(cdf == 0) { if(select == 0) { fprintf(ofile, "%e", calculate_bin_location(i, dx, min_x, centered_at_zero, extra_phase)); }else { fprintf(ofile, "%ld", distr[i]); } }else { fprintf(ofile, "%e", data_x[i]); } if(!output_fraction) { if(cdf == 0) { if(select == 0) { fprintf(ofile, " %ld", distr[i]); }else { fprintf(ofile, " %e", data_y[i]); } }else { fprintf(ofile, " %e", data_y[i]); } }else { if(cdf == 0) { fprintf(ofile, " %e", distr[i]/(double)ndata); }else { fprintf(ofile, " %e", data_y[i]); } } if(output_sigma) { if(distr[i] == 0) s = 1; else s = sqrt(distr[i]); if(output_fraction) s /= (double)ndata; fprintf(ofile, " %e", s); } fprintf(ofile, "\n"); } }else { float *distr_x_float; distr_float = malloc(nrbins*sizeof(float)); if(distr_float == NULL) { printerror(application.verbose_state.debug, "ERROR pdist: Cannot allocate memory\n"); return 0; } if(cdf == 0) { for(i = 0; i < nrbins; i++) { distr_float[i] = distr[i]; if(output_fraction) distr_float[i] /= (double)ndata; if(plotlog) { if(distr[i] > 0) { distr_float[i] = log10(distr_float[i]); }else { if(output_fraction) { distr_float[i] = log10(1.0/(float)ndata); }else { distr_float[i] = 0; } } } } }else { distr_x_float = malloc(nrbins*sizeof(float)); if(distr_x_float == NULL) { printerror(application.verbose_state.debug, "ERROR pdist: Cannot allocate memory\n"); return 0; } for(i = 0; i < nrbins; i++) { distr_float[i] = data_y[i]; distr_x_float[i] = data_x[i]; } } int forceMinZero, dontsetranges, colour; forceMinZero = 1; if(plotlog) forceMinZero = 0; dontsetranges = 0; colour = 1; if(showGraphics == 2) { if(currentfile > 1) dontsetranges = 1; colour = currentfile; } if(cdf == 0) { if(pgplotGraph1(&pgplot_options, distr_float, NULL, NULL, nrbins, calculate_bin_location(0, dx, min_x, centered_at_zero, extra_phase), calculate_bin_location(nrbins-1, dx, min_x, centered_at_zero, extra_phase), dontsetranges, calculate_bin_location(0, dx, min_x, centered_at_zero, extra_phase) - dx, calculate_bin_location(nrbins-1, dx, min_x, centered_at_zero, extra_phase) + dx, 0, 0, forceMinZero, 1, 0, linewidth, 0, colour, 1, NULL, -1, application.verbose_state) == 0) { printerror(application.verbose_state.debug, "ERROR pdist: Cannot plot graph\n"); return 0; } }else { if(pgplotGraph1(&pgplot_options, distr_float, distr_x_float, NULL, nrbins, 0, 0, dontsetranges, 0, 0, 0, 0, forceMinZero, 1*0, 0, linewidth, 0, colour, 1, NULL, -1, application.verbose_state) == 0) { printerror(application.verbose_state.debug, "ERROR pdist: Cannot plot graph\n"); return 0; } free(distr_x_float); } free(distr_float); } } free(data_x); free(data_y); free(distr); if(showGraphics == 0) { fclose(ofile); free(oname); } if(showGraphics == 1) { if(currentfile != numberInApplicationFilenameList(&application, argv, application.verbose_state)) { i = pgplot_device_type(application.pgplotdevice, application.verbose_state); if(i < 3 || i > 10) { printf("Press a key to continue\n"); fflush(stdout); pgetch(); } } } currentfile += 1; } if(showGraphics == 2) { ppgend(); } terminateApplication(&application); return 0; }
{ "alphanum_fraction": 0.6419306352, "avg_line_length": 39.3925438596, "ext": "c", "hexsha": "31f0ad265cd5b1a5ecf2e926704a3cffcd624b44", "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": "e5074b552d1c404123dee058d5cee79ea230b5a9", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "David-McKenna/psrsalsa", "max_forks_repo_path": "src/prog/pdist.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9", "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": "David-McKenna/psrsalsa", "max_issues_repo_path": "src/prog/pdist.c", "max_line_length": 755, "max_stars_count": null, "max_stars_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "David-McKenna/psrsalsa", "max_stars_repo_path": "src/prog/pdist.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 10204, "size": 35926 }
#include <gsl/gsl_combination.h> #include <caml/alloc.h> #include <caml/bigarray.h> #include <caml/memory.h> static void combi_of_val(gsl_combination *c, value vc) { c->n = Int_val(Field(vc, 0)); c->k = Int_val(Field(vc, 1)); c->data = Data_bigarray_val(Field(vc, 2)); } CAMLprim value ml_gsl_combination_init_first(value vc) { gsl_combination c; combi_of_val(&c, vc); gsl_combination_init_first(&c); return Val_unit; } CAMLprim value ml_gsl_combination_init_last(value vc) { gsl_combination c; combi_of_val(&c, vc); gsl_combination_init_last(&c); return Val_unit; } CAMLprim value ml_gsl_combination_valid(value vc) { int r; gsl_combination c; combi_of_val(&c, vc); r = gsl_combination_valid(&c); return Val_not(Val_bool(r)); } CAMLprim value ml_gsl_combination_next(value vc) { gsl_combination c; combi_of_val(&c, vc); gsl_combination_next(&c); return Val_unit; } CAMLprim value ml_gsl_combination_prev(value vc) { gsl_combination c; combi_of_val(&c, vc); gsl_combination_prev(&c); return Val_unit; }
{ "alphanum_fraction": 0.6980108499, "avg_line_length": 20.4814814815, "ext": "c", "hexsha": "f59dfd7656972c2f8bd298cd99d58ba50af13fd0", "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": "65dd093eddbd62740e615fd48da4f6de4fd528f4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "nrlucaroni/pareto", "max_forks_repo_path": "lib/mlgsl_extra.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "65dd093eddbd62740e615fd48da4f6de4fd528f4", "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": "nrlucaroni/pareto", "max_issues_repo_path": "lib/mlgsl_extra.c", "max_line_length": 54, "max_stars_count": 1, "max_stars_repo_head_hexsha": "65dd093eddbd62740e615fd48da4f6de4fd528f4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "nrlucaroni/pareto", "max_stars_repo_path": "lib/mlgsl_extra.c", "max_stars_repo_stars_event_max_datetime": "2017-12-06T08:05:19.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-06T08:05:19.000Z", "num_tokens": 326, "size": 1106 }
/* Copyright (C) 2006 Imperial College London and others. Please see the AUTHORS file in the main source directory for a full list of copyright holders. Prof. C Pain Applied Modelling and Computation Group Department of Earth Science and Engineering Imperial College London amcgsoftware@imperial.ac.uk This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 2.1 of the License. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef COMMAND_LINE_OPTIONS_H #define COMMAND_LINE_OPTIONS_H #include "confdefs.h" #include "version.h" #include "Tokenize.h" #ifdef _AIX #include <unistd.h> #else #include <getopt.h> #endif #ifdef HAVE_MPI #include <mpi.h> #endif #ifdef HAVE_PETSC #include <petsc.h> #endif #include <signal.h> #include <cstdlib> #include <iostream> #include <map> #include <sstream> #include <string> #include <vector> #include "fmangle.h" extern std::map<std::string, std::string> fl_command_line_options; void ParseArguments(int argc, char** argv); void PetscInit(int argc, char** argv); void print_version(std::ostream& stream = std::cerr); void qg_usage(char *cmd); extern "C" { void set_global_debug_level_fc(int *val); } #endif
{ "alphanum_fraction": 0.7358066329, "avg_line_length": 24.7083333333, "ext": "h", "hexsha": "23ba4c54b646583798b8e2d61a3e0dc1d82c850b", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-10-28T17:16:31.000Z", "max_forks_repo_forks_event_min_datetime": "2020-05-21T22:50:19.000Z", "max_forks_repo_head_hexsha": "cfcba990d52ccf535171cf54c0a91b184db6f276", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "msc-acse/acse-9-independent-research-project-Wade003", "max_forks_repo_path": "software/multifluids_icferst/include/qg_usage.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "cfcba990d52ccf535171cf54c0a91b184db6f276", "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": "msc-acse/acse-9-independent-research-project-Wade003", "max_issues_repo_path": "software/multifluids_icferst/include/qg_usage.h", "max_line_length": 76, "max_stars_count": 2, "max_stars_repo_head_hexsha": "cfcba990d52ccf535171cf54c0a91b184db6f276", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "msc-acse/acse-9-independent-research-project-Wade003", "max_stars_repo_path": "software/multifluids_icferst/include/qg_usage.h", "max_stars_repo_stars_event_max_datetime": "2020-05-11T03:08:38.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-11T02:39:46.000Z", "num_tokens": 417, "size": 1779 }
/* monte/gsl_monte_vegas.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Michael Booth * * 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. */ /* header for the gsl "vegas" routines. Mike Booth, May 1998 */ #ifndef __GSL_MONTE_VEGAS_H__ #define __GSL_MONTE_VEGAS_H__ #include <gsl/gsl_rng.h> #include <gsl/gsl_monte.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 enum {GSL_VEGAS_MODE_IMPORTANCE = 1, GSL_VEGAS_MODE_IMPORTANCE_ONLY = 0, GSL_VEGAS_MODE_STRATIFIED = -1}; typedef struct { /* grid */ size_t dim; size_t bins_max; unsigned int bins; unsigned int boxes; /* these are both counted along the axes */ double * xi; double * xin; double * delx; double * weight; double vol; double * x; int * bin; int * box; /* distribution */ double * d; /* control variables */ double alpha; int mode; int verbose; unsigned int iterations; int stage; /* scratch variables preserved between calls to vegas1/2/3 */ double jac; double wtd_int_sum; double sum_wgts; double chi_sum; double chisq; double result; double sigma; unsigned int it_start; unsigned int it_num; unsigned int samples; unsigned int calls_per_box; FILE * ostream; } gsl_monte_vegas_state; int gsl_monte_vegas_integrate(gsl_monte_function * f, double xl[], double xu[], size_t dim, size_t calls, gsl_rng * r, gsl_monte_vegas_state *state, double* result, double* abserr); gsl_monte_vegas_state* gsl_monte_vegas_alloc(size_t dim); int gsl_monte_vegas_init(gsl_monte_vegas_state* state); void gsl_monte_vegas_free (gsl_monte_vegas_state* state); __END_DECLS #endif /* __GSL_MONTE_VEGAS_H__ */
{ "alphanum_fraction": 0.6868877167, "avg_line_length": 25.0377358491, "ext": "h", "hexsha": "b328307e1e879ea026548bd82d77fc9852a8887a", "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/monte/gsl_monte_vegas.h", "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/monte/gsl_monte_vegas.h", "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/monte/gsl_monte_vegas.h", "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": 699, "size": 2654 }
#include "multivar_support.h" #include "multi_modelstruct.h" #include "emulator_struct.h" #include "modelstruct.h" #include "libEmu/estimate_threaded.h" #include <math.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> /** * estimates the thetas for an allocated multvariate model and outputs the * info to outfp * * requries: * m must have been succesfully allocated and pca'd * outfp is an open fileptr */ void estimate_multi(multi_modelstruct *m, FILE* outfp) { int i; for(i = 0; i < m->nr; i++){ estimate_thetas_threaded(m->pca_model_array[i], m->pca_model_array[i]->options); } // dump the trained modelstruct, this maybe should go somewhere else dump_multi_modelstruct(outfp, m); } multi_emulator *alloc_multi_emulator(multi_modelstruct *m) { int i; multi_emulator *e = (multi_emulator*)malloc(sizeof(multi_emulator)); e->nt = m->nt; e->nr = m->nr; e->nparams = m->nparams; e->nmodel_points = m->nmodel_points; // have to read these out of the pca array e->nregression_fns = m->pca_model_array[0]->options->nregression_fns; e->nthetas = m->pca_model_array[0]->options->nthetas; e->model = m; // allocate the nr emulators we need e->emu_struct_array = (emulator_struct**)malloc(sizeof(emulator_struct*)*e->nr); for(i = 0; i < e->nr; i++) e->emu_struct_array[i] = alloc_emulator_struct(m->pca_model_array[i]); return e; } /** * free allocated memory */ void free_multi_emulator(multi_emulator *e) { int i; free_multimodelstruct(e->model); for(i = 0; i < e->nr; i++) free_emulator_struct(e->emu_struct_array[i]); free(e->emu_struct_array); } /** * sample the multivariate emulator at the_point, returns values in the *PCA* space. * The returned values will be vectors of length emu->model->nr *not* emu->model->nt * * requires: * emu has been allocated from a multi_modelstruct, and * the_mean and the_variance point to allocated gsl_vectors of length (emu->model->nr) * * @argument emu: a multi_emulator structure created from an estimated multi_modelstruct with alloc_multi_emulator * @argument the_point: the location in parameter space (nparams) length vector * @argument the_mean: the emulated mean values (nr length) * @argument the_variance: the emulated variance values (nr length) */ void emulate_point_multi_pca(multi_emulator *emu, gsl_vector *the_point, gsl_vector *the_mean, gsl_vector *the_variance) { int i; // sample the nr emulators // the results are directly fed back into the_mean and the_variance for(i = 0; i < emu->nr; i++) emulate_point(emu->emu_struct_array[i], the_point, gsl_vector_ptr(the_mean, i), gsl_vector_ptr(the_variance, i)); } /** * emulate the values of a point in a multivariate model, returns values in the REAL Observable space. * This means that the values output here will be in the same space as the training data. * * requries: * emu has been allocated from a multi_modelstruct * the_mean and the_variance point to allocated gsl_vectors of length (emu->model->nt) * * @argument emu: a multi_emulator structure created from an estimated multi_modelstruct with alloc_multi_emulator * @argument the_point: the location in parameter space (nparams) length vector * @argument the_mean: the emulated mean values (t length) * @argument the_variance: the emulated variance values (t length) */ void emulate_point_multi(multi_emulator *emu, gsl_vector *the_point, gsl_vector *the_mean, gsl_vector *the_variance) { int i, j; int nr = emu->nr; int nt = emu->nt; double vec_mat_sum; // the mean and variance in the PCA space gsl_vector *mean_pca = gsl_vector_alloc(nr); gsl_vector *var_pca = gsl_vector_alloc(nr); // first we sample the nr emulators for(i = 0; i < emu->nr; i++) emulate_point(emu->emu_struct_array[i], the_point, gsl_vector_ptr(mean_pca, i), gsl_vector_ptr(var_pca, i)); /** * now we have to project back into the REAL space from the PCA space * mean_real (nt) = training_mean (nt) + pca_evec_r %*% diag(sqrt(pca_evals_R)) %*% mean_pca */ gsl_vector *mean_real = gsl_vector_alloc(nt); gsl_vector *temp = gsl_vector_alloc(nt); gsl_vector_memcpy(mean_real, emu->model->training_mean); vec_mat_sum = 0.0; for(i = 0; i < nt; i++){ for(j = 0; j < nr; j++) vec_mat_sum += gsl_matrix_get(emu->model->pca_evecs_r, i, j) * sqrt(gsl_vector_get(emu->model->pca_evals_r, j))*gsl_vector_get(mean_pca, j); // save the sum scaled by the sqrt of the eval //gsl_vector_set(temp, i, vec_mat_sum*sqrt(gsl_vector_get(emu->model->pca_evals_r, i))); gsl_vector_set(temp, i, vec_mat_sum); vec_mat_sum = 0.0; } gsl_vector_add(mean_real, temp); gsl_vector_memcpy(the_mean, mean_real); // save the final mean /** * project back the variance * yVar_i = Sum_k=0^{nr} ( U_i_k * U_i_k * lambda_k * V_k) */ gsl_vector_set_zero(temp); vec_mat_sum = 0.0; for(i = 0; i < nt; i++){ for(j = 0; j < nr; j++) vec_mat_sum += pow(gsl_matrix_get(emu->model->pca_evecs_r, i, j), 2.0) * gsl_vector_get(emu->model->pca_evals_r, j) * gsl_vector_get(var_pca, j); gsl_vector_set(the_variance, i, vec_mat_sum); vec_mat_sum = 0.0; } gsl_vector_free(mean_real); gsl_vector_free(temp); gsl_vector_free(mean_pca); gsl_vector_free(var_pca); } /** * repeats a lot of the code in emulate_point_multi, this is annoying * the_covar is an nt X nt matrix * * for facundo, 26.03.2013 */ void emulate_point_multi_covar(multi_emulator *emu, gsl_vector *the_point, gsl_vector *the_mean, gsl_vector *the_variance, gsl_matrix *the_covar) { int i, j, k; int nr = emu->nr; int nt = emu->nt; double covar_contrib = 0.0; double vec_mat_sum; // the mean and variance in the PCA space gsl_vector *mean_pca = gsl_vector_alloc(nr); gsl_vector *var_pca = gsl_vector_alloc(nr); // first we sample the nr emulators for(i = 0; i < emu->nr; i++) emulate_point(emu->emu_struct_array[i], the_point, gsl_vector_ptr(mean_pca, i), gsl_vector_ptr(var_pca, i)); /** * now we have to project back into the REAL space from the PCA space * mean_real (nt) = training_mean (nt) + pca_evec_r %*% diag(sqrt(pca_evals_R)) %*% mean_pca */ gsl_vector *mean_real = gsl_vector_alloc(nt); gsl_vector *temp = gsl_vector_alloc(nt); gsl_vector_memcpy(mean_real, emu->model->training_mean); vec_mat_sum = 0.0; for(i = 0; i < nt; i++){ for(j = 0; j < nr; j++) vec_mat_sum += gsl_matrix_get(emu->model->pca_evecs_r, i, j) * sqrt(gsl_vector_get(emu->model->pca_evals_r, j))* gsl_vector_get(mean_pca, j); // save the sum scaled by the sqrt of the eval //gsl_vector_set(temp, i, vec_mat_sum*sqrt(gsl_vector_get(emu->model->pca_evals_r, i))); gsl_vector_set(temp, i, vec_mat_sum); vec_mat_sum = 0.0; } gsl_vector_add(mean_real, temp); gsl_vector_memcpy(the_mean, mean_real); // save the final mean /** * project back the variance * yVar_i = Sum_k=0^{nr} ( U_i_k * U_i_k * lambda_k * V_k) */ gsl_vector_set_zero(temp); vec_mat_sum = 0.0; for(i = 0; i < nt; i++){ for(j = 0; j < nr; j++) vec_mat_sum += pow(gsl_matrix_get(emu->model->pca_evecs_r, i, j), 2.0) * gsl_vector_get(emu->model->pca_evals_r, j) * gsl_vector_get(var_pca, j); gsl_vector_set(the_variance, i, vec_mat_sum); vec_mat_sum = 0.0; } // reset the covariance gsl_matrix_set_zero(the_covar); /** * loop over points in the nt x nt covariance matrix */ for(i = 0; i < nt; i++){ for(j = 0; j < nt; j++){ /** * C_ij = sum_k^{nr} [ U_i_k * U_j_k * lambda_k * V_k ] * * sum contributions over k */ covar_contrib = 0.0; for(k = 0; k < nr; k++){ covar_contrib += gsl_matrix_get(emu->model->pca_evecs_r, i, k) * gsl_matrix_get(emu->model->pca_evecs_r, j, k) * gsl_vector_get(emu->model->pca_evals_r, k) * gsl_vector_get(var_pca, k); } gsl_matrix_set(the_covar, i, j, covar_contrib); } } gsl_vector_free(mean_real); gsl_vector_free(temp); gsl_vector_free(mean_pca); gsl_vector_free(var_pca); }
{ "alphanum_fraction": 0.7000375422, "avg_line_length": 31.337254902, "ext": "c", "hexsha": "0c896f384e97d230b50567bed53eaa32054d31b0", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-01-30T16:43:33.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-30T16:43:33.000Z", "max_forks_repo_head_hexsha": "1c11f69c535acef8159ef0e780cca343785ea004", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jackdawjackdaw/emulator", "max_forks_repo_path": "src/multivar_support.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1c11f69c535acef8159ef0e780cca343785ea004", "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": "jackdawjackdaw/emulator", "max_issues_repo_path": "src/multivar_support.c", "max_line_length": 143, "max_stars_count": null, "max_stars_repo_head_hexsha": "1c11f69c535acef8159ef0e780cca343785ea004", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jackdawjackdaw/emulator", "max_stars_repo_path": "src/multivar_support.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2444, "size": 7991 }
// // Created by karl_ on 2020-5-3. // #include <math.h> #include <cblas.h> #include <imgproc/color-convert.h> gboolean imgproc_to_HSL(CoreImage *src, CoreImage **dst) { CoreSize *size; CoreColorSpace src_color_space; CorePixelType src_pixel_type; gdouble *src_data_cast, *dst_data; gdouble *hsl_pixel, *rgb_pixel, c_max, c_min, c; gsize i, j, area; size = core_image_get_size(src); area = core_size_get_area(size); src_color_space = core_image_get_color_space(src); src_pixel_type = core_image_get_pixel_type(src); g_return_val_if_fail(src_color_space == CORE_COLOR_SPACE_RGB, FALSE); if (core_pixel_is_double(src_pixel_type)) { src_data_cast = core_image_get_data(src); } else if (core_pixel_is_uint8(src_pixel_type)) { src_data_cast = malloc(sizeof(gdouble) * core_size_get_area(size)); for (i = 0; i < core_size_get_area(size) * 3; ++i) { src_data_cast[i] = ((guint8 *) core_image_get_data(src))[i] / core_pixel_get_range(src_pixel_type); } } else { return FALSE; } dst_data = g_malloc(sizeof(gdouble) * core_size_get_area(size)); for (i = 0; i < area; ++i) { hsl_pixel = dst_data + i * 3; rgb_pixel = src_data_cast + i * 3; c_min = 1; c_max = 0; c = c_max - c_min; for (j = 0; j < 3; ++j) { if (rgb_pixel[j] > c_max) { c_max = rgb_pixel[j]; } if (rgb_pixel[j] < c_min) { c_max = rgb_pixel[j]; } } /* Lightness */ hsl_pixel[2] = (c_min + c_max) / 2; /* Saturation */ if (!c) { hsl_pixel[1] = 0; } else { hsl_pixel[1] = c / (1 - fabs(hsl_pixel[2] * 2 - 1)); } /* Hue */ if (!c) { hsl_pixel[0] = 0; } else { if (rgb_pixel[0] == c_max) { hsl_pixel[0] = 1.0 / 6 * (rgb_pixel[1] - rgb_pixel[2]) / c; } else if (rgb_pixel[1] == c_max) { hsl_pixel[0] = 1.0 / 6 * (2 + (rgb_pixel[2] - rgb_pixel[0]) / c); } else if (rgb_pixel[2] == c_max) { hsl_pixel[0] = 1.0 / 6 * (4 + (rgb_pixel[0] - rgb_pixel[1]) / c); } } } if (*dst == NULL) { *dst = core_image_new_with_data(dst_data, CORE_COLOR_SPACE_HSL, CORE_PIXEL_D3, size, FALSE); } else { core_image_assign_data(*dst, dst_data, CORE_COLOR_SPACE_HSL, CORE_PIXEL_D3, size, FALSE); } if (core_pixel_is_uint8(src_pixel_type)) { free(src_data_cast); } g_object_unref(size); return TRUE; } gboolean imgproc_to_RGB(CoreImage *src, CoreImage **dst) { CoreSize *size; CoreColorSpace color_space; CorePixelType pixel_type; gdouble *src_data, *dst_data; gdouble *hsl_pixel, *rgb_pixel; gdouble c, h, h_ceil, x, m, r, g, b; gsize i, area; g_return_val_if_fail(src, FALSE); color_space = core_image_get_color_space(src); pixel_type = core_image_get_pixel_type(src); g_return_val_if_fail(color_space == CORE_COLOR_SPACE_HSL, FALSE); g_return_val_if_fail(pixel_type == CORE_PIXEL_D3, FALSE); size = core_image_get_size(src); area = core_size_get_area(size); src_data = core_image_get_data(src); dst_data = g_malloc(sizeof(gdouble) * area); for (i = 0; i < area; ++i) { hsl_pixel = src_data + i * 3; rgb_pixel = dst_data + i * 3; c = (1 - fabs(2 * hsl_pixel[2] - 1)); h = hsl_pixel[0] * 6.0; x = c * (1 - fabs(h - floor(h / 2) * 2 - 1)); h_ceil = ceil(h) + DBL_EPSILON; if (h_ceil >= 6) { r = c; g = 0; b = x; } else if (h_ceil >= 5) { r = x; g = 0; b = c; } else if (h_ceil >= 4) { r = 0; g = x; b = c; } else if (h_ceil >= 3) { r = 0; g = c; b = x; } else if (h_ceil >= 2) { r = x; g = c; b = 0; } else if (h_ceil >= 1) { r = c; g = x; b = 0; } else { r = g = b = 0; } m = hsl_pixel[2] - c / 2; rgb_pixel[0] = r + m; rgb_pixel[1] = g + m; rgb_pixel[2] = b + m; } if (*dst == NULL) { *dst = core_image_new_with_data(dst_data, CORE_COLOR_SPACE_RGB, CORE_PIXEL_D3, size, FALSE); } else { core_image_assign_data(*dst, dst_data, CORE_COLOR_SPACE_RGB, CORE_PIXEL_D3, size, FALSE); } g_object_unref(size); return TRUE; } gboolean imgproc_to_grayscale(CoreImage *src, CoreImage **dst) { gsize i; CoreSize *size; gdouble *dst_data_cast, *src_data_cast; gpointer src_data, dst_data; gsize channel, area; CorePixelType pixel_type; g_return_val_if_fail(src != NULL, FALSE); g_return_val_if_fail(dst != NULL, FALSE); size = core_image_get_size(src); area = core_size_get_area(size); pixel_type = core_image_get_pixel_type(src); channel = core_image_get_channel(src); src_data = core_image_get_data(src); if (core_pixel_is_uint8(pixel_type)) { src_data_cast = g_malloc(area * sizeof(gdouble) * channel); for (i = 0; i < area * channel; ++i) { src_data_cast[i] = (gdouble) ((guint8 *) src_data)[i]; } } else { /* do not need to cast if pixel type is Dx */ src_data_cast = src_data; } dst_data_cast = g_malloc(area * sizeof(gdouble)); cblas_dcopy(area, src_data_cast, channel, dst_data_cast, 1); for (i = 1; i < channel; ++i) { cblas_daxpy(area, 1.0, src_data_cast + i, channel, dst_data_cast, 1); } if (channel > 1) { cblas_daxpy(area, 1.0 / channel - 1.0, dst_data_cast, 1, dst_data_cast, 1); } if (core_pixel_is_uint8(pixel_type)) { pixel_type = CORE_PIXEL_U1; } else if (core_pixel_is_double(pixel_type)) { pixel_type = CORE_PIXEL_D1; } else { g_return_val_if_fail(FALSE, FALSE); } /* cast dst_data from double back to uchar if needed */ if (core_pixel_is_uint8(pixel_type)) { for (i = 0; i < area; ++i) { ((guint8 *) dst_data_cast)[i] = dst_data_cast[i]; } } dst_data = dst_data_cast; if (core_pixel_is_uint8(pixel_type)) { dst_data = g_realloc(dst_data, sizeof(guint8) * area); } /* assign result */ if (*dst == NULL) { *dst = core_image_new_with_data(dst_data, CORE_COLOR_SPACE_GRAY_SCALE, pixel_type, size, FALSE); } else { core_image_assign_data(*dst, dst_data, CORE_COLOR_SPACE_GRAY_SCALE, pixel_type, size, FALSE); } /* free additional allocated memory */ if (core_pixel_is_uint8(pixel_type)) { g_free(src_data_cast); } g_object_unref(size); return TRUE; } gboolean imgproc_to_binary_threshold(CoreImage *src, CoreImage **dst, gdouble threshold, gboolean inverse) { CoreImage *gray_src = NULL; CoreSize *size; gsize i, area; gdouble *src_data, *dst_data; CoreColorSpace color_space; CorePixelType pixel_type; g_return_val_if_fail(src != NULL, FALSE); g_return_val_if_fail(dst != NULL, FALSE); if (core_image_get_channel(src) > 1) { imgproc_to_grayscale(src, &gray_src); } else { gray_src = g_object_ref(src); } size = core_image_get_size(gray_src); area = core_size_get_area(size); src_data = core_image_get_data(gray_src); dst_data = g_malloc(sizeof(gdouble) * area); for (i = 0; i < area; ++i) { dst_data[i] = ((unsigned) (src_data[i] > threshold) ^ (unsigned) inverse) * 255.0; } if (*dst == NULL) { core_image_new_with_data(dst_data, CORE_COLOR_SPACE_BIN, CORE_PIXEL_U1, size, FALSE); } else { core_image_assign_data(*dst, dst_data, CORE_COLOR_SPACE_BIN, CORE_PIXEL_U1, size, FALSE); } g_object_unref(size); g_object_unref(gray_src); return TRUE; }
{ "alphanum_fraction": 0.5581087584, "avg_line_length": 32.2170542636, "ext": "c", "hexsha": "15e03a4463d18abee181c83a4e62c0915a24df89", "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": "de62bdd6fe0c7359453ce83fa6efa6592d9bf821", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zhengbanbufengbi/EasyPhotoshop", "max_forks_repo_path": "imgproc/color-convert.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "de62bdd6fe0c7359453ce83fa6efa6592d9bf821", "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": "zhengbanbufengbi/EasyPhotoshop", "max_issues_repo_path": "imgproc/color-convert.c", "max_line_length": 112, "max_stars_count": null, "max_stars_repo_head_hexsha": "de62bdd6fe0c7359453ce83fa6efa6592d9bf821", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zhengbanbufengbi/EasyPhotoshop", "max_stars_repo_path": "imgproc/color-convert.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2343, "size": 8312 }
/* * Copyright 2014 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* include the ATLAS headers */ extern "C" { #include <cblas.h> } /* choose precision to train and classify. Only float and double are * currently suppored */ typedef float floatType_t; /* macro to convert 2d coords to 1d offset */ #define INDX(row,col,ld) (((col) * (ld)) + (row)) /* macros for max/min to combine with argmin */ #define MYMAX(val,array,i,index) \ if( array[i] > val ) \ { \ val = array[i]; \ index = i; \ } \ #define MYMIN(val,array,i,index) \ if( array[i] < val ) \ { \ val = array[i]; \ index = i; \ } \ /* macro to clip values from min to max */ #define CLIP(val,min,max) \ if( (val) < (min) ) val = (min); \ else if( (val) > (max) ) val = (max); /* hardcoded constants for training and test set size and feature * vector size */ #define FEATURE_VECTOR_SIZE (1899) #define TRAINING_SET_SIZE (4000) #define TEST_SET_SIZE (1000) /* CUDA debugging */ #ifdef DEBUG #define CUDA_CALL(F) if( (F) != cudaSuccess ) \ {printf("Error %s at %s:%d\n", cudaGetErrorString(cudaGetLastError()), \ __FILE__,__LINE__); exit(-1);} #define CUDA_CHECK() if( (cudaPeekAtLastError()) != cudaSuccess ) \ {printf("Error %s at %s:%d\n", cudaGetErrorString(cudaGetLastError()), \ __FILE__,__LINE__-1); exit(-1);} #else #define CUDA_CALL(F) (F) #define CUDA_CHECK() #endif /* function defs */ void readMatrixFromFile( char *, int *, const int, const int ); void calculateBI( floatType_t const *, floatType_t const *, floatType_t const *, int , floatType_t *, floatType_t *, int *, int *, floatType_t const ); void svmTrain( floatType_t const *, floatType_t const *, floatType_t const, const int, const int, const floatType_t, floatType_t * ); void svmPredict( floatType_t const *, floatType_t const *, int const, int const, int * );
{ "alphanum_fraction": 0.6381889764, "avg_line_length": 26.4583333333, "ext": "h", "hexsha": "10e3a3036bcfb289c80a8a0db91f2de2458ddafa", "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": "6846c1d24b3725824696d0aaf75908b67422ea2f", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ardila/gpu_workshop", "max_forks_repo_path": "exercises/cuda/svm_challenge/original/headers.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "6846c1d24b3725824696d0aaf75908b67422ea2f", "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": "ardila/gpu_workshop", "max_issues_repo_path": "exercises/cuda/svm_challenge/original/headers.h", "max_line_length": 76, "max_stars_count": null, "max_stars_repo_head_hexsha": "6846c1d24b3725824696d0aaf75908b67422ea2f", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ardila/gpu_workshop", "max_stars_repo_path": "exercises/cuda/svm_challenge/original/headers.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 642, "size": 2540 }
/* cheb/init.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * Copyright (C) 2009 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_chebyshev.h> /*-*-*-*-*-*-*-*-*-*-*-* Allocators *-*-*-*-*-*-*-*-*-*-*-*/ gsl_cheb_series * gsl_cheb_alloc(const size_t order) { gsl_cheb_series * cs = (gsl_cheb_series *) malloc(sizeof(gsl_cheb_series)); if(cs == 0) { GSL_ERROR_VAL("failed to allocate gsl_cheb_series struct", GSL_ENOMEM, 0); } cs->order = order; cs->order_sp = order; cs->c = (double *) malloc((order+1) * sizeof(double)); if(cs->c == 0) { GSL_ERROR_VAL("failed to allocate cheb coefficients", GSL_ENOMEM, 0); } cs->f = (double *) malloc((order+1) * sizeof(double)); if(cs->f == 0) { GSL_ERROR_VAL("failed to allocate cheb function space", GSL_ENOMEM, 0); } return cs; } void gsl_cheb_free(gsl_cheb_series * cs) { RETURN_IF_NULL (cs); free(cs->f); free(cs->c); free(cs); } /*-*-*-*-*-*-*-*-*-*-*-* Initializer *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_cheb_init(gsl_cheb_series * cs, const gsl_function *func, const double a, const double b) { size_t k, j; if(a >= b) { GSL_ERROR_VAL("null function interval [a,b]", GSL_EDOM, 0); } cs->a = a; cs->b = b; /* cs->err = 0.0; */ { double bma = 0.5 * (cs->b - cs->a); double bpa = 0.5 * (cs->b + cs->a); double fac = 2.0/(cs->order +1.0); for(k = 0; k<=cs->order; k++) { double y = cos(M_PI * (k+0.5)/(cs->order+1)); cs->f[k] = GSL_FN_EVAL(func, (y*bma + bpa)); } for(j = 0; j<=cs->order; j++) { double sum = 0.0; for(k = 0; k<=cs->order; k++) sum += cs->f[k]*cos(M_PI * j*(k+0.5)/(cs->order+1)); cs->c[j] = fac * sum; } } return GSL_SUCCESS; } size_t gsl_cheb_order (const gsl_cheb_series * cs) { return cs->order; } size_t gsl_cheb_size (const gsl_cheb_series * cs) { return (cs->order + 1); } double * gsl_cheb_coeffs (const gsl_cheb_series * cs) { return cs->c; }
{ "alphanum_fraction": 0.6089266738, "avg_line_length": 23.9237288136, "ext": "c", "hexsha": "a923377d5dc5e1af96da0eadf46937586feb11be", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/cheb/init.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/cheb/init.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/cheb/init.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": 914, "size": 2823 }
#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_covariance(MCMC_info *MCMC, char *filename) { FILE * fp; double *V; int n_P, i_P, j_P; if(MCMC->V == NULL) SID_log("Initializing the covariance matrix from file {%s}...", SID_LOG_OPEN, filename); else SID_log("Updating the covariance matrix from file {%s}...", SID_LOG_OPEN, filename); fp = fopen(filename, "r"); SID_fread_verify(&n_P, sizeof(int), 1, fp); V = (double *)SID_malloc(sizeof(double) * n_P * n_P); SID_fread_verify(V, sizeof(double), n_P * n_P, fp); fclose(fp); set_MCMC_covariance(MCMC, V); SID_free(SID_FARG V); SID_log("Done.", SID_LOG_CLOSE); }
{ "alphanum_fraction": 0.6517241379, "avg_line_length": 30, "ext": "c", "hexsha": "ceb2b267b7af521c6d0636752a4281c64a9ce92a", "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_covariance.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_covariance.c", "max_line_length": 96, "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_covariance.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": 268, "size": 870 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #define COMPEARTH_PRIVATE_GEM3 1 #include "compearth.h" #ifdef DEBUG #ifdef COMPEARTH_USE_MKL #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreserved-id-macro" #pragma clang diagnostic ignored "-Wstrict-prototypes" #endif #include <mkl_cblas.h> #ifdef __clang__ #pragma clang diagnostic pop #endif #else #include <cblas.h> #endif #endif /*! * @brief Compute a rotation matrix given an axis and angle * * @param[in] n Number of matrices to generate. * @param[in] v Rotation axis. This is an array of dimension [3 x n] * with leading dimension 3. * @param[in] xi Rotation angles (degrees). This is an array of * dimension [n]. * * @param[in] U Rotation matrices. This is an array of dimension * [3 x 3 x n] where each leading [3 x 3] matrix is * in column major format. * * @result 0 indicates success. * * @date 2016 - Ben Baker translated Carl Tape's rotmat_gen.m to C * * @copyright MIT * */ int compearth_eulerUtil_rotmatGen(const int n, const double *__restrict__ v, const double *__restrict__ xi, double *__restrict__ U) { double R1[9], R2[9], R3[9], R4[9], R5[9], R54[9], R543[9], R5432[9]; double ele, nvph_deg, nvth_deg, rho, vph, vth, vph_deg, vth_deg; int i, ierr; const double pi180i = 180.0/M_PI; ierr = 0; for (i=0; i<n; i++) { compearth_matlab_cart2sph(1, &v[3*i+0], &v[3*i+1], &v[3*i+2], &vph, &ele, &rho); vth = M_PI_2 - ele; vth_deg = vth*pi180i; vph_deg = vph*pi180i; nvph_deg =-vph_deg; nvth_deg =-vth_deg; ierr = ierr + compearth_eulerUtil_rotmat(1, &nvph_deg, 3, R1); ierr = ierr + compearth_eulerUtil_rotmat(1, &nvth_deg, 2, R2); ierr = ierr + compearth_eulerUtil_rotmat(1, &xi[i], 3, R3); ierr = ierr + compearth_eulerUtil_rotmat(1, &vth_deg, 2, R4); ierr = ierr + compearth_eulerUtil_rotmat(1, &vph_deg, 3, R5); if (ierr != 0) { fprintf(stderr, "%s: Error computing rotation matrices %d\n", __func__, i); } gemm3_colMajorNoTransNoTrans(R5, R4, R54); gemm3_colMajorNoTransNoTrans(R54, R3, R543); gemm3_colMajorNoTransNoTrans(R543, R2, R5432); gemm3_colMajorNoTransNoTrans(R5432, R1, &U[9*i]); #ifdef DEBUG double U9[9]; cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3, 1.0, R5, 3, R4, 3, 0.0, R54, 3); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3, 1.0, R54, 3, R3, 3, 0.0, R543, 3); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3, 1.0, R543, 3, R2, 3, 0.0, R5432, 3); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3, 1.0, R5432, 3, R1, 3, 0.0, U9, 3); for (int k=0; k<9; k++) { if (fabs(U9[k] - U[9*i+k]) > 1.e-14) { printf("Computation failed: %f %f\n", U9[k], U[9*i+k]); ierr = ierr + 1; } } #endif } return ierr; }
{ "alphanum_fraction": 0.5607005046, "avg_line_length": 34.3775510204, "ext": "c", "hexsha": "99ec0fea8173d14a381d05bc5691706756d9b5f7", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2022-02-28T13:42:40.000Z", "max_forks_repo_forks_event_min_datetime": "2021-07-08T00:13:50.000Z", "max_forks_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "carltape/mtbeach", "max_forks_repo_path": "c_src/eulerUtil_rotmatGen.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_issues_repo_issues_event_max_datetime": "2017-11-02T17:30:53.000Z", "max_issues_repo_issues_event_min_datetime": "2017-11-02T17:30:53.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "carltape/mtbeach", "max_issues_repo_path": "c_src/eulerUtil_rotmatGen.c", "max_line_length": 73, "max_stars_count": 9, "max_stars_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "OUCyf/mtbeach", "max_stars_repo_path": "c_src/eulerUtil_rotmatGen.c", "max_stars_repo_stars_event_max_datetime": "2022-02-28T23:55:36.000Z", "max_stars_repo_stars_event_min_datetime": "2021-03-13T01:18:12.000Z", "num_tokens": 1111, "size": 3369 }
#pragma once #include "CesiumGltf/MetadataArrayView.h" #include "CesiumGltf/PropertyType.h" #include "CesiumGltf/PropertyTypeTraits.h" #include <gsl/span> #include <cassert> #include <cstddef> #include <cstdint> #include <string_view> #include <type_traits> namespace CesiumGltf { /** * @brief Indicates the status of a property view. * * The {@link MetadataPropertyView} constructor always completes successfully. However, * it may not always reflect the actual content of the {@link FeatureTableProperty}, but * instead indicate that its {@link MetadataPropertyView::size} is 0. This enumeration * provides the reason. */ enum class MetadataPropertyViewStatus { /** * @brief This property view is valid and ready to use. */ Valid, /** * @brief This property view does not exist in the FeatureTable. */ InvalidPropertyNotExist, /** * @brief This property view does not have a correct type with what is * specified in {@link ClassProperty::type}. */ InvalidTypeMismatch, /** * @brief This property view does not have a valid value buffer view index. */ InvalidValueBufferViewIndex, /** * @brief This array property view does not have a valid array offset buffer * view index. */ InvalidArrayOffsetBufferViewIndex, /** * @brief This string property view does not have a valid string offset buffer * view index. */ InvalidStringOffsetBufferViewIndex, /** * @brief This property view has a valid value buffer view index, but buffer * view specifies an invalid buffer index */ InvalidValueBufferIndex, /** * @brief This property view has a valid array string buffer view index, but * buffer view specifies an invalid buffer index */ InvalidArrayOffsetBufferIndex, /** * @brief This property view has a valid string offset buffer view index, but * buffer view specifies an invalid buffer index */ InvalidStringOffsetBufferIndex, /** * @brief This property view has buffer view's offset not aligned by 8 bytes */ InvalidBufferViewNotAligned8Bytes, /** * @brief This property view has an out-of-bound buffer view */ InvalidBufferViewOutOfBound, /** * @brief This property view has an invalid buffer view's length which is not * a multiple of the size of its type or offset type */ InvalidBufferViewSizeNotDivisibleByTypeSize, /** * @brief This property view has an invalid buffer view's length which cannot * fit all the instances of the feature table */ InvalidBufferViewSizeNotFitInstanceCount, /** * @brief This array property view has both component count and offset buffer * view */ InvalidArrayComponentCountAndOffsetBufferCoexist, /** * @brief This array property view doesn't have either component count or * offset buffer view */ InvalidArrayComponentCountOrOffsetBufferNotExist, /** * @brief This property view have an unknown offset type */ InvalidOffsetType, /** * @brief This property view has offset values not sorted ascendingly */ InvalidOffsetValuesNotSortedAscending, /** * @brief This property view has an offset point to an out of bound value */ InvalidOffsetValuePointsToOutOfBoundBuffer }; /** * @brief A view on the data of the FeatureTableProperty * * It provides utility to retrieve the actual data stored in the * {@link FeatureTableProperty::bufferView} like an array of elements. * Data of each instance can be accessed through the {@link get(int64_t instance)} method * * @param ElementType must be uin8_t, int8_t, uint16_t, int16_t, * uint32_t, int32_t, uint64_t, int64_t, float, double, bool, std::string_view, * and MetadataArrayView<T> with T must be one of the types mentioned above */ template <typename ElementType> class MetadataPropertyView { public: /** * @brief Constructs a new instance viewing a non-existent property. */ MetadataPropertyView() : _status{MetadataPropertyViewStatus::InvalidPropertyNotExist}, _valueBuffer{}, _arrayOffsetBuffer{}, _stringOffsetBuffer{}, _offsetType{}, _offsetSize{}, _componentCount{}, _instanceCount{}, _normalized{} {} /** * @brief Construct a new instance pointing to the data specified by * FeatureTableProperty * @param valueBuffer The raw buffer specified by {@link FeatureTableProperty::bufferView} * @param arrayOffsetBuffer The raw buffer specified by {@link FeatureTableProperty::arrayOffsetBufferView} * @param stringOffsetBuffer The raw buffer specified by {@link FeatureTableProperty::stringOffsetBufferView} * @param offsetType The offset type of the arrayOffsetBuffer and stringOffsetBuffer that is specified by {@link FeatureTableProperty::offsetType} * @param componentCount The number of elements for fixed array value which is specified by {@link FeatureTableProperty::componentCount} * @param instanceCount The number of instances specified by {@link FeatureTable::count} * @param normalized Whether this property has a normalized integer type. */ MetadataPropertyView( MetadataPropertyViewStatus status, gsl::span<const std::byte> valueBuffer, gsl::span<const std::byte> arrayOffsetBuffer, gsl::span<const std::byte> stringOffsetBuffer, PropertyType offsetType, int64_t componentCount, int64_t instanceCount, bool normalized) noexcept : _status{status}, _valueBuffer{valueBuffer}, _arrayOffsetBuffer{arrayOffsetBuffer}, _stringOffsetBuffer{stringOffsetBuffer}, _offsetType{offsetType}, _offsetSize{getOffsetSize(offsetType)}, _componentCount{componentCount}, _instanceCount{instanceCount}, _normalized{normalized} {} /** * @brief Gets the status of this property view. * * Indicates whether the view accurately reflects the property's data, or * whether an error occurred. */ MetadataPropertyViewStatus status() const noexcept { return _status; } /** * @brief Get the value of an instance of the FeatureTable. * @param instance The instance index * @return The value of the instance */ ElementType get(int64_t instance) const noexcept { assert( _status == MetadataPropertyViewStatus::Valid && "Check the status() first to make sure view is valid"); assert( size() > 0 && "Check the size() of the view to make sure it's not empty"); assert(instance >= 0 && "instance index must be positive"); if constexpr (IsMetadataNumeric<ElementType>::value) { return getNumeric(instance); } if constexpr (IsMetadataBoolean<ElementType>::value) { return getBoolean(instance); } if constexpr (IsMetadataString<ElementType>::value) { return getString(instance); } if constexpr (IsMetadataNumericArray<ElementType>::value) { return getNumericArray<typename MetadataArrayType<ElementType>::type>( instance); } if constexpr (IsMetadataBooleanArray<ElementType>::value) { return getBooleanArray(instance); } if constexpr (IsMetadataStringArray<ElementType>::value) { return getStringArray(instance); } } /** * @brief Get the number of instances in the FeatureTable * @return The number of instances in the FeatureTable */ int64_t size() const noexcept { return _instanceCount; } /** * @brief Get the component count of this property. Only applicable when the * property is an array type. * * @return The component count of this property. */ int64_t getComponentCount() const noexcept { return _componentCount; } /** * @brief Whether this property has a normalized integer type. * * @return Whether this property has a normalized integer type. */ bool isNormalized() const noexcept { return _normalized; } private: ElementType getNumeric(int64_t instance) const noexcept { return reinterpret_cast<const ElementType*>(_valueBuffer.data())[instance]; } bool getBoolean(int64_t instance) const noexcept { const int64_t byteIndex = instance / 8; const int64_t bitIndex = instance % 8; const int bitValue = static_cast<int>(_valueBuffer[byteIndex] >> bitIndex) & 1; return bitValue == 1; } std::string_view getString(int64_t instance) const noexcept { const size_t currentOffset = getOffsetFromOffsetBuffer(instance, _stringOffsetBuffer, _offsetType); const size_t nextOffset = getOffsetFromOffsetBuffer( instance + 1, _stringOffsetBuffer, _offsetType); return std::string_view( reinterpret_cast<const char*>(_valueBuffer.data() + currentOffset), (nextOffset - currentOffset)); } template <typename T> MetadataArrayView<T> getNumericArray(int64_t instance) const noexcept { if (_componentCount > 0) { const gsl::span<const std::byte> vals( _valueBuffer.data() + instance * _componentCount * sizeof(T), _componentCount * sizeof(T)); return MetadataArrayView<T>{vals}; } const size_t currentOffset = getOffsetFromOffsetBuffer(instance, _arrayOffsetBuffer, _offsetType); const size_t nextOffset = getOffsetFromOffsetBuffer( instance + 1, _arrayOffsetBuffer, _offsetType); const gsl::span<const std::byte> vals( _valueBuffer.data() + currentOffset, (nextOffset - currentOffset)); return MetadataArrayView<T>{vals}; } MetadataArrayView<std::string_view> getStringArray(int64_t instance) const noexcept { if (_componentCount > 0) { const gsl::span<const std::byte> offsetVals( _stringOffsetBuffer.data() + instance * _componentCount * _offsetSize, (_componentCount + 1) * _offsetSize); return MetadataArrayView<std::string_view>( _valueBuffer, offsetVals, _offsetType, _componentCount); } const size_t currentOffset = getOffsetFromOffsetBuffer(instance, _arrayOffsetBuffer, _offsetType); const size_t nextOffset = getOffsetFromOffsetBuffer( instance + 1, _arrayOffsetBuffer, _offsetType); const gsl::span<const std::byte> offsetVals( _stringOffsetBuffer.data() + currentOffset, (nextOffset - currentOffset + _offsetSize)); return MetadataArrayView<std::string_view>( _valueBuffer, offsetVals, _offsetType, (nextOffset - currentOffset) / _offsetSize); } MetadataArrayView<bool> getBooleanArray(int64_t instance) const noexcept { if (_componentCount > 0) { const size_t offsetBits = _componentCount * instance; const size_t nextOffsetBits = _componentCount * (instance + 1); const gsl::span<const std::byte> buffer( _valueBuffer.data() + offsetBits / 8, (nextOffsetBits / 8 - offsetBits / 8 + 1)); return MetadataArrayView<bool>(buffer, offsetBits % 8, _componentCount); } const size_t currentOffset = getOffsetFromOffsetBuffer(instance, _arrayOffsetBuffer, _offsetType); const size_t nextOffset = getOffsetFromOffsetBuffer( instance + 1, _arrayOffsetBuffer, _offsetType); const size_t totalBits = nextOffset - currentOffset; const gsl::span<const std::byte> buffer( _valueBuffer.data() + currentOffset / 8, (nextOffset / 8 - currentOffset / 8 + 1)); return MetadataArrayView<bool>(buffer, currentOffset % 8, totalBits); } static int64_t getOffsetSize(PropertyType offsetType) noexcept { switch (offsetType) { case CesiumGltf::PropertyType::Uint8: return sizeof(uint8_t); case CesiumGltf::PropertyType::Uint16: return sizeof(uint16_t); case CesiumGltf::PropertyType::Uint32: return sizeof(uint32_t); case CesiumGltf::PropertyType::Uint64: return sizeof(uint64_t); default: return 0; } } static size_t getOffsetFromOffsetBuffer( size_t instance, const gsl::span<const std::byte>& offsetBuffer, PropertyType offsetType) noexcept { switch (offsetType) { case PropertyType::Uint8: { assert(instance < offsetBuffer.size() / sizeof(uint8_t)); const uint8_t offset = *reinterpret_cast<const uint8_t*>( offsetBuffer.data() + instance * sizeof(uint8_t)); return static_cast<size_t>(offset); } case PropertyType::Uint16: { assert(instance < offsetBuffer.size() / sizeof(uint16_t)); const uint16_t offset = *reinterpret_cast<const uint16_t*>( offsetBuffer.data() + instance * sizeof(uint16_t)); return static_cast<size_t>(offset); } case PropertyType::Uint32: { assert(instance < offsetBuffer.size() / sizeof(uint32_t)); const uint32_t offset = *reinterpret_cast<const uint32_t*>( offsetBuffer.data() + instance * sizeof(uint32_t)); return static_cast<size_t>(offset); } case PropertyType::Uint64: { assert(instance < offsetBuffer.size() / sizeof(uint64_t)); const uint64_t offset = *reinterpret_cast<const uint64_t*>( offsetBuffer.data() + instance * sizeof(uint64_t)); return static_cast<size_t>(offset); } default: assert(false && "Offset type has unknown type"); return 0; } } MetadataPropertyViewStatus _status; gsl::span<const std::byte> _valueBuffer; gsl::span<const std::byte> _arrayOffsetBuffer; gsl::span<const std::byte> _stringOffsetBuffer; PropertyType _offsetType; int64_t _offsetSize; int64_t _componentCount; int64_t _instanceCount; bool _normalized; }; } // namespace CesiumGltf
{ "alphanum_fraction": 0.6976931527, "avg_line_length": 33.1432038835, "ext": "h", "hexsha": "6b535d27db94d1e61314c6cbfacbc9c3612d2d69", "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": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "yieryi/cesium-native", "max_forks_repo_path": "CesiumGltf/include/CesiumGltf/MetadataPropertyView.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "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": "yieryi/cesium-native", "max_issues_repo_path": "CesiumGltf/include/CesiumGltf/MetadataPropertyView.h", "max_line_length": 148, "max_stars_count": null, "max_stars_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "yieryi/cesium-native", "max_stars_repo_path": "CesiumGltf/include/CesiumGltf/MetadataPropertyView.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3171, "size": 13655 }
/* Sound display/edit/etc * * originally intended as a re-implementation of my much-missed dpysnd -- the Foonly/SAIL/E/Mus10/Grnlib sound editor from ca 1983. */ #include "snd.h" snd_state *ss = NULL; static bool ignore_mus_error(int type, char *msg) { XEN result = XEN_FALSE; if (XEN_HOOKED(ss->mus_error_hook)) result = run_or_hook(ss->mus_error_hook, XEN_LIST_2(C_TO_XEN_INT(type), C_TO_XEN_STRING(msg)), S_mus_error_hook); return(XEN_NOT_FALSE_P(result)); } #if HAVE_SETJMP_H void top_level_catch(int ignore); #endif void mus_error_to_snd(int type, char *msg) { if (!ss) { fprintf(stderr, "%s", msg); return; } if (!(ignore_mus_error(type, msg))) { #if HAVE_EXTENSION_LANGUAGE if (msg == NULL) XEN_ERROR(XEN_ERROR_TYPE("mus-error"), XEN_LIST_1(C_TO_XEN_STRING((char *)mus_error_type_to_string(type)))); else XEN_ERROR(XEN_ERROR_TYPE("mus-error"), XEN_LIST_1(C_TO_XEN_STRING(msg))); #endif snd_error("%s: %s", mus_error_type_to_string(type), msg); #if HAVE_SETJMP_H ss->jump_ok = true; top_level_catch(1); /* sigh -- try to keep going */ #endif } } static void mus_print_to_snd(char *msg) { if (!ss) { fprintf(stderr, "%s", msg); return; } if (!(ignore_mus_error(MUS_NO_ERROR, msg))) if (msg) { int i, len; listener_append(";"); len = strlen(msg); for (i = 1; i < len - 1; i++) if ((msg[i] == '\n') && (msg[i + 1] == ' ')) msg[i + 1] = ';'; if (msg[0] == '\n') listener_append((char *)(msg + 1)); else listener_append(msg); if (msg[strlen(msg) - 1] != '\n') listener_append("\n"); } } static void initialize_load_path(void) { /* look for SND_PATH env var, add dirs to %load-path or load_path */ char *path; path = getenv("SND_PATH"); if (path) { /* colon-separated list of directory names, pushed on load-path in reverse order (hopefully = search order) */ int i, len, dirs = 1, curdir = 0, start = 0; char **dirnames; len = strlen(path); for (i = 0; i < len; i++) if (path[i] == ':') dirs++; dirnames = (char **)calloc(dirs, sizeof(char *)); for (i = 0; i < len; i++) { if ((path[i] == ':') || (i == len - 1)) { if (i > start) { int j, lim; char *tmp; if (i == (len - 1)) lim = i + 1; else lim = i; tmp = (char *)calloc(lim - start + 1, sizeof(char)); for (j = start; j < lim; j++) tmp[j - start] = path[j]; dirnames[curdir++] = mus_expand_filename(tmp); start = i + 1; free(tmp); } } } for (i = curdir - 1; i >= 0; i--) { XEN_ADD_TO_LOAD_PATH(dirnames[i]); free(dirnames[i]); } free(dirnames); } } void snd_set_global_defaults(bool need_cleanup) { if (need_cleanup) { if (ss->HTML_Program) {free(ss->HTML_Program); ss->HTML_Program = NULL;} if (ss->HTML_Dir) {free(ss->HTML_Dir); ss->HTML_Dir = NULL;} if (ss->Temp_Dir) {free(ss->Temp_Dir); ss->Temp_Dir = NULL;} if (ss->Save_Dir) {free(ss->Save_Dir); ss->Save_Dir = NULL;} if (ss->Ladspa_Dir) {free(ss->Ladspa_Dir); ss->Ladspa_Dir = NULL;} if (ss->Save_State_File) {free(ss->Save_State_File); ss->Save_State_File = NULL;} if (ss->Eps_File) {free(ss->Eps_File); ss->Eps_File = NULL;} if (ss->Listener_Prompt) {free(ss->Listener_Prompt); ss->Listener_Prompt = NULL;} if (ss->Open_File_Dialog_Directory) {free(ss->Open_File_Dialog_Directory); ss->Open_File_Dialog_Directory = NULL;} /* not sure about the next two... */ if ((cursor_style(ss) == CURSOR_PROC) && (XEN_PROCEDURE_P(ss->cursor_proc))) snd_unprotect_at(ss->cursor_proc_loc); if ((zoom_focus_style(ss) == ZOOM_FOCUS_PROC) && (XEN_PROCEDURE_P(ss->zoom_focus_proc))) snd_unprotect_at(ss->zoom_focus_proc_loc); } ss->Transform_Size = DEFAULT_TRANSFORM_SIZE; ss->Fft_Window = DEFAULT_FFT_WINDOW; ss->Fft_Window_Alpha = DEFAULT_FFT_WINDOW_ALPHA; ss->Fft_Window_Beta = DEFAULT_FFT_WINDOW_BETA; ss->Transform_Graph_Type = DEFAULT_TRANSFORM_GRAPH_TYPE; ss->Sinc_Width = DEFAULT_SINC_WIDTH; ss->Zero_Pad = DEFAULT_ZERO_PAD; ss->Wavelet_Type = DEFAULT_WAVELET_TYPE; ss->Transform_Type = DEFAULT_TRANSFORM_TYPE; ss->Transform_Normalization = DEFAULT_TRANSFORM_NORMALIZATION; ss->Show_Transform_Peaks = DEFAULT_SHOW_TRANSFORM_PEAKS; ss->Show_Sonogram_Cursor = DEFAULT_SHOW_SONOGRAM_CURSOR; ss->Fft_Log_Magnitude = DEFAULT_FFT_LOG_MAGNITUDE; ss->Fft_Log_Frequency = DEFAULT_FFT_LOG_FREQUENCY; ss->Fft_With_Phases = DEFAULT_FFT_WITH_PHASES; ss->Max_Transform_Peaks = DEFAULT_MAX_TRANSFORM_PEAKS; ss->Log_Freq_Start = DEFAULT_LOG_FREQ_START; ss->Min_dB = DEFAULT_MIN_DB; ss->lin_dB = pow(10.0, DEFAULT_MIN_DB * 0.05); ss->Show_Selection_Transform = DEFAULT_SHOW_SELECTION_TRANSFORM; ss->Default_Output_Chans = DEFAULT_OUTPUT_CHANS; ss->Default_Output_Srate = DEFAULT_OUTPUT_SRATE; ss->Default_Output_Header_Type = DEFAULT_OUTPUT_HEADER_TYPE; ss->Default_Output_Data_Format = DEFAULT_OUTPUT_DATA_FORMAT; ss->Audio_Input_Device = DEFAULT_AUDIO_INPUT_DEVICE; ss->Audio_Output_Device = DEFAULT_AUDIO_OUTPUT_DEVICE; ss->Dac_Size = DEFAULT_DAC_SIZE; ss->Dac_Combines_Channels = DEFAULT_DAC_COMBINES_CHANNELS; ss->Auto_Resize = DEFAULT_AUTO_RESIZE; ss->Auto_Update = DEFAULT_AUTO_UPDATE; ss->Auto_Update_Interval = DEFAULT_AUTO_UPDATE_INTERVAL; ss->Ask_Before_Overwrite = DEFAULT_ASK_BEFORE_OVERWRITE; ss->With_Toolbar = DEFAULT_WITH_TOOLBAR; ss->With_Tooltips = DEFAULT_WITH_TOOLTIPS; ss->Remember_Sound_State = DEFAULT_REMEMBER_SOUND_STATE; ss->Ask_About_Unsaved_Edits = DEFAULT_ASK_ABOUT_UNSAVED_EDITS; ss->Save_As_Dialog_Src = DEFAULT_SAVE_AS_DIALOG_SRC; ss->Save_As_Dialog_Auto_Comment = DEFAULT_SAVE_AS_DIALOG_AUTO_COMMENT; ss->Show_Full_Duration = DEFAULT_SHOW_FULL_DURATION; ss->Show_Full_Range = DEFAULT_SHOW_FULL_RANGE; ss->Initial_Beg = DEFAULT_INITIAL_BEG; ss->Initial_Dur = DEFAULT_INITIAL_DUR; ss->With_Background_Processes = DEFAULT_WITH_BACKGROUND_PROCESSES; ss->With_File_Monitor = DEFAULT_WITH_FILE_MONITOR; ss->Selection_Creates_Region = DEFAULT_SELECTION_CREATES_REGION; ss->Channel_Style = DEFAULT_CHANNEL_STYLE; ss->Sound_Style = DEFAULT_SOUND_STYLE; ss->Graphs_Horizontal = DEFAULT_GRAPHS_HORIZONTAL; ss->Graph_Style = DEFAULT_GRAPH_STYLE; ss->Region_Graph_Style = DEFAULT_GRAPH_STYLE; ss->Time_Graph_Type = DEFAULT_TIME_GRAPH_TYPE; ss->X_Axis_Style = DEFAULT_X_AXIS_STYLE; ss->Beats_Per_Minute = DEFAULT_BEATS_PER_MINUTE; ss->Beats_Per_Measure = DEFAULT_BEATS_PER_MEASURE; ss->With_Relative_Panes = DEFAULT_WITH_RELATIVE_PANES; ss->With_GL = DEFAULT_WITH_GL; ss->Dot_Size = DEFAULT_DOT_SIZE; ss->Grid_Density = DEFAULT_GRID_DENSITY; ss->Zoom_Focus_Style = DEFAULT_ZOOM_FOCUS_STYLE; ss->zoom_focus_proc = XEN_UNDEFINED; ss->zoom_focus_proc_loc = NOT_A_GC_LOC; ss->Max_Regions = DEFAULT_MAX_REGIONS; ss->Show_Y_Zero = DEFAULT_SHOW_Y_ZERO; ss->Show_Grid = DEFAULT_SHOW_GRID; ss->Show_Axes = DEFAULT_SHOW_AXES; ss->Show_Indices = DEFAULT_SHOW_INDICES; ss->Show_Backtrace = DEFAULT_SHOW_BACKTRACE; ss->With_Inset_Graph = DEFAULT_WITH_INSET_GRAPH; ss->With_Interrupts = DEFAULT_WITH_INTERRUPTS; ss->With_Menu_Icons = DEFAULT_WITH_MENU_ICONS; ss->With_Smpte_Label = DEFAULT_WITH_SMPTE_LABEL; ss->With_Pointer_Focus = DEFAULT_WITH_POINTER_FOCUS; ss->Play_Arrow_Size = DEFAULT_PLAY_ARROW_SIZE; ss->Sync_Style = DEFAULT_SYNC_STYLE; ss->Listener_Prompt = mus_strdup(DEFAULT_LISTENER_PROMPT); ss->listener_prompt_length = mus_strlen(ss->Listener_Prompt); ss->Minibuffer_History_Length = DEFAULT_MINIBUFFER_HISTORY_LENGTH; ss->Clipping = DEFAULT_CLIPPING; ss->Optimization = DEFAULT_OPTIMIZATION; ss->Print_Length = DEFAULT_PRINT_LENGTH; ss->View_Files_Sort = DEFAULT_VIEW_FILES_SORT; ss->Just_Sounds = DEFAULT_JUST_SOUNDS; ss->Open_File_Dialog_Directory = NULL; ss->HTML_Dir = mus_strdup(DEFAULT_HTML_DIR); ss->HTML_Program = mus_strdup(DEFAULT_HTML_PROGRAM); ss->Cursor_Size = DEFAULT_CURSOR_SIZE; ss->Cursor_Style = DEFAULT_CURSOR_STYLE; ss->Tracking_Cursor_Style = DEFAULT_TRACKING_CURSOR_STYLE; ss->With_Tracking_Cursor = DEFAULT_WITH_TRACKING_CURSOR; ss->cursor_proc = XEN_UNDEFINED; ss->cursor_proc_loc = NOT_A_GC_LOC; ss->Verbose_Cursor = DEFAULT_VERBOSE_CURSOR; ss->Cursor_Update_Interval = DEFAULT_CURSOR_UPDATE_INTERVAL; ss->Cursor_Location_Offset = DEFAULT_CURSOR_LOCATION_OFFSET; ss->Show_Mix_Waveforms = DEFAULT_SHOW_MIX_WAVEFORMS; ss->Mix_Waveform_Height = DEFAULT_MIX_WAVEFORM_HEIGHT; ss->Mix_Tag_Width = DEFAULT_MIX_TAG_WIDTH; ss->Mix_Tag_Height = DEFAULT_MIX_TAG_HEIGHT; ss->With_Mix_Tags = DEFAULT_WITH_MIX_TAGS; ss->Mark_Tag_Width = DEFAULT_MARK_TAG_WIDTH; ss->Mark_Tag_Height = DEFAULT_MARK_TAG_HEIGHT; ss->Show_Marks = DEFAULT_SHOW_MARKS; ss->Color_Map = DEFAULT_COLOR_MAP; ss->Color_Map_Size = DEFAULT_COLOR_MAP_SIZE; ss->Color_Cutoff = DEFAULT_COLOR_CUTOFF; ss->Color_Scale = DEFAULT_COLOR_SCALE; ss->Color_Inverted = DEFAULT_COLOR_INVERTED; ss->Color_Map = DEFAULT_COLOR_MAP; ss->Wavo_Hop = DEFAULT_WAVO_HOP; ss->Wavo_Trace = DEFAULT_WAVO_TRACE; ss->Spectro_Hop = DEFAULT_SPECTRO_HOP; ss->Spectro_X_Scale = DEFAULT_SPECTRO_X_SCALE; ss->Spectro_Y_Scale = DEFAULT_SPECTRO_Y_SCALE; ss->Spectro_Z_Scale = DEFAULT_SPECTRO_Z_SCALE; ss->Spectro_Z_Angle = DEFAULT_SPECTRO_Z_ANGLE; ss->Spectro_X_Angle = DEFAULT_SPECTRO_X_ANGLE; ss->Spectro_Y_Angle = DEFAULT_SPECTRO_Y_ANGLE; ss->Spectrum_End = DEFAULT_SPECTRUM_END; ss->Spectrum_Start = DEFAULT_SPECTRUM_START; ss->Enved_Base = DEFAULT_ENVED_BASE; ss->Enved_Power = DEFAULT_ENVED_POWER; ss->Enved_Wave_p = DEFAULT_ENVED_WAVE_P; ss->Enved_Style = DEFAULT_ENVED_STYLE; ss->Enved_Target = DEFAULT_ENVED_TARGET; ss->Enved_Filter_Order = DEFAULT_ENVED_FILTER_ORDER; ss->Eps_Bottom_Margin = DEFAULT_EPS_BOTTOM_MARGIN; ss->Eps_Left_Margin = DEFAULT_EPS_LEFT_MARGIN; ss->Eps_Size = DEFAULT_EPS_SIZE; ss->Expand_Control_Min = DEFAULT_EXPAND_CONTROL_MIN; ss->Expand_Control_Max = DEFAULT_EXPAND_CONTROL_MAX; ss->Amp_Control_Min = DEFAULT_AMP_CONTROL_MIN; ss->Amp_Control_Max = DEFAULT_AMP_CONTROL_MAX; ss->Speed_Control_Min = DEFAULT_SPEED_CONTROL_MIN; ss->Speed_Control_Max = DEFAULT_SPEED_CONTROL_MAX; ss->Contrast_Control_Min = DEFAULT_CONTRAST_CONTROL_MIN; ss->Contrast_Control_Max = DEFAULT_CONTRAST_CONTROL_MAX; ss->Contrast_Control_Amp = DEFAULT_CONTRAST_CONTROL_AMP; ss->Expand_Control_Length = DEFAULT_EXPAND_CONTROL_LENGTH; ss->Expand_Control_Ramp = DEFAULT_EXPAND_CONTROL_RAMP; ss->Expand_Control_Hop = DEFAULT_EXPAND_CONTROL_HOP; ss->Expand_Control_Jitter = DEFAULT_EXPAND_CONTROL_JITTER; ss->Reverb_Control_Feedback = DEFAULT_REVERB_CONTROL_FEEDBACK; ss->Reverb_Control_Lowpass = DEFAULT_REVERB_CONTROL_LOWPASS; ss->Reverb_Control_Scale_Min = DEFAULT_REVERB_CONTROL_SCALE_MIN; ss->Reverb_Control_Scale_Max = DEFAULT_REVERB_CONTROL_SCALE_MAX; ss->Reverb_Control_Decay = DEFAULT_REVERB_CONTROL_DECAY; ss->Speed_Control_Tones = DEFAULT_SPEED_CONTROL_TONES; ss->Speed_Control_Style = DEFAULT_SPEED_CONTROL_STYLE; ss->Reverb_Control_Length_Min = DEFAULT_REVERB_CONTROL_LENGTH_MIN; ss->Reverb_Control_Length_Max = DEFAULT_REVERB_CONTROL_LENGTH_MAX; ss->Filter_Control_Order = DEFAULT_FILTER_CONTROL_ORDER; ss->Filter_Control_In_Db = DEFAULT_FILTER_CONTROL_IN_DB; ss->Filter_Control_In_Hz = DEFAULT_FILTER_CONTROL_IN_HZ; ss->Show_Controls = DEFAULT_SHOW_CONTROLS; if (MUS_DEFAULT_TEMP_DIR != (char *)NULL) ss->Temp_Dir = mus_strdup(MUS_DEFAULT_TEMP_DIR); else ss->Temp_Dir = NULL; if (MUS_DEFAULT_SAVE_DIR != (char *)NULL) ss->Save_Dir = mus_strdup(MUS_DEFAULT_SAVE_DIR); else ss->Save_Dir = NULL; if (DEFAULT_LADSPA_DIR != (char *)NULL) ss->Ladspa_Dir = mus_strdup(DEFAULT_LADSPA_DIR); else ss->Ladspa_Dir = NULL; if (DEFAULT_SAVE_STATE_FILE != (char *)NULL) ss->Save_State_File = mus_strdup(DEFAULT_SAVE_STATE_FILE); else ss->Save_State_File = NULL; if (DEFAULT_PEAK_ENV_DIR != (char *)NULL) ss->Peak_Env_Dir = mus_strdup(DEFAULT_PEAK_ENV_DIR); else ss->Peak_Env_Dir = NULL; if (DEFAULT_EPS_FILE != (char *)NULL) ss->Eps_File = mus_strdup(DEFAULT_EPS_FILE); else ss->Eps_File = NULL; } #if HAVE_SETJMP_H && HAVE_SCHEME static void jump_to_top_level(void) { top_level_catch(1); } #endif #if HAVE_GSL #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_errno.h> /* default gsl error handler apparently aborts main program! */ static void snd_gsl_error(const char *reason, const char *file, int line, int gsl_errno) { XEN_ERROR(XEN_ERROR_TYPE("gsl-error"), XEN_LIST_6(C_TO_XEN_STRING("GSL: ~A, ~A in ~A line ~A, gsl err: ~A"), C_TO_XEN_STRING(gsl_strerror(gsl_errno)), C_TO_XEN_STRING(reason), C_TO_XEN_STRING(file), C_TO_XEN_INT(line), C_TO_XEN_INT(gsl_errno))); } #endif #if SND_AS_WIDGET snd_state *snd_main(int argc, char **argv) #else int main(int argc, char **argv) #endif { int i; #if HAVE_GSL /* if HAVE_GSL and the environment variable GSL_IEEE_MODE exists, use it */ /* GSL_IEEE_MODE=double-precision,mask-underflow,mask-denormalized */ if (getenv("GSL_IEEE_MODE") != NULL) gsl_ieee_env_setup(); gsl_set_error_handler(snd_gsl_error); #endif ss = (snd_state *)calloc(1, sizeof(snd_state)); /* not calloc! */ ss->fam_ok = false; ss->startup_errors = NULL; #if HAVE_GTK_3 g_type_init(); #endif mus_sound_initialize(); /* has to precede version check (mus_audio_moniker needs to be setup in Alsa/Oss) */ xen_initialize(); #if HAVE_SCHEME && HAVE_SETJMP_H s7_set_error_exiter(s7, jump_to_top_level); #endif for (i = 1; i < argc; i++) { if (strcmp(argv[i], "--version") == 0) { fprintf(stdout, "%s", version_info()); snd_exit(0); } else { if (strcmp(argv[i], "--help") == 0) { fprintf(stdout, "%s", "Snd is a sound editor; see http://ccrma.stanford.edu/software/snd/.\n"); fprintf(stdout, "%s", version_info()); snd_exit(0); } } } initialize_format_lists(); snd_set_global_defaults(false); #if MUS_DEBUGGING ss->Trap_Segfault = false; #else ss->Trap_Segfault = DEFAULT_TRAP_SEGFAULT; #endif ss->jump_ok = false; allocate_regions(max_regions(ss)); ss->init_window_x = DEFAULT_INIT_WINDOW_X; ss->init_window_y = DEFAULT_INIT_WINDOW_Y; ss->init_window_width = DEFAULT_INIT_WINDOW_WIDTH; ss->init_window_height = DEFAULT_INIT_WINDOW_HEIGHT; ss->click_time = 100; init_sound_file_extensions(); ss->max_sounds = 4; /* expands to accommodate any number of files */ ss->sound_sync_max = 0; ss->stopped_explicitly = false; /* C-g sets this flag so that we can interrupt various loops */ ss->checking_explicitly = false; ss->selection_play_stop = false; ss->reloading_updated_file = 0; ss->selected_sound = NO_SELECTION; ss->sounds = (snd_info **)calloc(ss->max_sounds, sizeof(snd_info *)); ss->print_choice = PRINT_SND; ss->graph_hook_active = false; ss->lisp_graph_hook_active = false; ss->exiting = false; ss->deferred_regions = 0; ss->fam_connection = NULL; ss->snd_error_data = NULL; ss->snd_error_handler = NULL; ss->snd_warning_data = NULL; ss->snd_warning_handler = NULL; ss->xen_error_data = NULL; ss->xen_error_handler = NULL; ss->update_sound_channel_style = NOT_A_CHANNEL_STYLE; #if HAVE_GL && WITH_GL2PS ss->gl_printing = false; #endif g_xen_initialize(); ss->search_proc = XEN_UNDEFINED; ss->search_expr = NULL; ss->search_tree = NULL; mus_error_set_handler(mus_error_to_snd); mus_print_set_handler(mus_print_to_snd); initialize_load_path(); /* merge SND_PATH entries into the load-path */ #ifdef SND_AS_WIDGET return(ss); #else snd_doit(argc, argv); return(0); #endif } void g_init_base(void) { #define H_mus_error_hook S_mus_error_hook " (error-type error-message): called upon mus_error. \ If it returns " PROC_TRUE ", Snd ignores the error (it assumes you've handled it via the hook)." ss->mus_error_hook = XEN_DEFINE_HOOK(S_mus_error_hook, 2, H_mus_error_hook); /* arg = error-type error-message */ }
{ "alphanum_fraction": 0.6603459747, "avg_line_length": 37.7322175732, "ext": "c", "hexsha": "dbe01904529818e1f4a4d0ecf114e7bd4e01aa2f", "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": "b633660e5945a6a6b095cd9aa3178deab56b354f", "max_forks_repo_licenses": [ "Ruby" ], "max_forks_repo_name": "OS2World/MM-SOUND-Snd", "max_forks_repo_path": "sources/snd.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "b633660e5945a6a6b095cd9aa3178deab56b354f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Ruby" ], "max_issues_repo_name": "OS2World/MM-SOUND-Snd", "max_issues_repo_path": "sources/snd.c", "max_line_length": 131, "max_stars_count": 1, "max_stars_repo_head_hexsha": "b633660e5945a6a6b095cd9aa3178deab56b354f", "max_stars_repo_licenses": [ "Ruby" ], "max_stars_repo_name": "OS2World/MM-SOUND-Snd", "max_stars_repo_path": "sources/snd.c", "max_stars_repo_stars_event_max_datetime": "2018-08-27T17:57:08.000Z", "max_stars_repo_stars_event_min_datetime": "2018-08-27T17:57:08.000Z", "num_tokens": 4829, "size": 18036 }
/* ** read data matrix, map of voxel addresses ** ** G.Lohmann, Jan 2013 */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_sort.h> #include "viaio/Vlib.h" #include "viaio/VImage.h" #include "viaio/mu.h" #define SQR(x) ((x) * (x)) #define ABS(x) ((x) > 0 ? (x) : -(x)) VImage *VImagePointer(VAttrList list,int *nt) { VImage tmp; VAttrListPosn posn; int i,ntimesteps,nrows,ncols,nslices; /* get image dimensions, read functional data */ nslices = 0; for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr (& posn)) { if (VGetAttrRepn (& posn) != VImageRepn) continue; VGetAttrValue (& posn, NULL,VImageRepn, & tmp); if (VPixelRepn(tmp) != VShortRepn) continue; nslices++; } /* VDestroyImage(tmp); */ if (nslices < 1) VError(" no slices"); VImage *src = (VImage *) VCalloc(nslices,sizeof(VImage)); i = ntimesteps = nrows = ncols = 0; for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr (& posn)) { if (VGetAttrRepn (& posn) != VImageRepn) continue; VGetAttrValue (& posn, NULL,VImageRepn, & src[i]); if (VPixelRepn(src[i]) != VShortRepn) continue; if (VImageNBands(src[i]) > ntimesteps) ntimesteps = VImageNBands(src[i]); if (VImageNRows(src[i]) > nrows) nrows = VImageNRows(src[i]); if (VImageNColumns(src[i]) > ncols) ncols = VImageNColumns(src[i]); i++; } nslices = i; if (nslices < 1) return NULL; if (ntimesteps < 2) return NULL; *nt = ntimesteps; return src; } /* read functional data */ void VReadImagePointer(VAttrList list,VImage *src) { VAttrListPosn posn; int i = 0; for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr (& posn)) { if (VGetAttrRepn (& posn) != VImageRepn) continue; VGetAttrValue (& posn, NULL,VImageRepn, & src[i]); if (VPixelRepn(src[i]) != VShortRepn) continue; i++; } } /* check if mask covers data. If not, set surplus voxels to zero */ long VMaskCoverage(VAttrList list,VImage mask) { VImage src=NULL; VAttrListPosn posn; int b,r,c; long count=0; b = 0; for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr (& posn)) { if (VGetAttrRepn (& posn) != VImageRepn) continue; VGetAttrValue (& posn, NULL,VImageRepn, & src); if (VPixelRepn(src) != VShortRepn) continue; if (VImageNRows(src) < 3) continue; if (VImageNRows(src) != VImageNRows(mask)) VError(" inconsistent nrows: %d, mask: %d",VImageNRows(src),VImageNRows(mask)); if (VImageNColumns(src) != VImageNColumns(mask)) VError(" inconsistent ncols: %d, mask: %d",VImageNColumns(src),VImageNColumns(mask)); for (r=0; r<VImageNRows(src); r++) { for (c=0; c<VImageNColumns(src); c++) { if (b >= VImageNBands(mask)) VError("VMaskCoverage, illegal addr, band= %d",b); float u = VGetPixel(mask,b,r,c); int j = (int)VPixel(src,0,r,c,VShort); if (j == 0 && u > 0.3) { VSetPixel(mask,b,r,c,0); count++; } } } b++; } return count; } /* check if data matrix contains zero voxels */ void VCheckMatrix(gsl_matrix_float *X) { long i,j,nvox=X->size1,nt=X->size2; double sum1,sum2,nx,mean,var,tiny=1.0e-4; long count = 0; nx = (double)nt; for (i=0; i<nvox; i++) { const float *arr1 = gsl_matrix_float_const_ptr(X,i,0); sum1 = sum2 = 0; for (j=0; j<nt; j++) { const double u = (double)arr1[j]; sum1 += u; sum2 += u*u; } mean = sum1/nx; var = (sum2 - nx * mean * mean) / (nx - 1.0); if (var < tiny) count++; } if (count > 0) VWarning(" number of empty voxels: %ld",count); } VImage VoxelMap(VImage mask,size_t *nvoxels) { int b,r,c; int nslices = VImageNBands(mask); int nrows = VImageNRows(mask); int ncols = VImageNColumns(mask); /* count number of non-zero voxels */ size_t nvox = 0; for (b=0; b<nslices; b++) { for (r=0; r<nrows; r++) { for (c=0; c<ncols; c++) { float u = VGetPixel(mask,b,r,c); if (ABS(u) < 0.5) continue; nvox++; } } } (*nvoxels) = nvox; /* voxel addresses */ VImage map = VCreateImage(1,4,nvox,VShortRepn); if (map == NULL) VError(" error allocating addr map"); VFillImage(map,VAllBands,0); VImage xmap=NULL; VExtractAttr (VImageAttrList(mask),"map",NULL,VImageRepn,&xmap,FALSE); VCopyImageAttrs (mask,map); VSetAttr(VImageAttrList(map),"nvoxels",NULL,VLongRepn,(VLong)nvox); VSetAttr(VImageAttrList(map),"nslices",NULL,VLongRepn,(VLong)nslices); VSetAttr(VImageAttrList(map),"nrows",NULL,VLongRepn,(VLong)nrows); VSetAttr(VImageAttrList(map),"ncols",NULL,VLongRepn,(VLong)ncols); VPixel(map,0,3,0,VShort) = nslices; VPixel(map,0,3,1,VShort) = nrows; VPixel(map,0,3,2,VShort) = ncols; size_t i = 0; for (b=0; b<nslices; b++) { for (r=0; r<nrows; r++) { for (c=0; c<ncols; c++) { float u = VGetPixel(mask,b,r,c); if (ABS(u) < 0.5) continue; VPixel(map,0,0,i,VShort) = b; VPixel(map,0,1,i,VShort) = r; VPixel(map,0,2,i,VShort) = c; i++; } } } return map; } /* two-pass formula, correct for round-off error */ void VNormalize(float *data,int nt,VBoolean stddev) { int j; float ave,var,sd,nx,s,u,tiny=1.0e-6; nx = (float)nt; ave = 0; for (j=0; j<nt; j++) ave += data[j]; ave /= nx; var = u = 0; for (j=0; j<nt; j++) { s = data[j]-ave; u += s; var += s*s; } var=(var-u*u/nx)/(nx-1); sd = sqrt(var); if (sd < tiny) { for (j=0; j<nt; j++) data[j] = 0; } else { if (stddev==FALSE) sd = 1.0; /* only subtract mean !!!! */ for (j=0; j<nt; j++) { u = data[j]; data[j] = (u-ave)/sd; } } } /* copy data to input matrix X, contains fMRI time series */ void VDataMatrix(VImage *src,int first,int len,VImage map,gsl_matrix_float *X) { long i,j,k,nvox; int b,r,c; float *data=NULL; data = (float *) VCalloc(len,sizeof(float)); gsl_matrix_float_set_zero (X); nvox = VImageNColumns(map); if (nvox != (long)X->size1) VError(" err, %ld %ld",(long)X->size1,nvox); if (len != (long)X->size2) VError(" err, %ld %ld",(long)X->size2,len); for (i=0; i<nvox; i++) { b = VPixel(map,0,0,i,VShort); r = VPixel(map,0,1,i,VShort); c = VPixel(map,0,2,i,VShort); if ((first+len) > VImageNBands(src[b])) VError(" illegal len addr, %d %d %d %d", b,first,len,VImageNBands(src[b])); if (r >= VImageNRows(src[b])) VError(" illegal row addr"); if (c >= VImageNColumns(src[b])) VError(" illegal column addr"); k = 0; for (j=first; j<first+len; j++) { data[k] = (float) VGetPixel(src[b],j,r,c); k++; } VNormalize(data,len,TRUE); float *ptr = gsl_matrix_float_ptr(X,i,0); for (j=0; j<len; j++) *ptr++ = data[j]; } VFree(data); }
{ "alphanum_fraction": 0.6030489592, "avg_line_length": 26.4418604651, "ext": "c", "hexsha": "e41fca749e7984b1fcc820df5a3a467b1eefc777", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_path": "src/ted/vted/VoxelMap.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_path": "src/ted/vted/VoxelMap.c", "max_line_length": 92, "max_stars_count": 17, "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_path": "src/ted/vted/VoxelMap.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "num_tokens": 2436, "size": 6822 }
#pragma once /*************************************************** *************** Auto-Generated File *************** ***************************************************/ #include <cstring> #include <string> #include <gsl/gsl_const_mksa.h> #include <gsl/gsl_const_num.h> #include "../../Utils/BinarySearch.h" enum UnitType { NONE, {UnitTypes} }; constexpr const int numUnits = {numUnits}; constexpr const char* unitNames[numUnits] = { {unitNames} }; constexpr const int unitIndices[numUnits] = { {unitIndices} }; constexpr const char * unitAbbreviations[numUnits] = { {unitAbbreviations} }; constexpr const UnitType unitTypes[numUnits] = { {unitTypes} }; constexpr const double unitConversions[numUnits] = { {unitConversions} }; /* Returns index of the unit in the unitNames array. Uses binary search under the hood to search for the index. Parameters ---------- name: The name of the unit Returns ------- The index or -1 if the provided name is not a unit. */ CONSTEXPR_BINARY_SEARCH(getUnitIndex, unitNames, numUnits) CONSTEXPR_BINARY_SEARCH(getAbbrIndex, unitAbbreviations, numUnits) constexpr UnitType getUnitType(const char* name){ int index = getUnitIndex(name); if (index != -1){ return NONE; } return unitTypes[index]; } inline UnitType getUnitType(const std::string& name){ int index = getUnitIndex(name.c_str()); if (index != -1){ return NONE; } return unitTypes[index]; } inline UnitType getUnitType(int index){ if (index < 0 || index >= numUnits){ return NONE; } return unitTypes[index]; } constexpr double getUnitConversion(const char* name){ int index = getUnitIndex(name); if (index != -1){ return NONE; } return unitConversions[index]; } inline double getUnitConversion(const std::string& name){ int index = getUnitIndex(name.c_str()); if (index != -1){ return NONE; } return unitConversions[index]; } inline double getUnitConversion(int index){ if (index < 0 || index >= numUnits){ return NONE; } return unitConversions[index]; }
{ "alphanum_fraction": 0.6592920354, "avg_line_length": 21.1875, "ext": "h", "hexsha": "9156ad63fbf264612b423887609805e1108ec099", "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": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "antoniojkim/CalcPlusPlus", "max_forks_repo_path": "MathEngine/.utils/.templates/Units.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "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": "antoniojkim/CalcPlusPlus", "max_issues_repo_path": "MathEngine/.utils/.templates/Units.h", "max_line_length": 66, "max_stars_count": null, "max_stars_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "antoniojkim/CalcPlusPlus", "max_stars_repo_path": "MathEngine/.utils/.templates/Units.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 485, "size": 2034 }
// Test driver for the pyramid class. #include <math.h> #include <stdlib.h> #include <glib.h> #include <gsl/gsl_math.h> #include <asf_meta.h> #include <float_image.h> #include "meta_read_wrapper.h" #include "pyramid.h" // Base name of .img/.meta pair we will use for testing. //#define TEST_IMG_BASENAME "E116306133G1S009" #define TEST_IMG_BASENAME "E116306133G1S009_subimage" // Directory to use as a scratch directory for pyramid layers. #define SCRATCH_DIR "/tmp/" // When we make JPEG images we give this mask value to the routine // which does it. This make should have any effect for the image we // are using. #define TEST_IMG_BOGUS_MASK_VALUE -999999.9 int main (void) { g_print ("This test may take a few moments...\n"); GString *meta_name = g_string_new (TEST_IMG_BASENAME); g_string_append (meta_name, ".meta"); GString *data_name = g_string_new (TEST_IMG_BASENAME); g_string_append (data_name, ".img"); meta_parameters *md = meta_read_wrapper (meta_name->str); g_string_free (meta_name, TRUE); ssize_t tisx = md->general->sample_count; ssize_t tisy = md->general->line_count; FloatImage *tiafi = float_image_new_from_file (tisx, tisy, data_name->str, 0, FLOAT_IMAGE_BYTE_ORDER_BIG_ENDIAN); g_string_free (data_name, TRUE); float_image_export_as_jpeg (tiafi, "test_pyramid_base_layer_direct.jpg", GSL_MAX (tisx, tisy), TEST_IMG_BOGUS_MASK_VALUE); meta_free (md); Pyramid *p = pyramid_new (TEST_IMG_BASENAME, SCRATCH_DIR); // "Testing" currently consists of creating jpeg images of each // layer and checking to see if they look decent. size_t ii; for ( ii = 0 ; ii < p->layers->len ; ii++ ) { pyramid_layer *cl = g_ptr_array_index (p->layers, ii); float *region; size_t rstart_x, rstart_y, rw, rh; gboolean unowned_memory; pyramid_get_region (p, 0, 0, tisx, tisy, pow (2, ii), &region, &rstart_x, &rstart_y, &rw, &rh, &unowned_memory); g_assert (rstart_x == 0 & rstart_y == 0); g_assert (rstart_x + rw * pow (2.0, ii) >= tisx); g_assert (rstart_y + rh * pow (2.0, ii) >= tisy); FloatImage *layer_image = float_image_new_from_memory (rw, rh, region); if ( unowned_memory ) { g_free (region); } GString *layer_file_name = g_string_new (""); g_string_append_printf (layer_file_name, "layer_%d.jpg", ii); ssize_t max_dimension = rw > rh ? rw : rh; int return_code = float_image_export_as_jpeg (layer_image, layer_file_name->str, max_dimension, TEST_IMG_BOGUS_MASK_VALUE); g_assert (return_code == 0); float_image_unref (layer_image); g_string_free (layer_file_name, TRUE); } g_print ("JPEG images of pyramid layers formed, now look at them and\n" "'touch test_pyramid_stamp' if they are ok.\n"); exit (EXIT_SUCCESS); }
{ "alphanum_fraction": 0.700248315, "avg_line_length": 27.637254902, "ext": "c", "hexsha": "dea20b3bf063f7078c2a3f57dc5f847a7180a0e3", "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/ssv/test_pyramid.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/ssv/test_pyramid.c", "max_line_length": 77, "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/ssv/test_pyramid.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": 810, "size": 2819 }
/* -*- linux-c -*- */ /* fewbody_hier.c Copyright (C) 2002-2004 John M. Fregeau This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_rng.h> #include "fewbody.h" /* allocate memory for a hier_t */ void fb_malloc_hier(fb_hier_t *hier) { int i; hier->hi = (int *) malloc(hier->nstarinit * sizeof(int)) - 1; fb_create_indices(hier->hi, hier->nstarinit); hier->narr = (int *) malloc((hier->nstarinit-1)*sizeof(int)) - 2; /* change from malloc to calloc to get rid of harmless valgrind errors... the errors occur in fb_normalize(), where uninitialized memory is normalized - these are clearly harmless */ hier->hier = (fb_obj_t *) calloc(hier->hi[hier->nstarinit] + 1, sizeof(fb_obj_t)); for (i=0; i<hier->hi[hier->nstarinit]+1; i++) { hier->hier[i].ncoll = 0; hier->hier[i].id = (long *) malloc(hier->nstarinit * sizeof(long)); } hier->obj = (fb_obj_t **) malloc(hier->nstarinit * sizeof(fb_obj_t *)); } /* initialize to a flat hier */ void fb_init_hier(fb_hier_t *hier) { int i; hier->nobj = hier->nstar; for (i=2; i<=hier->nstar; i++) { hier->narr[i] = 0; } for (i=0; i<hier->nstar; i++) { hier->obj[i] = &(hier->hier[hier->hi[1]+i]); } } /* free memory */ void fb_free_hier(fb_hier_t hier) { int i; for (i=0; i<hier.hi[hier.nstarinit]+1; i++) { free(hier.hier[i].id); } free(hier.hi+1); free(hier.narr+2); free(hier.hier); free(hier.obj); } /* trickle down hier */ void fb_trickle(fb_hier_t *hier, double t) { int i, j; for (i=hier->nstar; i>=2; i--) { for (j=0; j<hier->narr[i]; j++) { fb_downsync(&(hier->hier[hier->hi[i] + j]), t); } } } /* trickle up hier */ void fb_elkcirt(fb_hier_t *hier, double t) { int i, j; for (i=2; i<=hier->nstar; i++) { for (j=0; j<hier->narr[i]; j++) { fb_upsync(&(hier->hier[hier->hi[i] + j]), t); } } } /* created the index array */ int fb_create_indices(int *hi, int nstar) { int i, j=0; for (i=1; i<=nstar; i++) { hi[i] = j; j += nstar/i; } return(0); } /* how many members are in the immediate hierarchy */ int fb_n_hier(fb_obj_t *obj) { if (obj == NULL) { return(0); } else if ((obj->obj[0] == NULL) && (obj->obj[1] == NULL)) { return(1); } else if ((obj->obj[0]->obj[0] == NULL) && (obj->obj[0]->obj[1] == NULL) && (obj->obj[1]->obj[0] == NULL) && (obj->obj[1]->obj[1] == NULL)) { return(2); } else if (((obj->obj[0]->obj[0] == NULL) && (obj->obj[0]->obj[1] == NULL)) || ((obj->obj[1]->obj[0] == NULL) && (obj->obj[1]->obj[1] == NULL))) { return(3); } else { return(4); } } /* print the hierarchy information */ char *fb_sprint_hier(fb_hier_t hier, char string[FB_MAX_STRING_LENGTH]) { int i; snprintf(string, FB_MAX_STRING_LENGTH, "nstar=%d nobj=%d: ", hier.nstar, hier.nobj); for (i=0; i<hier.nobj; i++) { snprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), " %s", hier.obj[i]->idstring); } return(string); } /* print the hierarchy information in a nice human-readable format */ char *fb_sprint_hier_hr(fb_hier_t hier, char string[FB_MAX_STRING_LENGTH]) { int i; /* zero out string so strlen(string) returns 0 */ string[0] = '\0'; /* loop through objects */ for (i=0; i<hier.nobj; i++) { /* put a dash inbetween labels */ if (i > 0) { snprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), "-"); } /* a name for each type of hierarchy */ if (hier.obj[i]->n == 1) { snprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), "single"); } else if (hier.obj[i]->n == 2) { snprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), "binary"); } else if (hier.obj[i]->n == 3) { snprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), "triple"); } else if (hier.obj[i]->n == 4) { snprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), "quadruple"); } else if (hier.obj[i]->n == 5) { snprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), "quintuple"); } else if (hier.obj[i]->n == 6) { snprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), "sextuple"); } else if (hier.obj[i]->n == 7) { snprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), "septuple"); } else if (hier.obj[i]->n == 8) { snprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), "octuple"); } else if (hier.obj[i]->n == 9) { snprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), "nontuple"); } else if (hier.obj[i]->n == 10) { snprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), "decituple"); } else { snprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), "%d", hier.obj[i]->n); snprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), "tuple"); } } return(string); } /* merge the object's properties up---calculate the binary's properties from the stars' properties */ void fb_upsync(fb_obj_t *obj, double t) { int i; double m0, m1, x0[3], x1[3], xrel[3], v0[3], v1[3], vrel[3], E, l0[3], l1[3], l[3]; double ypp[3], psi, ecc_anom, L[3], A[3]; /* a little bit of paranoia here */ obj->ncoll = 0; obj->id[0] = -1; /* set time of upsync */ obj->t = t; /* create idstring */ snprintf(obj->idstring, FB_MAX_STRING_LENGTH, "[%s %s]", obj->obj[0]->idstring, obj->obj[1]->idstring); /* update number of stars in hierarchy */ obj->n = obj->obj[0]->n + obj->obj[1]->n; /* update mass */ m0 = obj->obj[0]->m; m1 = obj->obj[1]->m; obj->m = m0 + m1; /* update position and velocity */ for (i=0; i<3; i++) { obj->x[i] = (m0*(obj->obj[0]->x[i]) + m1*(obj->obj[1]->x[i])) / (obj->m); obj->v[i] = (m0*(obj->obj[0]->v[i]) + m1*(obj->obj[1]->v[i])) / (obj->m); } /* update semimajor axis */ for (i=0; i<3; i++) { x0[i] = obj->obj[0]->x[i] - obj->x[i]; x1[i] = obj->obj[1]->x[i] - obj->x[i]; xrel[i] = obj->obj[0]->x[i] - obj->obj[1]->x[i]; v0[i] = obj->obj[0]->v[i] - obj->v[i]; v1[i] = obj->obj[1]->v[i] - obj->v[i]; vrel[i] = obj->obj[0]->v[i] - obj->obj[1]->v[i]; } E = 0.5*(m0*fb_dot(v0, v0) + m1*fb_dot(v1, v1)) - m0*m1/fb_mod(xrel); if (E >= 0.0) { fprintf(stderr, "fb_upsync: E = %g >= 0!\n", E); exit(1); } obj->a = -m0 * m1 / (2.0 * E); /* update angular momentum, Runge-Lenz vector, and eccentricity (using the Runge-Lenz vector) */ fb_cross(x0, v0, l0); fb_cross(x1, v1, l1); for (i=0; i<3; i++) { L[i] = m0 * l0[i] + m1 * l1[i]; l[i] = L[i] * (m0+m1)/(m0*m1); } /* -A = l x v + G M \hat r */ fb_cross(vrel, l, A); for (i=0; i<3; i++) { A[i] -= (m0+m1) * xrel[i]/fb_mod(xrel); } obj->e = fb_mod(A)/(m0+m1); /* must be careful with circular orbits, which have a null A vector */ if (obj->e == 0.0) { for (i=0; i<3; i++) { A[i] = xrel[i]; } } /* define coord system */ for (i=0; i<3; i++) { obj->Lhat[i] = L[i]/fb_mod(L); /* z-direction */ obj->Ahat[i] = A[i]/fb_mod(A); /* x-direction */ } fb_cross(obj->Lhat, obj->Ahat, ypp); /* and set mean anomaly */ psi = atan2(fb_dot(x0, ypp), fb_dot(x0, obj->Ahat)); ecc_anom = acos((obj->e + cos(psi)) / (1.0 + obj->e * cos(psi))); if (psi < 0.0) { ecc_anom = 2.0 * FB_CONST_PI - ecc_anom; } obj->mean_anom = ecc_anom - obj->e * sin(ecc_anom); } /* randomly orient binary */ void fb_randorient(fb_obj_t *obj, gsl_rng *rng) { int i; double theta, phi, omega, xp[3], yp[3], zp[3]; /* random angles */ theta = acos(2.0 * gsl_rng_uniform(rng) - 1.0); phi = 2.0 * FB_CONST_PI * gsl_rng_uniform(rng); omega = 2.0 * FB_CONST_PI * gsl_rng_uniform(rng); obj->mean_anom = 2.0 * FB_CONST_PI * gsl_rng_uniform(rng); /* set up coordinate transformations */ zp[0] = -sin(theta) * sin(phi); zp[1] = sin(theta) * cos(phi); zp[2] = cos(theta); xp[0] = cos(phi); xp[1] = sin(phi); xp[2] = 0.0; fb_cross(zp, xp, yp); for (i=0; i<3; i++) { obj->Lhat[i] = zp[i]; obj->Ahat[i] = xp[i] * cos(omega) + yp[i] * sin(omega); } } /* merge the object's properties down---calculate the objs' properties from the binary's properties */ void fb_downsync(fb_obj_t *obj, double t) { int i; double xpp[3], ypp[3], zpp[3], er[3], epsi[3]; double a, e, m0, m1, omega, mean_anom, ecc_anom, psi, r0, r1, L, psidot, E, r0dot, r0dot2, r1dot; /* we're assuming here that the objs' masses are already set */ a = obj->a; e = obj->e; m0 = obj->obj[0]->m; m1 = obj->obj[1]->m; /* angular frequency */ omega = sqrt(obj->m/fb_cub(a)); /* mean anomaly, between 0 and 2PI */ mean_anom = (obj->mean_anom + omega * (t - obj->t)) / (2.0 * FB_CONST_PI); mean_anom = (mean_anom - floor(mean_anom)) * 2.0 * FB_CONST_PI; /* eccentric anomaly, from solving the Kepler equation */ ecc_anom = fb_kepler(e, mean_anom); /* true anomaly, between 0 and 2PI */ psi = acos((cos(ecc_anom) - e) / (1.0 - e * cos(ecc_anom))); /* this step is necessary because acos() returns a value between 0 and PI */ if (ecc_anom > FB_CONST_PI) { psi = 2.0 * FB_CONST_PI - psi; } /* define vectors, based on angular momentum and Runge-Lenz vectors */ for (i=0; i<3; i++) { zpp[i] = obj->Lhat[i]; xpp[i] = obj->Ahat[i]; } fb_cross(zpp, xpp, ypp); for (i=0; i<3; i++) { er[i] = xpp[i] * cos(psi) + ypp[i] * sin(psi); epsi[i] = ypp[i] * cos(psi) - xpp[i] * sin(psi); } /* determine binary params */ r0 = a * (1.0 - fb_sqr(e)) / ((1.0 + e*cos(psi)) * (1.0 + m0/m1)); r1 = a * (1.0 - fb_sqr(e)) / ((1.0 + e*cos(psi)) * (1.0 + m1/m0)); L = m0 * m1 * sqrt((m0+m1)*a*(1.0-fb_sqr(e))) / (m0 + m1); psidot = L / (m0 * fb_sqr(r0) + m1 * fb_sqr(r1)); E = -m0 * m1 / (2.0 * a); /* must be careful for circular orbits */ r0dot2 = (E + m0*m1/(r0+r1)) * 2.0 / (m0 * (1.0+m0/m1)) - fb_sqr(r0*psidot); if (ecc_anom > FB_CONST_PI) { r0dot = -(r0dot2<=0.0?0.0:sqrt(r0dot2)); } else { r0dot = (r0dot2<=0.0?0.0:sqrt(r0dot2)); } r1dot = m0 * r0dot / m1; for (i=0; i<3; i++) { obj->obj[0]->x[i] = r0 * er[i] + obj->x[i]; obj->obj[0]->v[i] = r0dot * er[i] + r0 * psidot * epsi[i] + obj->v[i]; obj->obj[1]->x[i] = -r1 * er[i] + obj->x[i]; obj->obj[1]->v[i] = -r1dot * er[i] - r1 * psidot * epsi[i] + obj->v[i]; } } /* copy one object to another, being careful about any pointers */ void fb_objcpy(fb_obj_t *obj1, fb_obj_t *obj2) { int i; long *longptr; for (i=0; i<obj2->ncoll; i++) { obj1->id[i] = obj2->id[i]; } /* prevent any dangling pointers */ longptr = obj1->id; *obj1 = *obj2; obj1->id = longptr; }
{ "alphanum_fraction": 0.5950788981, "avg_line_length": 28.9097938144, "ext": "c", "hexsha": "34fbb90f00d4e92efc39e51f1621abf9dd54fc61", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_forks_repo_licenses": [ "PSF-2.0" ], "max_forks_repo_name": "gnodvi/cosmos", "max_forks_repo_path": "ext/fewbod/fewbody-0.26/fewbody_hier.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:35:46.000Z", "max_issues_repo_issues_event_min_datetime": "2021-12-13T20:35:46.000Z", "max_issues_repo_licenses": [ "PSF-2.0" ], "max_issues_repo_name": "gnodvi/cosmos", "max_issues_repo_path": "ext/fewbod/fewbody-0.26/fewbody_hier.c", "max_line_length": 147, "max_stars_count": null, "max_stars_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_stars_repo_licenses": [ "PSF-2.0" ], "max_stars_repo_name": "gnodvi/cosmos", "max_stars_repo_path": "ext/fewbod/fewbody-0.26/fewbody_hier.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4138, "size": 11217 }
/* file: del2mat.h */ #ifndef DEL2MAT_H #define DEL2MAT_H #include <petsc.h> #include <petscvec.h> #include <petscmat.h> /* external Fortran 90 subroutine */ #define Del2Apply del2apply_ extern void Del2Apply(int*,double*,const double*,double*); /* user data structure and routines * defining the matrix-free operator */ typedef struct { PetscInt N; PetscScalar *F; } Del2Mat; #undef __FUNCT__ #define __FUNCT__ "Del2Mat_mult" /* y <- A * x */ PetscErrorCode Del2Mat_mult(Mat A, Vec x, Vec y) { Del2Mat *ctx; const PetscScalar *xx; PetscScalar *yy; PetscErrorCode ierr; PetscFunctionBegin; ierr = MatShellGetContext(A,(void**)&ctx);CHKERRQ(ierr); /* get raw vector arrays */ ierr = VecGetArrayRead(x,&xx);CHKERRQ(ierr); ierr = VecGetArray(y,&yy);CHKERRQ(ierr); /* call external Fortran subroutine */ Del2Apply(&ctx->N,ctx->F,xx,yy); /* restore raw vector arrays */ ierr = VecRestoreArrayRead(x,&xx);CHKERRQ(ierr); ierr = VecRestoreArray(y,&yy);CHKERRQ(ierr); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "Del2Mat_diag" /*D_i <- A_ii */ PetscErrorCode Del2Mat_diag(Mat A, Vec D) { PetscErrorCode ierr; PetscFunctionBegin; ierr = VecSet(D,6.0);CHKERRQ(ierr); PetscFunctionReturn(0); } #endif
{ "alphanum_fraction": 0.702681388, "avg_line_length": 23.0545454545, "ext": "h", "hexsha": "e129947a6ccbe2986e2a0ff5d3ef8e939547b59e", "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": "33408c70b4211b801c24f8c3cdb859f5aaf59367", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "zonca/petsc4py", "max_forks_repo_path": "demo/poisson3d/del2mat.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "33408c70b4211b801c24f8c3cdb859f5aaf59367", "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": "zonca/petsc4py", "max_issues_repo_path": "demo/poisson3d/del2mat.h", "max_line_length": 58, "max_stars_count": 1, "max_stars_repo_head_hexsha": "33408c70b4211b801c24f8c3cdb859f5aaf59367", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "zonca/petsc4py", "max_stars_repo_path": "demo/poisson3d/del2mat.h", "max_stars_repo_stars_event_max_datetime": "2018-11-11T05:00:53.000Z", "max_stars_repo_stars_event_min_datetime": "2018-11-11T05:00:53.000Z", "num_tokens": 369, "size": 1268 }
/** * \author Sylvain Marsat, University of Maryland - NASA GSFC * * \brief C header for the computation of the Fourier-domain overlaps, likelihoods. * * */ #ifndef _LIKELIHOOD_H #define _LIKELIHOOD_H #define _XOPEN_SOURCE 500 #ifdef __GNUC__ #define UNUSED __attribute__ ((unused)) #else #define UNUSED #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include <complex.h> #include <time.h> #include <unistd.h> #include <getopt.h> #include <stdbool.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_bspline.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_min.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_complex.h> #include "constants.h" #include "struct.h" #include "waveform.h" #include "wip.h" #if defined(__cplusplus) extern "C" { #elif 0 } /* so that editors will match preceding brace */ #endif /****** Prototypes: utilities *******/ /* Function to evaluate a Noise function */ void EvaluateNoise( gsl_vector* noisevalues, /* Output: vector of the noise values */ gsl_vector* freq, /* Input: vector of frequencies on which to evaluate */ ObjectFunction * Snoise, /* Noise function */ double fLow, /* Lower bound of the frequency window for the detector */ double fHigh); /* Upper bound of the frequency window for the detector */ /* Function building a frequency vector with logarithmic sampling */ void SetLogFrequencies( gsl_vector* freqvector, /* Output pointer to gsl_vector, already allocated */ const double fmin, /* Lower bound of the frequency interval */ const double fmax, /* Upper bound of the frequency interval */ const int nbpts); /* Number of points */ /* Function building a frequency vector with linear sampling */ void SetLinearFrequencies( gsl_vector* freqvector, /* Output pointer to gsl_vector, already allocated */ const double fmin, /* Lower bound of the frequency interval */ const double fmax, /* Upper bound of the frequency interval */ const int nbpts); /* Number of points */ /* Function determining logarithmically spaced frequencies from a waveform given as a list of modes, a minimal frequency and a number of points */ void ListmodesSetFrequencies( struct tagListmodesCAmpPhaseFrequencySeries *list, /* Waveform, list of modes in amplitude/phase form */ double fLow, /* Additional lower frequency limit */ double fHigh, /* Additional upper frequency limit */ int nbpts, /* Number of frequency samples */ int tagsampling, /* Tag for linear (0) or logarithmic (1) sampling */ gsl_vector* freqvector); /* Output: vector of frequencies, already allocated with nbpts */ /****** Prototypes: overlaps and likelihood computation *******/ /***************************** Functions for overlaps using linear integration ******************************/ /* Function computing the overlap (h1|h2) between two given modes, for a given noise function - uses simple trapeze integration on logarithmically sampled frequencies */ double FDSinglemodeLogLinearOverlap( struct tagCAmpPhaseFrequencySeries *freqseries1, /* First mode h1, in amplitude/phase form */ struct tagCAmpPhaseFrequencySeries *freqseries2, /* Second mode h2, in amplitude/phase form */ ObjectFunction * Snoise, /* Noise function */ double fLow, /* Lower bound of the frequency window for the detector */ double fHigh); /* Upper bound of the frequency window for the detector */ /* Function computing the overlap (h1|h2) between two waveforms given as lists of mode contributions (factos sYlm already included), for a given noise function - uses simple trapeze integration on logarithmically sampled frequencies - generates the frequency series in Re/Im form by summing the mode contributions first, then computes the overlap */ double FDListmodesLogLinearOverlap( struct tagListmodesCAmpPhaseFrequencySeries *list1, /* First waveform, list of modes in amplitude/phase form */ struct tagListmodesCAmpPhaseFrequencySeries *list2, /* First waveform, list of modes in amplitude/phase form */ ObjectFunction * Snoise, /* Noise function */ double fLow, /* Lower bound of the frequency window for the detector */ double fHigh, /* Upper bound of the frequency window for the detector */ double fstartobs1, /* Starting frequency for the 22 mode of wf 1 - as determined from a limited duration of the observation - set to 0 to ignore */ double fstartobs2); /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */ /* Function computing the overlap (h1|h2) between h1 given in Re/Im form and h2 given as a list of mode contributions (factos sYlm already included), for a given vector of noise values - uses simple trapeze integration - generates the frequency series of h2 in Re/Im form by summing the mode contributions first, then computes the overlap */ double FDOverlapReImvsListmodesCAmpPhase( struct tagReImFrequencySeries *freqseries1, /* First waveform, in Re/Im form */ struct tagListmodesCAmpPhaseFrequencySeries *list2, /* Second waveform, list of modes in amplitude/phase form */ gsl_vector* noisevalues, /* Vector for the noise values on the freq of h1 */ double fLow, /* Minimal frequency - set to 0 to ignore */ double fHigh, /* Maximal frequency - set to 0 to ignore */ double fstartobs2); /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */ /* Function computing the overlap (h1|h2) between two waveforms given as Re/Im frequency series (common freq values), for a given vector of noise values - uses simple trapeze integration */ double FDOverlapReImvsReIm( struct tagReImFrequencySeries *h1, /* First waveform, frequency series in Re/Im form */ struct tagReImFrequencySeries *h2, /* Second waveform, frequency series in Re/Im form */ gsl_vector* noisevalues); /* Vector for the noise values on common freq of the freqseries */ /***************************** Functions for overlaps using amplitude/phase (wip) ******************************/ /* Function computing the overlap (h1|h2) between two given modes in amplitude/phase form, for a given noise function - uses the amplitude/phase representation (wip) */ double FDSinglemodeWIPOverlap( struct tagCAmpPhaseFrequencySeries *freqseries1, /* First mode h1, in amplitude/phase form */ struct tagCAmpPhaseFrequencySeries *freqseries2, /* Second mode h2, in amplitude/phase form */ ObjectFunction * Snoise, /* Noise function */ double fLow, /* Lower bound of the frequency window for the detector */ double fHigh); /* Upper bound of the frequency window for the detector */ /* Function computing the overlap (h1|h2) between two waveforms given as list of modes, for a given noise function - no cross-products between modes are taken into account - two additional parameters for the starting 22-mode frequencies (then properly scaled for the other modes) for a limited duration of the observations */ double FDListmodesWIPOverlap( struct tagListmodesCAmpPhaseFrequencySeries *listh1, /* First waveform, list of modes in amplitude/phase form */ struct tagListmodesCAmpPhaseFrequencySeries *listh2, /* Second waveform, list of modes in amplitude/phase form */ ObjectFunction * Snoise, /* Noise function */ double fLow, /* Lower bound of the frequency window for the detector */ double fHigh, /* Upper bound of the frequency window for the detector */ double fstartobs1, /* Starting frequency for the 22 mode of wf 1 - as determined from a limited duration of the observation - set to 0 to ignore */ double fstartobs2); /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */ /************** Functions for overlap/likelihood allowing to switch between wip and loglinear integration *****************/ /* Wrapping of FDListmodesWIPOverlap or FDListmodesLogLinearOverlap according to tagint */ double FDListmodesOverlap( struct tagListmodesCAmpPhaseFrequencySeries *listh1, /* First mode h1, list of modes in amplitude/phase form */ struct tagListmodesCAmpPhaseFrequencySeries *listh2, /* Second mode h2, list of modes in amplitude/phase form */ ObjectFunction * Snoise, /* Noise function */ double fLow, /* Lower bound of the frequency window for the detector */ double fHigh, /* Upper bound of the frequency window for the detector */ double fstartobs1, /* Starting frequency for the 22 mode of wf 1 - as determined from a limited duration of the observation - set to 0 to ignore */ double fstartobs2, /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */ int tagint); /* Tag choosing the integrator: 0 for wip, 1 for log linear integration */ /* Function computing the log likelihood (h|s) - 1/2 (h|h) - 1/2 (s|s), with s the signal, h the template, and where we keep the constant term (s|s) - passed to the function as a parameter - all the cross-products between modes are taken into account - two additionals parameters for the starting 22-mode frequencies (then properly scaled for the other modes) for a limited duration of the observations */ double FDLogLikelihood( struct tagListmodesCAmpPhaseFrequencySeries *lists, /* Input: list of modes for the signal s, in Frequency-domain amplitude and phase form */ struct tagListmodesCAmpPhaseFrequencySeries *listh, /* Input: list of modes for the template, in Frequency-domain amplitude and phase form */ ObjectFunction * Snoise, /* Noise function */ double fLow, /* Lower bound of the frequency window for the detector */ double fHigh, /* Upper bound of the frequency window for the detector */ double ss, /* Inner product (s|s), constant to be computed elsewhere and passed as an argument */ double hh, /* Inner product (h|h), constant to be computed elsewhere and passed as an argument */ double fstartobss, /* Starting frequency for the 22 mode of s - as determined from a limited duration of the observation - set to 0 to ignore */ double fstartobsh, /* Starting frequency for the 22 mode of h - as determined from a limited duration of the observation - set to 0 to ignore */ int tagint); /* Tag choosing the integrator: 0 for wip, 1 for log linear integration */ /************** Functions for overlap/likelihood specific to loglinear integration *****************/ /* Function computing the log likelihood -1/2(h-s|h-s), with s the signal, h the template (both given as frequency series in Re/Im form) - h, s assumed to be given on the same set of frequencies - same for the vector of noise values - fstartobs for s, h has already been taken into account */ double FDLogLikelihoodReIm( struct tagReImFrequencySeries *s, /* First waveform (injection), frequency series in Re/Im form */ struct tagReImFrequencySeries *h, /* Second waveform (template), frequency series in Re/Im form */ gsl_vector* noisevalues); /* Vector for the noise values on common freq of the freqseries */ /***************************** Functions for overlaps using amplitude/phase (Fresnel) ******************************/ void ComputeIntegrandValues( CAmpPhaseFrequencySeries** integrand, /* Output: values of the integrand on common frequencies (initialized in the function) */ CAmpPhaseFrequencySeries* freqseries1, /* Input: frequency series for wf 1 */ CAmpPhaseSpline* splines2, /* Input: splines in matrix form for wf 2 */ ObjectFunction * Snoise, /* Noise function */ double fLow, /* Lower bound of the frequency - 0 to ignore */ double fHigh); /* Upper bound of the frequency - 0 to ignore */ /* Function computing the integrand values, combining the three channels A, E and T */ int ComputeIntegrandValues3Chan( CAmpPhaseFrequencySeries** integrand, /* Output: values of the integrand on common frequencies (initialized in the function) */ CAmpPhaseFrequencySeries* freqseries1chan1, /* Input: frequency series for wf 1, channel 1 */ CAmpPhaseFrequencySeries* freqseries1chan2, /* Input: frequency series for wf 1, channel 2 */ CAmpPhaseFrequencySeries* freqseries1chan3, /* Input: frequency series for wf 1, channel 3 */ CAmpPhaseSpline* splines2chan1, /* Input: splines in matrix form for wf 2, channel 1 */ CAmpPhaseSpline* splines2chan2, /* Input: splines in matrix form for wf 2, channel 2 */ CAmpPhaseSpline* splines2chan3, /* Input: splines in matrix form for wf 2, channel 3 */ ObjectFunction * Snoise1, /* Noise function */ ObjectFunction * Snoise2, /* Noise function */ ObjectFunction * Snoise3, /* Noise function */ double fLow, /* Lower bound of the frequency - 0 to ignore */ double fHigh); /* Upper bound of the frequency - 0 to ignore */ /* Function computing the overlap (h1|h2) between two given modes in amplitude/phase form, one being already interpolated, for a given noise function - uses the amplitude/phase representation (Fresnel) */ double FDSinglemodeFresnelOverlap( struct tagCAmpPhaseFrequencySeries *freqseries1, /* First mode h1, in amplitude/phase form */ struct tagCAmpPhaseSpline *splines2, /* Second mode h2, already interpolated in matrix form */ ObjectFunction * Snoise, /* Noise function */ double fLow, /* Lower bound of the frequency window for the detector */ double fHigh); /* Upper bound of the frequency window for the detector */ /* Function computing the overlap (h1|h2) between two given modes in amplitude/phase form for each channel A, E, T, one being already interpolated, for a given noise function - uses the amplitude/phase representation (Fresnel) */ double FDSinglemodeFresnelOverlap3Chan( struct tagCAmpPhaseFrequencySeries *freqseries1chan1, /* First mode h1 for channel 1, in amplitude/phase form */ struct tagCAmpPhaseFrequencySeries *freqseries1chan2, /* First mode h1 for channel 2, in amplitude/phase form */ struct tagCAmpPhaseFrequencySeries *freqseries1chan3, /* First mode h1 for channel 3, in amplitude/phase form */ struct tagCAmpPhaseSpline *splines2chan1, /* Second mode h2 for channel 1, already interpolated in matrix form */ struct tagCAmpPhaseSpline *splines2chan2, /* Second mode h2 for channel 2, already interpolated in matrix form */ struct tagCAmpPhaseSpline *splines2chan3, /* Second mode h2 for channel 3, already interpolated in matrix form */ ObjectFunction * Snoise1, /* Noise function */ ObjectFunction * Snoise2, /* Noise function */ ObjectFunction * Snoise3, /* Noise function */ double fLow, /* Lower bound of the frequency window for the detector */ double fHigh); /* Upper bound of the frequency window for the detector */ /* Function computing the overlap (h1|h2) between two waveforms given as list of modes, one being already interpolated, for a given noise function - two additional parameters for the starting 22-mode frequencies (then properly scaled for the other modes) for a limited duration of the observations */ double FDListmodesFresnelOverlap( struct tagListmodesCAmpPhaseFrequencySeries *listh1, /* First waveform, list of modes in amplitude/phase form */ struct tagListmodesCAmpPhaseSpline *listsplines2, /* Second waveform, list of modes already interpolated in matrix form */ ObjectFunction * Snoise, /* Noise function */ double fLow, /* Lower bound of the frequency window for the detector */ double fHigh, /* Upper bound of the frequency window for the detector */ double fstartobs1, /* Starting frequency for the 22 mode of wf 1 - as determined from a limited duration of the observation - set to 0 to ignore */ double fstartobs2); /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */ /* Function computing the overlap (h1|h2) between two waveforms given as list of modes for each non-correlated channel 1,2,3, one being already interpolated, for a given noise function - two additional parameters for the starting 22-mode frequencies (then properly scaled for the other modes) for a limited duration of the observations */ double FDListmodesFresnelOverlap3Chan( struct tagListmodesCAmpPhaseFrequencySeries *listh1chan1, /* First waveform channel channel 1, list of modes in amplitude/phase form */ struct tagListmodesCAmpPhaseFrequencySeries *listh1chan2, /* First waveform channel channel 2, list of modes in amplitude/phase form */ struct tagListmodesCAmpPhaseFrequencySeries *listh1chan3, /* First waveform channel channel 3, list of modes in amplitude/phase form */ struct tagListmodesCAmpPhaseSpline *listsplines2chan1, /* Second waveform channel channel 1, list of modes already interpolated in matrix form */ struct tagListmodesCAmpPhaseSpline *listsplines2chan2, /* Second waveform channel channel 2, list of modes already interpolated in matrix form */ struct tagListmodesCAmpPhaseSpline *listsplines2chan3, /* Second waveform channel channel 3, list of modes already interpolated in matrix form */ ObjectFunction * Snoise1, /* Noise function */ ObjectFunction * Snoise2, /* Noise function */ ObjectFunction * Snoise3, /* Noise function */ double fLow, /* Lower bound of the frequency window for the detector */ double fHigh, /* Upper bound of the frequency window for the detector */ double fstartobs1, /* Starting frequency for the 22 mode of wf 1 - as determined from a limited duration of the observation - set to 0 to ignore */ double fstartobs2); /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */ #if 0 { /* so that editors will match succeeding brace */ #elif defined(__cplusplus) } #endif #endif /* _LIKELIHOOD_H */
{ "alphanum_fraction": 0.6528292562, "avg_line_length": 80.94, "ext": "h", "hexsha": "8228133b207e020c54e55d90c6d4bd36f2dec797", "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": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_path": "tools/likelihood.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "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": "titodalcanton/flare", "max_issues_repo_path": "tools/likelihood.h", "max_line_length": 405, "max_stars_count": null, "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_path": "tools/likelihood.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4249, "size": 20235 }
/** * Copyright 2016 José Manuel Abuín Mosquera <josemanuel.abuin@usc.es> * * This file is part of Matrix Market Suite. * * Matrix Market Suite 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. * * Matrix Market Suite 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 Matrix Market Suite. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <cblas.h> #include "DMxV.h" void usageDMxDM(){ fprintf(stderr, "\n"); fprintf(stderr, "Usage: MM-Suite DMxDM [options] <input-matrix-A> <input-matrix-B>\n"); fprintf(stderr, "\nInput/output options:\n\n"); fprintf(stderr, " -o STR Output file name. Default: stdout\n"); fprintf(stderr, " -r Input format is row per line. Default: False\n"); fprintf(stderr, "\nPerformance options:\n\n"); fprintf(stderr, " -t INT Number of threads to use in OpenBLAS. Default: 1\n"); fprintf(stderr, "\n"); } int DMxDM(int argc, char *argv[]) { int ret_code = 1; int option; unsigned long *IA; unsigned long *JA; double *valuesA; unsigned long MA; unsigned long NA; unsigned long long nzA; unsigned long *IB; unsigned long *JB; double *valuesB; unsigned long MB; unsigned long NB; unsigned long long nzB; char *outputFileName = NULL; char *inputMatrixFileA = NULL; char *inputMatrixFileB= NULL; int inputFormatRow = 0; int numThreads = 1; while ((option = getopt(argc, argv,"ro:t:")) >= 0) { switch (option) { case 'o' : //free(outputFileName); outputFileName = (char *) malloc(sizeof(char)*strlen(optarg)+1); strcpy(outputFileName,optarg); break; case 'r': inputFormatRow = 1; break; case 't': numThreads = atoi(optarg); break; default: break; } } if ((optind + 2 > argc) || (optind + 3 <= argc)) { usageDMxDM(); return 0; } openblas_set_num_threads(numThreads); if(outputFileName == NULL) { outputFileName = (char *) malloc(sizeof(char)*7); sprintf(outputFileName,"stdout"); } inputMatrixFileA = (char *)malloc(sizeof(char)*strlen(argv[optind])+1); inputMatrixFileB = (char *)malloc(sizeof(char)*strlen(argv[optind+1])+1); strcpy(inputMatrixFileA,argv[optind]); strcpy(inputMatrixFileB,argv[optind+1]); //Read matrices if(inputFormatRow){ if(!readDenseCoordinateMatrixRowLine(inputMatrixFileA,&IA,&JA,&valuesA,&MA,&NA,&nzA)){ fprintf(stderr, "[%s] Can not read Matrix\n",__func__); return 0; } if(!readDenseCoordinateMatrixRowLine(inputMatrixFileB,&IB,&JB,&valuesB,&MB,&NB,&nzB)){ fprintf(stderr, "[%s] Can not read Matrix\n",__func__); return 0; } } else { if(!readDenseCoordinateMatrix(inputMatrixFileA,&IA,&JA,&valuesA,&MA,&NA,&nzA)){ fprintf(stderr, "[%s] Can not read Matrix\n",__func__); return 0; } if(!readDenseCoordinateMatrix(inputMatrixFileB,&IB,&JB,&valuesB,&MB,&NB,&nzB)){ fprintf(stderr, "[%s] Can not read Matrix\n",__func__); return 0; } } /* void cblas_dgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const double alpha, const double *A, const int lda, const double *B, const int ldb, const double beta, double *C, const int ldc); */ double *result=(double *) malloc(MA * NB * sizeof(double)); //cblas_dgemv(CblasColMajor,CblasNoTrans,M,N,1.0,values,N,vectorValues,1,0.0,result,1); cblas_dgemm(CblasRowMajor,CblasNoTrans,CblasNoTrans, MA, NB, NA, 1.0,valuesA,NA,valuesB,NB,0.0,result,NB); if(inputFormatRow){ writeDenseCoordinateMatrixRowLine(outputFileName, result,MA,NB,MA * NB); } else{ writeDenseCoordinateMatrix(outputFileName, result,MA,NB,MA * NB); } return ret_code; }
{ "alphanum_fraction": 0.6557377049, "avg_line_length": 26.7804878049, "ext": "c", "hexsha": "c56ecc5c6c29f706c32bd4aed538127352c93568", "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": "0bf3a81214f094dbddec868d3d133986b31f4b01", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "vkeller/math-454", "max_forks_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/operations/DMxDM.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01", "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": "vkeller/math-454", "max_issues_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/operations/DMxDM.c", "max_line_length": 107, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "vkeller/math-454", "max_stars_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/operations/DMxDM.c", "max_stars_repo_stars_event_max_datetime": "2021-05-19T13:31:49.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-19T13:31:49.000Z", "num_tokens": 1243, "size": 4392 }
/* This library is used by compare_hashes_* tests. */ #ifndef COMPARISON_STATS_H #define COMPARISON_STATS_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <gsl/gsl_sf_log.h> #include <gsl/gsl_math.h> struct comparison_stats { uint64_t *ones_count; uint64_t tot_count; uint hash_width; uint64_t (*calc_hash)(void *hash_info, unsigned char *str, unsigned length); void *hash_info; }; typedef enum { report_type_short, report_type_long } report_type; void basic_init_comparison_stats(struct comparison_stats *cs, uint width); void process_comparison_stats(struct comparison_stats *cs, unsigned char *str, unsigned sz); void report_comparison_stats(struct comparison_stats *cs, const char *name, report_type rtyp); void free_comparison_stats(struct comparison_stats *cs); #endif
{ "alphanum_fraction": 0.7870036101, "avg_line_length": 25.1818181818, "ext": "h", "hexsha": "611d35da6d543826bf1115c74fe0d197adddcdc3", "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": "dc103a67d0826f09b07196217f00a454441d5011", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jonkanderson/BitBalancedTableHash", "max_forks_repo_path": "tests/entropy_tests/comparison_stats.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "dc103a67d0826f09b07196217f00a454441d5011", "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": "jonkanderson/BitBalancedTableHash", "max_issues_repo_path": "tests/entropy_tests/comparison_stats.h", "max_line_length": 94, "max_stars_count": null, "max_stars_repo_head_hexsha": "dc103a67d0826f09b07196217f00a454441d5011", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jonkanderson/BitBalancedTableHash", "max_stars_repo_path": "tests/entropy_tests/comparison_stats.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 190, "size": 831 }
#include <gsl/gsl_math.h> #include <gsl/gsl_cblas.h> #include "cblas.h" void cblas_srotg (float *a, float *b, float *c, float *s) { #define BASE float #include "source_rotg.h" #undef BASE }
{ "alphanum_fraction": 0.7015706806, "avg_line_length": 15.9166666667, "ext": "c", "hexsha": "65b279641e95e91464f5f8681aba86b96f2cd0d1", "lang": "C", "max_forks_count": 173, "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z", "max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_forks_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_forks_repo_name": "juandesant/astrometry.net", "max_forks_repo_path": "gsl-an/cblas/srotg.c", "max_issues_count": 208, "max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z", "max_issues_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_issues_repo_name": "juandesant/astrometry.net", "max_issues_repo_path": "gsl-an/cblas/srotg.c", "max_line_length": 52, "max_stars_count": 460, "max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_stars_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_stars_repo_name": "juandesant/astrometry.net", "max_stars_repo_path": "gsl-an/cblas/srotg.c", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z", "num_tokens": 65, "size": 191 }
/* movstat/movqqr.c * * Compute moving q-quantile range * * Copyright (C) 2018 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 <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_movstat.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_statistics.h> /* gsl_movstat_qqr() Apply a moving q-quantile range to an input vector Inputs: endtype - how to handle end points x - input vector, size n q - quantile \in [0,0.5] xqqr - (output) vector of q-quantile ranges of x, size n xqqr_i = q-quantile range of i-th window: w - workspace */ int gsl_movstat_qqr(const gsl_movstat_end_t endtype, const gsl_vector * x, const double q, gsl_vector * xqqr, gsl_movstat_workspace * w) { if (x->size != xqqr->size) { GSL_ERROR("x and xqqr vectors must have same length", GSL_EBADLEN); } else if (q < 0.0 || q > 0.5) { GSL_ERROR("q must be between 0 and 0.5", GSL_EDOM); } else { double qq = q; int status = gsl_movstat_apply_accum(endtype, x, gsl_movstat_accum_qqr, (void *) &qq, xqqr, NULL, w); return status; } }
{ "alphanum_fraction": 0.6692268305, "avg_line_length": 31, "ext": "c", "hexsha": "8d2c2ec92bec69a981e6b3c5c72735a070a6d4d2", "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": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_path": "test/lib/gsl-2.6/movstat/movqqr.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "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": [ "MIT" ], "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/movstat/movqqr.c", "max_line_length": 107, "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/movstat/movqqr.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": 549, "size": 1953 }
/* * Calculation of Integral */ #include <stdio.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_statistics.h> #include <gsl/gsl_math.h> #include <gsl/gsl_monte.h> #include <gsl/gsl_monte_vegas.h> #include "timer.h" double g (double *t, size_t dim, void *params); int main (void) { double res, err; double dist, dmin = 1.001, dmax = 4.; size_t dim = 6; int np = 20; double vegas[20], vegaserr[20]; double time1, time2; double dstep = (dmax - dmin) / (np - 1); double xl[] = { 0., 0., 0., 0., 0., 0. }; double xu[] = { 1., 1., 1., 1., 1., 1. }; gsl_rng *r = gsl_rng_alloc (gsl_rng_taus2); unsigned long seed = 1UL; gsl_rng_set (r, seed); size_t calls = 1000000; gsl_monte_function G = { &g, dim, &dist }; gsl_monte_vegas_state *sv = gsl_monte_vegas_alloc (dim); gsl_monte_vegas_init (sv); dist = dmin; // Vegas algorithm calculation timer_start (); // printf ("# Dist Energy ErrEst Dipole\n"); for (int i = 0; i < np; i++) { gsl_monte_vegas_integrate (&G, xl, xu, dim, calls / 5, r, sv, &res, &err); do { gsl_monte_vegas_integrate (&G, xl, xu, dim, calls, r, sv, &res, &err); } while (fabs (gsl_monte_vegas_chisq (sv) - 1.0) > 0.2); //printf ("% .6f % .6f % .6f % .6f\n", dist, res, err, // -2. / pow (dist, 3.)); //fflush (stdout); vegas[i] = res; vegaserr[i] = err; dist += dstep; } time1 = timer_stop (); gsl_monte_vegas_free (sv); dist = dmin; printf ("# Dist HMC Vegas Verr Dipole Difference\n"); double t[6]; // Calculation using homemade Monte Carlo algorithm timer_start (); for (int i = 0; i < np; i++) { double sum = 0.; for (int j = 0; j < (int) calls; j++) { for (int m = 0; m < (int) dim; m++) { t[m] = gsl_rng_uniform (r); } sum += g (t, dim, &dist); } double energy = sum / calls; double difference = fabs (energy - vegas[i]); printf ("% .6f % .6f % .6f % .6f % .6f % .6f\n", dist, energy, vegas[i], vegaserr[i], -2./pow(dist, 3.), difference ); dist += dstep; } time2 = timer_stop (); printf ("Time Vegas: %.2f Time HMC: %.2f\n", time1, time2); printf ("Speedup: %.2f\n", time1 / time2); gsl_rng_free (r); return 0; }
{ "alphanum_fraction": 0.4986269125, "avg_line_length": 21.7863247863, "ext": "c", "hexsha": "b70a80e9238f0a2dc6257ed2de81c5f5a67c132d", "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": "4829666b4a2ec58625b6dc37a5d47501f8fbd059", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "matthewignal/fin2", "max_forks_repo_path": "main.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "4829666b4a2ec58625b6dc37a5d47501f8fbd059", "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": "matthewignal/fin2", "max_issues_repo_path": "main.c", "max_line_length": 83, "max_stars_count": null, "max_stars_repo_head_hexsha": "4829666b4a2ec58625b6dc37a5d47501f8fbd059", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "matthewignal/fin2", "max_stars_repo_path": "main.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 828, "size": 2549 }
#include <cblas.h> #include <stdio.h> #include <stdlib.h> #include <papi.h> #ifndef MATLEN #define MATLEN 128 #endif #ifndef QUIET #define PRINT( exp ) exp #else #define PRINT( exp ) #endif int main( ) { int EventSet = PAPI_NULL; long long values[ 4 ], s, e; int retval; double *a, *b, *c; /* INICIALIZAÇÃO */ PRINT( printf( "Inicializando Matriz: %dx%d\n", MATLEN, MATLEN ) ); a = ( double* ) malloc( MATLEN * MATLEN * sizeof( double ) ); b = ( double* ) malloc( MATLEN * MATLEN * sizeof( double ) ); c = ( double* ) malloc( MATLEN * MATLEN * sizeof( double ) ); /* * CONFIGURAÇÃO DO PAPI * Init PAPI library */ retval = PAPI_library_init( PAPI_VER_CURRENT ); if( retval != PAPI_VER_CURRENT ) { printf( "Erro em PAPI_library_init : retval = %d\n", retval ); exit( 1 ); } if( ( retval = PAPI_create_eventset( &EventSet ) ) != PAPI_OK ) { printf( "Erro em PAPI_create_eventset : retval = %d\n", retval ); exit( 1 ); } if( PAPI_add_event( EventSet, PAPI_L2_DCM ) != PAPI_OK ) { printf( "Erro em PAPI_L2_DCM\n" ); exit( 1 ); } if( PAPI_add_event( EventSet, PAPI_DP_OPS ) != PAPI_OK ) { printf( "Erro em PAPI_DP_OPS\n" ); exit( 1 ); } if( PAPI_add_event( EventSet, PAPI_TOT_CYC ) != PAPI_OK ) { printf( "Erro em PAPI_TOT_CYC\n" ); exit( 1 ); } if( PAPI_add_event( EventSet, PAPI_TOT_INS ) != PAPI_OK ) { printf( "Erro em PAPI_TOT_INS\n" ); exit( 1 ); } if( ( retval = PAPI_start( EventSet ) ) != PAPI_OK ) { printf( "Erro em PAPI_start" ); exit( 1 ); } s = PAPI_get_real_usec( ); /* FUNÇÃO A SER AVALIADA */ cblas_dgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans, MATLEN, MATLEN, MATLEN, 1.0, a, MATLEN, b, MATLEN, 0.0, c, MATLEN ); /* FIM DA FUNÇÃO A SER AVALIADA */ e = PAPI_get_real_usec( ); if( ( retval = PAPI_read( EventSet, &values[ 0 ] ) ) != PAPI_OK ) { printf( "Erro em PAPI_read" ); exit( 1 ); } if( ( retval = PAPI_stop( EventSet, NULL ) ) != PAPI_OK ) { printf( "Erro em PAPI_stop" ); exit( 1 ); } double cpi = ( double ) values[ 2 ] / ( double ) values[ 3 ]; double icp = ( double ) values[ 3 ] / ( double ) values[ 2 ]; double mflops = ( double ) values[ 1 ]; // double mflops = ( double ) 2 * MATLEN * MATLEN * MATLEN; mflops = ( mflops / ( ( double ) ( e - s ) ) ); /* EXIBINDO INFORMAÇÕES */ PRINT( printf( "PAPI_L2_DCM = %lld\n", values[ 0 ] ); printf( "PAPI_DP_OPS = %lld\n", values[ 1 ] ); /* CPI */ printf( "PAPI_TOT_CYC = %lld\n", values[ 2 ] ); printf( "PAPI_TOT_INS = %lld\n", values[ 3 ] ); printf( "CPI: %.2f\n", cpi ); printf( "ICP: %.2f\n", icp ); printf( "Wallclock time: %lld ms\n", e - s ); printf( "MFLOPS: %g\n", mflops ); printf( "Fim\n" ); ); /* MAT BLk Time DCM MFLOPS CPI */ printf( "%d, %lld, %lld, %.2f, %.2f\n", MATLEN, e - s, values[ 0 ], mflops, cpi ); free( a ); free( b ); free( c ); return( 0 ); }
{ "alphanum_fraction": 0.5700996678, "avg_line_length": 27.8703703704, "ext": "c", "hexsha": "6c5235fd137bea3d24578d9e2e599545c8df1ae5", "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": "eb4fcb9c19ca4fc2cba2a392928957efe4bd5198", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lellisls/PAD", "max_forks_repo_path": "at02-cache/ex04/ex04.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "eb4fcb9c19ca4fc2cba2a392928957efe4bd5198", "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": "lellisls/PAD", "max_issues_repo_path": "at02-cache/ex04/ex04.c", "max_line_length": 84, "max_stars_count": null, "max_stars_repo_head_hexsha": "eb4fcb9c19ca4fc2cba2a392928957efe4bd5198", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lellisls/PAD", "max_stars_repo_path": "at02-cache/ex04/ex04.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1071, "size": 3010 }
#include "stdlib.h" #include "stdio.h" #include "/home/lillian/work/install_fpdebug/valgrind-3.7.0/fpdebug/fpdebug.h" #include <gsl/gsl_sf.h> int main(int argc, const char * argv[]) { unsigned long int hexdouble; double a; sscanf(argv[1], "%lX", &hexdouble); a = *(double*)(&hexdouble); double result = gsl_sf_Si(a); //printf("%.15f\n", result); VALGRIND_PRINT_ERROR("result", &result); return 0; }
{ "alphanum_fraction": 0.7035175879, "avg_line_length": 28.4285714286, "ext": "c", "hexsha": "b134ae9b55c2204bbf4041034ba13a8c5deb739c", "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": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "floatfeather/FpGenetic", "max_forks_repo_path": "others_ori/gsl_sf_Si.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559", "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": "floatfeather/FpGenetic", "max_issues_repo_path": "others_ori/gsl_sf_Si.c", "max_line_length": 78, "max_stars_count": null, "max_stars_repo_head_hexsha": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "floatfeather/FpGenetic", "max_stars_repo_path": "others_ori/gsl_sf_Si.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 123, "size": 398 }
#pragma once #include <gsl/gsl> #include <memory> struct SpeexResamplerState_; typedef struct SpeexResamplerState_ SpeexResamplerState; namespace Halley { struct AudioResamplerResult { size_t nRead; size_t nWritten; }; class AudioResampler { public: AudioResampler(int from, int to, int nChannels, float quality = 1.0f); ~AudioResampler(); AudioResamplerResult resample(gsl::span<const float> src, gsl::span<float> dst, size_t channel); AudioResamplerResult resampleInterleaved(gsl::span<const float> src, gsl::span<float> dst); AudioResamplerResult resampleInterleaved(gsl::span<const short> src, gsl::span<short> dst); AudioResamplerResult resampleNoninterleaved(gsl::span<const float> src, gsl::span<float> dst, const size_t numChannels); size_t numOutputSamples(size_t numInputSamples) const; private: std::unique_ptr<SpeexResamplerState, void(*)(SpeexResamplerState*)> resampler; size_t nChannels; int from; int to; }; }
{ "alphanum_fraction": 0.7678756477, "avg_line_length": 27.5714285714, "ext": "h", "hexsha": "341b1cfdbb09eae11d584b2bf8f238c96f783c47", "lang": "C", "max_forks_count": 193, "max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z", "max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z", "max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "sunhay/halley", "max_forks_repo_path": "src/engine/utils/include/halley/audio/resampler.h", "max_issues_count": 53, "max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z", "max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "sunhay/halley", "max_issues_repo_path": "src/engine/utils/include/halley/audio/resampler.h", "max_line_length": 122, "max_stars_count": 3262, "max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "sunhay/halley", "max_stars_repo_path": "src/engine/utils/include/halley/audio/resampler.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z", "max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z", "num_tokens": 276, "size": 965 }
#include <assert.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/time.h> #include "../src/fastlambertw.h" #include "testmacros.h" #include "../src/config.h" #ifdef HAVE_GSL_GSL_SF_LAMBERT_H #include <gsl/gsl_sf_lambert.h> #endif static inline float lambertwrange (void) { if (drand48 () < 0.5) { return -0.36787944117144232f + 1.36787944117144232f * drand48 (); } else { return 100.0f * drand48 (); } } static inline float lambertwf (float x) { float w = (x < 5) ? 0 : log (x) - log (log (x)) + log (log (x)) / log (x); unsigned int n; for (n = 0; n < 20; ++n) { w = (w * w + exp (-w) * x) / (1.0 + w); } return w; } static inline float lambertwexpxf (float x) { return lambertwf (expf (x)); } test_scalar (fastlambertw, lambertwf, lambertwrange (), 1e-4f, 100000000) test_scalar (fasterlambertw, lambertwf, lambertwrange (), 1e-2f, 100000000) test_scalar (fastlambertwexpx, lambertwexpxf, -3.0f + 6.0f * drand48 (), 1e-3f, 100000000) test_scalar (fasterlambertwexpx, lambertwexpxf, -3.0f + 6.0f * drand48 (), 1e-2f, 100000000) #ifdef HAVE_GSL_GSL_SF_LAMBERT_H test_scalar (gsl_sf_lambert_W0, lambertwf, lambertwrange (), 1e-2f, 1000000) #endif test_vector (vfastlambertw, lambertwf, lambertwrange (), 1e-4f, 100000000) test_vector (vfasterlambertw, lambertwf, lambertwrange (), 1e-2f, 100000000) test_vector (vfastlambertwexpx, lambertwexpxf, -3.0f + 6.0f * drand48 (), 1e-3f, 100000000) test_vector (vfasterlambertwexpx, lambertwexpxf, -3.0f + 6.0f * drand48 (), 1e-2f, 100000000) int main (int argc, char *argv[]) { char buf[4096]; (void) argc; srand48 (69); // fprintf (stderr, "fastlambertw (%g) = %g, " // "fastlambertw (%g) = %g, " // "fasterlambertwexpx (%g) = %g (%g)\n", // -0.36787944117144232f, // fastlambertw (-0.36787944117144232f), // -0.36787944117144232f + 0.01f, // fastlambertw (-0.36787944117144232f + 0.01f), // -5.0f, // fasterlambertwexpx (-5.0f), // v4sf_index (vfasterlambertwexpx (v4sfl (-5.0f)), 0)); strncpy (buf, argv[0], sizeof (buf) - 5); strncat (buf, ".out", 5); fclose (stderr); stderr = fopen (buf, "w"); test_fastlambertw (); test_fasterlambertw (); test_vfastlambertw (); test_vfasterlambertw (); #ifdef HAVE_GSL_GSL_SF_LAMBERT_H test_gsl_sf_lambert_W0 (); #endif test_fastlambertwexpx (); test_fasterlambertwexpx (); test_vfastlambertwexpx (); test_vfasterlambertwexpx (); time_fastlambertw (); time_fasterlambertw (); time_vfastlambertw (); time_vfasterlambertw (); #ifdef HAVE_GSL_GSL_SF_LAMBERT_H time_gsl_sf_lambert_W0 (); #endif time_fastlambertwexpx (); time_fasterlambertwexpx (); time_vfastlambertwexpx (); time_vfasterlambertwexpx (); return 0; }
{ "alphanum_fraction": 0.6498269896, "avg_line_length": 24.7008547009, "ext": "c", "hexsha": "5a4861846f0e0c3d5e9ed90f8afb03f52c7d52fd", "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": "cbd7eaa7e1a41157c927d1b188b55436cafefd09", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "Mister-Meeseeks/fastapprox", "max_forks_repo_path": "tests/testfastlambertw.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "cbd7eaa7e1a41157c927d1b188b55436cafefd09", "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": "Mister-Meeseeks/fastapprox", "max_issues_repo_path": "tests/testfastlambertw.c", "max_line_length": 93, "max_stars_count": null, "max_stars_repo_head_hexsha": "cbd7eaa7e1a41157c927d1b188b55436cafefd09", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Mister-Meeseeks/fastapprox", "max_stars_repo_path": "tests/testfastlambertw.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1124, "size": 2890 }
/// /// @file /// /// @brief This file contains math functions that are shared among all /// components of the library. /// /// @author Mirko Myllykoski (mirkom@cs.umu.se), Umeå University /// /// @internal LICENSE /// /// Copyright (c) 2019-2020, Umeå Universitet /// /// Redistribution and use in source and binary forms, with or without /// modification, are permitted provided that the following conditions are met: /// /// 1. Redistributions of source code must retain the above copyright notice, /// this list of conditions and the following disclaimer. /// /// 2. Redistributions in binary form must reproduce the above copyright notice, /// this list of conditions and the following disclaimer in the documentation /// and/or other materials provided with the distribution. /// /// 3. Neither the name of the copyright holder nor the names of its /// contributors may be used to endorse or promote products derived from this /// software without specific prior written permission. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" /// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE /// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE /// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE /// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR /// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF /// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS /// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN /// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) /// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE /// POSSIBILITY OF SUCH DAMAGE. /// #include <starneig_config.h> #include <starneig/configuration.h> #include "math.h" #include "common.h" #include "sanity.h" #include <stddef.h> #include <string.h> #include <cblas.h> int starneig_largers_factor(int a, int b) { while (b != 0) { int t = b; b = a % b; a = t; } return a; } void starneig_init_local_q(int n, size_t ldA, double *A) { for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) A[i*ldA+j] = 0.0; for (int i = 0; i < n; i++) A[i*ldA+i] = 1.0; } void starneig_small_left_gemm_update(int rbegin, int rend, int cbegin, int cend, size_t ldQ, size_t ldA, size_t ldT, double const *Q, double *A, double *T) { STARNEIG_SANITY_CHECK_INF(rbegin, rend, cbegin, cend, ldA, A, "A (in)"); STARNEIG_SANITY_CHECK_INF(0, rend-rbegin, 0, rend-rbegin, ldQ, Q, "Q"); int m = rend-rbegin; int n = cend-cbegin; int k = rend-rbegin; if (m == 0 || n == 0) return; starneig_copy_matrix( k, n, ldA, ldT, sizeof(double), A+cbegin*ldA+rbegin, T); cblas_dgemm( CblasColMajor, CblasTrans, CblasNoTrans, m, n, k, 1.0, Q, ldQ, T, ldT, 0.0, A+cbegin*ldA+rbegin, ldA); STARNEIG_SANITY_CHECK_INF(rbegin, rend, cbegin, cend, ldA, A, "A (out)"); } void starneig_small_right_gemm_update( int rbegin, int rend, int cbegin, int cend, size_t ldQ, size_t ldA, size_t ldT, double const *Q, double *A, double *T) { STARNEIG_SANITY_CHECK_INF(rbegin, rend, cbegin, cend, ldA, A, "A (in)"); STARNEIG_SANITY_CHECK_INF(0, cend-cbegin, 0, cend-cbegin, ldQ, Q, "Q"); int m = rend-rbegin; int n = cend-cbegin; int k = cend-cbegin; if (m == 0 || n == 0) return; starneig_copy_matrix( m, k, ldA, ldT, sizeof(double), A+cbegin*ldA+rbegin, T); cblas_dgemm( CblasColMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1.0, T, ldT, Q, ldQ, 0.0, A+cbegin*ldA+rbegin, ldA); STARNEIG_SANITY_CHECK_INF(rbegin, rend, cbegin, cend, ldA, A, "A (out)"); } void starneig_small_gemm_updates( int begin, int end, int n, size_t ldlQ, size_t ldlZ, size_t ldQ, size_t ldZ, size_t ldA, size_t ldB, size_t ldhT, size_t ldvT, double const *lQ, double const *lZ, double *Q, double *Z, double *A, double *B, double *hT, double *vT) { // apply the local transformation matrices lQ and lZ to Q and Z if (Q != NULL) starneig_small_right_gemm_update( 0, n, begin, end, ldlQ, ldQ, ldvT, lQ, Q, vT); if (Z != NULL && Z != Q) starneig_small_right_gemm_update( 0, n, begin, end, ldlZ, ldZ, ldvT, lZ, Z, vT); // apply the local transformation matrices lQ and lZ to A if (A != NULL) { starneig_small_right_gemm_update( 0, begin, begin, end, ldlZ, ldA, ldvT, lZ, A, vT); starneig_small_left_gemm_update( begin, end, end, n, ldlQ, ldA, ldhT, lQ, A, hT); } // apply the local transformation matrices lQ and lZ to B if (B != NULL) { starneig_small_right_gemm_update( 0, begin, begin, end, ldlZ, ldB, ldvT, lZ, B, vT); starneig_small_left_gemm_update( begin, end, end, n, ldlQ, ldB, ldhT, lQ, B, hT); } } void starneig_compute_complex_eigenvalue( int ldA, int ldB, double const *A, double const *B, double *real1, double *imag1, double *real2, double *imag2, double *beta1, double *beta2) { if (B != NULL) { extern void dlag2_(double const *, int const *, double const *, int const *, double const *, double*, double *, double *, double *, double *); extern double dlamch_(char const *); const double safmin = dlamch_("S"); double _real1, _real2, _beta1, _beta2, wi; dlag2_( A, &ldA, B, &ldB, &safmin, &_beta1, &_beta2, &_real1, &_real2, &wi); if (beta1) { *real1 = _real1; *real2 = _real2; *imag1 = wi; *imag2 = -wi; *beta1 = _beta1; *beta2 = _beta2; } else { *real1 = _real1/_beta1; *real2 = _real2/_beta2; *imag1 = wi/_beta1; *imag2 = -wi/_beta2; } } else { extern void dlanv2_( double *, double *, double *, double *, double *, double *, double *, double *, double *, double *); double a[] = { A[0], A[1], A[ldA], A[ldA+1] }; double cs, ss; dlanv2_( &a[0], &a[2], &a[1], &a[3], real1, imag1, real2, imag2, &cs, &ss); if (beta1) { *beta1 = 1.0; *beta2 = 1.0; } } }
{ "alphanum_fraction": 0.6115307538, "avg_line_length": 33.0969387755, "ext": "c", "hexsha": "16b4ee0ffbd54ced451064ad875366d3bd32e65e", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2020-04-14T09:41:23.000Z", "max_forks_repo_forks_event_min_datetime": "2019-04-30T12:14:12.000Z", "max_forks_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "NLAFET/StarNEig", "max_forks_repo_path": "src/common/math.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "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": "NLAFET/StarNEig", "max_issues_repo_path": "src/common/math.c", "max_line_length": 80, "max_stars_count": 12, "max_stars_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "NLAFET/StarNEig", "max_stars_repo_path": "src/common/math.c", "max_stars_repo_stars_event_max_datetime": "2021-12-24T12:30:19.000Z", "max_stars_repo_stars_event_min_datetime": "2019-04-28T17:13:04.000Z", "num_tokens": 2002, "size": 6487 }
#ifndef DEGNOME #define DEGNOME #include <stdlib.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> //Degnomedia Rogerus typedef struct Degnome Degnome; struct Degnome { double* dna_array; double hat_size; }; Degnome* Degnome_new(void); void Degnome_mate(Degnome* location, Degnome* p1, Degnome* p2, gsl_rng* rng, int mutation_rate, int mutation_effect, int crossover_rate); void Degnome_free(Degnome* q); int chrom_size; #endif
{ "alphanum_fraction": 0.7311827957, "avg_line_length": 20.2173913043, "ext": "h", "hexsha": "4e53e2a7e21ead866a8be37683f675daf73e8294", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-04-27T23:28:50.000Z", "max_forks_repo_forks_event_min_datetime": "2021-04-27T23:28:50.000Z", "max_forks_repo_head_hexsha": "4ef91b1d3cf00d9caca6c4fa2fb5c401a0f8d191", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Darokrithia/PolygenSim", "max_forks_repo_path": "src/degnome.h", "max_issues_count": 27, "max_issues_repo_head_hexsha": "4ef91b1d3cf00d9caca6c4fa2fb5c401a0f8d191", "max_issues_repo_issues_event_max_datetime": "2020-11-29T23:56:03.000Z", "max_issues_repo_issues_event_min_datetime": "2019-09-17T20:12:17.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Darokrithia/PopGenSim", "max_issues_repo_path": "src/degnome.h", "max_line_length": 77, "max_stars_count": 3, "max_stars_repo_head_hexsha": "4ef91b1d3cf00d9caca6c4fa2fb5c401a0f8d191", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Darokrithia/PolygenSim", "max_stars_repo_path": "src/degnome.h", "max_stars_repo_stars_event_max_datetime": "2019-02-01T18:53:36.000Z", "max_stars_repo_stars_event_min_datetime": "2018-08-14T20:45:40.000Z", "num_tokens": 125, "size": 465 }
/** * \author Sylvain Marsat, University of Maryland - NASA GSFC * * \brief C header for the initialization of the instrumental noise for LIGO/VIRGO detectors. * * */ #ifndef _LLVNOISE_H #define _LLVNOISE_H #define _XOPEN_SOURCE 500 #ifdef __GNUC__ #define UNUSED __attribute__ ((unused)) #else #define UNUSED #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include <complex.h> #include <time.h> #include <unistd.h> #include <getopt.h> #include <stdbool.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_bspline.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_min.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_complex.h> #include "constants.h" /************************************************************************/ /****** Global variables storing min and max f for the noise PSD *******/ extern double __LLVSimFD_LHONoise_fLow; extern double __LLVSimFD_LHONoise_fHigh; extern double __LLVSimFD_LLONoise_fLow; extern double __LLVSimFD_LLONoise_fHigh; extern double __LLVSimFD_VIRGONoise_fLow; extern double __LLVSimFD_VIRGONoise_fHigh; /**************************************************************************/ /****** Prototypes: functions loading and evaluating the noise PSD *******/ /* Function parsing the environment variable $LLV_NOISE_DATA_PATH and trying to run LLVSimFD_Noise_Init in each */ int LLVSimFD_Noise_Init_ParsePath(void); /* Function loading the noise data from a directory */ int LLVSimFD_Noise_Init(const char dir[]); /* The noise functions themselves */ double NoiseSnLHO(const double f); double NoiseSnLLO(const double f); double NoiseSnVIRGO(const double f); #if 0 { /* so that editors will match succeeding brace */ #elif defined(__cplusplus) } #endif #endif /* _LLVNOISE_H */
{ "alphanum_fraction": 0.6930469192, "avg_line_length": 25.2714285714, "ext": "h", "hexsha": "e1bbd48ba99036be2c54526496f793bfdbf6da0f", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_path": "LLVsim/LLVnoise.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "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": "titodalcanton/flare", "max_issues_repo_path": "LLVsim/LLVnoise.h", "max_line_length": 114, "max_stars_count": 3, "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_path": "LLVsim/LLVnoise.h", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "num_tokens": 438, "size": 1769 }
/*GENLIB library routines */ /* Compile progs: gcc -O3 -o prog prog.c ~/genlib.c -lm -lgsl -lgslcblas */ #include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #define pi 3.14159265358979 #define infinity 999999 #define true 1 #define false 0 #define maxranges 5 /* for numerical integration */ #define maxsimpsonpoints 1025 /* change libhdr if these changed */ #define MBIG 1000000000 #define MSEED 161803398 #define FAC (1.0/MBIG) #define ib1 1 #define ib2 2 #define ib5 16 #define ib18 131072 #define undefined -99999999999999.9999999 typedef double (*fun1)(); FILE *seedfileptr, *tmoutfile, *fopen(); int inputcounter=0; /* GSL random number definitions */ gsl_rng * gsl_rng_r; unsigned long int seed; int random_number_generator_initialised_flag = 0; long sseed; /* seed for the slow generator */ int tracelevel; struct acc { int n; double sum; double sumsq; }; struct covacc { int n; double sumxy, sumx, sumy, sumx2, sumy2; }; gabort(char *s, int r) { printf("ERROR %s %d\n", s, r); exit(1); } /* This is the random number generator ran3 from Numerical Recipes from Knuth. It's the fastest of the ``non-quick-and-dirty'' generators, and is supposed to have decent properties */ double uniform_old() { static int inext,inextp; static long ma[56]; static int iff=0; long mj,mk; double res; int i,ii,k; if(sseed<0||iff==0) { iff=1; mj=MSEED-(sseed<0?-sseed:sseed); mj%=MBIG; ma[55]=mj; mk=1; for(i=1;i<=54;i++) { ii=(21*i)%55; ma[ii]=mk; mk=mj-mk; if(mk<0) mk+=MBIG; mj=ma[ii]; } for(k=1;k<=4;k++) for(i=1;i<=55;i++) { ma[i] -=ma[1+(i+30)%55]; if(ma[i]<0) ma[i]+=MBIG; } inext=0; inextp=31; sseed=1; } if(++inext==56) inext=1; if(++inextp==56) inextp=1; mj=ma[inext]-ma[inextp]; if(mj<0) mj+=MBIG; ma[inext]=mj; sseed=mj; res = mj*FAC; if (res > 1.0) res = 1.0; else if (res < 0.0) res = 0.0; return res; } double uniform() { double res; if (!random_number_generator_initialised_flag) gabort("uniform() called, but !random_number_generator_initialised_flag", 0); res = gsl_ran_flat(gsl_rng_r,0.0,1.0); return(res); } int irbit1(unsigned long *iseed) /* routine to return random bits */ { unsigned long newbit; newbit = (*iseed &ib18) >> 17 ^ (*iseed &ib5) >> 4 ^ (*iseed &ib2) >> 1 ^ (*iseed &ib1); *iseed = (*iseed<<1) | newbit; return (int)newbit; } initialise_uniform_generator() { /* create a generator chosen by the environment variable GSL_RNG_TYPE */ const gsl_rng_type * T; // printf("initialise_uniform_generator\n"); gsl_rng_env_setup(); T = gsl_rng_default; gsl_rng_r = gsl_rng_alloc (T); random_number_generator_initialised_flag = 1; } getseed() { FILE *seedfileptr; static int c = 1; if (c==1) // first time routine called { initialise_uniform_generator(); c = 0; } printf("Enter seed (-99 to read from file) "); manual: scanf("%lu", &seed); if (seed == -99) { seedfileptr = fopen("seedfile", "r"); if (seedfileptr==0) { printf("No seedfile, enter seed please "); goto manual; } fscanf(seedfileptr, "%lu", &seed); // printf("Seed read %lu\n", seed); fclose(seedfileptr); } gsl_rng_set(gsl_rng_r, seed); } getseedquick() { FILE *seedfileptr; static int c = 1; if (c==1) // first time routine called { initialise_uniform_generator(); c = 0; } seedfileptr = fopen("seedfile", "r"); if (seedfileptr==0) { printf("No seedfile, enter seed please "); scanf("%lu", &seed); } else { fscanf(seedfileptr, "%lu", &seed); fclose(seedfileptr); } // printf("getseedquick: Seed read %lu\n", seed); gsl_rng_set(gsl_rng_r, seed); } terminate_uniform_generator() { gsl_rng_free(gsl_rng_r); } writeseed() { FILE *seedfileptr; double temp, x; x = uniform(); temp = floor(x*100000000); seed = (unsigned long int)temp; // printf("Write seed %lu\n", seed); seedfileptr = fopen("seedfile", "w"); fprintf(seedfileptr, "%lu\n", seed); fclose(seedfileptr); terminate_uniform_generator(); } initacc(a) struct acc *a; { a -> n = 0; a -> sum = 0; a -> sumsq = 0; } accum(struct acc *a, double x) { a->n = a->n + 1; a->sum = a->sum + x; a->sumsq = a->sumsq + x*x; } double accmean(struct acc *a) { return(a->sum/(double)(a->n)); } double variance(struct acc *a) { double num, denom; if (a->n == 0) return((double)-infinity); num = a->sumsq - (a->sum)*(a->sum)/((double)(a->n)); denom = (double)(a->n) - (double)1; return(num/denom); } /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! normal ! ------ ! Returns 2 random long reals from the standard normal distribution. ! ! Parameters: mu = mean ! sdev = standard deviation ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ double normal(double mu, double sdev) { double u1, u2, r; u1= uniform(); if (u1==0.0) u1 = 0.00001; /*prevent fatal error*/ if (u1==1.0) u1 = .999999; u2= uniform(); r = sqrt (-2.0*log(u1)) * cos(2.0*pi*u2); return(r*sdev + mu); } /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! quick normal ! ------------ ! Returns two uniform long reals from the normal distribution. ! ! Parameters: x1, x2 -> return values ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ quicknormal (double *x1, double *x2) { double u1, u2, r; u1= uniform(); if (u1==0.0) u1 = 0.00001; /*prevent fatal error*/ if (u1==1.0) u1 = .999999; u2 = uniform(); *x1 = sqrt (-2.0*log(u1)) * cos(2.0*pi*u2); *x2 = sqrt (-2.0*log(u1)) * sin(2.0*pi*u2); } /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! wishart ! ------- ! ! Returns two uniform real numbers from the wishart (bivariate) distribution. ! These are obtained by squaring correlated uniform numbers from the bivariate ! normal distribution. ! ! Parameters : z1 = return value for symmetrical distribution (i.e. metric) ! z2 = ,, ,, ,, negative sided distribution (i.e. fitness) ! epsilon1 = sqrt(E(z1*z1)) ! epsilon2 = sqrt(E(z2*z2)) ! rho = correlation of absolute values. ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ wishart(double *z1, double *z2, double epsilon1, double epsilon2, double rho) { double sq; rho = sqrt(rho); sq = 1/sqrt(3.0); quicknormal(z1, z2); *z2 = *z1*rho + *z2*sqrt(1.0 - rho*rho); *z1 = sq*epsilon1*(*z1)*(*z1); *z2 = -sq*epsilon2*(*z2)*(*z2); if (uniform() > 0.5) *z1 = -(*z1); } /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! bivnormal ! ------- ! ! Returns two real numbers from the bivariate normal distribution. ! ! Parameters : z1 = return value for symmetrical distribution (i.e. metric) ! z2 = ,, ,, ,, negative sided distribution (i.e. fitness) ! epsilon1 = sqrt(E(z1*z1)) ! epsilon2 = sqrt(E(z2*z2)) ! rho = correlation of absolute values. ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ bivnormal(double *z1, double *z2, double epsilon1, double epsilon2, double rho) { rho = sqrt(rho); quicknormal(z1, z2); *z2 = *z1*rho + *z2*sqrt(1.0 - rho*rho); *z1 = epsilon1*(*z1); *z2 = -epsilon2*(*z2); if (*z2 > 0.0) *z2 = -*z2; } cubenormal(z1, z2, epsilon1, epsilon2, rho) double *z1, *z2, epsilon1, epsilon2, rho; { double sq; sq = 1.0/sqrt(16.0); rho = sqrt(rho); quicknormal(z1, z2); *z2 = *z1*rho + *z2*sqrt(1.0 - rho*rho); *z1 = sq*epsilon1*(*z1)*(*z1)*(*z1); *z2 = -sq*epsilon2*(*z2)*(*z2)*(*z2); if (*z2 > 0.0) *z2 = -*z2; } /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! doublegamma ! ----------- ! ! Returns uniform long real from the double gamma distribution. ! ! Parameter: epsilon = sqrt(E(a*a)) ! proportion positive = proportion of distribution +ve ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ double doublegamma (epsilon, proppositive) double epsilon, proppositive; { double r, sigma; sigma = sqrt(epsilon*1.0/sqrt(3.0)); r= normal(0.0, sigma); r= r*r; if (uniform() > proppositive) r= -r; /*uniformly allocate sign*/ return(r); } double gamdev(int ia, double epsilon) /* returns random number from gamma distribution with integer parameter taken from Numerical Recipes in C */ { int j; double x; if ((ia<1)||(ia>=6)) gabort("Parameter to gamdev() invalid ", (double)ia); x = 1.0; for (j=1; j<=ia; j++) { x *= uniform(); } x = -log(x); x = (epsilon*x)/sqrt((double)(ia*(ia+1))); return x; } initcovacc(struct covacc *a) { a->n = 0; a->sumx = 0; a->sumy = 0; a->sumxy = 0; a->sumx2 = 0; a->sumy2 = 0; } covaccum(struct covacc *a, double x, double y) { a->n = a->n + 1; a->sumx = a->sumx + x; a->sumy = a->sumy + y; a->sumxy = a->sumxy + x*y; a->sumx2 = a->sumx2 + x*x; a->sumy2 = a->sumy2 + y*y; } double covariance(struct covacc *a) { if (a->n < 2) { return(-infinity); } return((a->sumxy - (a->sumx*a->sumy/(double)a->n))/((double)a->n - 1.0)); } double correlation(struct covacc *a) { double num, denom, cov, v1, v2; if (a->n < 2) { return(-infinity); } cov = covariance(a); num = a->sumx2 - (a->sumx)*(a->sumx)/((double)(a->n)); denom = (double)(a->n) - 1.0; v1 = num/denom; num = a->sumy2 - (a->sumy)*(a->sumy)/((double)(a->n)); denom = (double)(a->n) - 1.0; v2 = num/denom; return(cov/sqrt(v1*v2)); } double se(a) struct acc *a; { if (a->n < 1) return(-infinity); if (variance(a)/a->n < 0) return(-infinity); return(sqrt(variance(a)/a->n)); } printmse(s, r) char *s; struct acc *r; { printf("%s %f +/- %f\n", s, accmean(r), se(r)); } /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! generate poisson table ! ---------------------- ! ! generates a table of probabilities for each whole number given a poisson ! distribution. ! ! Parametes: mean = mean of poisson. ! last number = max. elements in table ! table -> table of probabilities. ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ generatepoissontable (double mean, int *lastnumber, double *table, int max) { int j; double prev; prev = exp(-mean); if (prev == 0) gabort("Insufficient resolution in generate poisson table", 0); table[0] = prev; for (j = 1; j <= max; j++) { *lastnumber = j; prev = prev*mean/(double)j; table[j] = table[j-1] + prev; if (1 - table[j] < 0.000001) break; } } /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! poisson ! ------- ! ! Looks up a table of probabilities of the poisson distribution already ! set up. Returns the index of this probability. This discrete vaue ! will come from the posson distribution. ! ! Parameters: last number = last entry in the table ! table -> table of probabilities ! ! Returns : integer from poisson distribution. ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ int poisson (int lastnumber, double *table) { int j; float u; u = uniform(); for (j = 0; j<=lastnumber; j++) { if ((double)u < table[j]) return(j); } return(lastnumber); } /*-------------------------------------------------------------------*/ /* binarysearchcumulative */ /* ---------------------- */ /* Assumes array contains a cumulative density function of a discrete*/ /* distribution. Returns an */ /* integer randomly drawn from the density function. */ /* Parameters array -> cdf. */ /* size = no. of elements in array [1..size] */ /*-------------------------------------------------------------------*/ int binarysearchcumulative(array, size) double *array; int size; { int cur, pre, post; double r; r = uniform(); /* printf("Uniform %f\n", r);*/ pre = 1; post = size; cur = (size + 1)/2; do { if (array[cur] < r) pre = cur; else post = cur; cur = (pre + post)/2; if ((cur==post) || (cur==pre)) { if (r < array[pre]) { /* printf("Returning pre %d\n", pre);*/ return(pre); } else { /* printf("Returning post %d\n", post);*/ return(post); } } } while (size > 0); } /*----------------------------------------------------------------------*/ /* */ /* discrete */ /* -------- */ /* */ /* Returns random integer in range 1..n with equal probability. */ /* Parameter: n = max. integer to return. */ /* */ /*----------------------------------------------------------------------*/ int discrete(int n) { int res; res = (int)(uniform()*(double)n) + 1; if (res<1) res = 1; else if (res>n) res = n; return(res); } /*----------------------------------------------------------------------*/ /* */ /* samplewithoutreplacement */ /* ------------------------ */ /* */ /* Returns a random integer from those present in array, which is valid */ /* from 1 to limit. Overwrites sampled integer with array[limit], */ /* then decrements limit. */ /* Parameters: limit -> no. valid integers in array */ /* array -> array[1..limit] of integers to sample */ /* */ /*----------------------------------------------------------------------*/ int samplewithoutreplacement(limit, array) int *limit, *array; { int index, res; index = discrete(*limit); res = array[index]; array[index] = array[*limit]; *limit = *limit - 1; return(res); } /* trap - asks for input to stop program */ trap() { int i; printf("Enter any int to continue\n"); scanf("%d", &i); } /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! getint; ! ------- ! ! Displays a prompt and reads in an integer. Checks the range of the integer ! and stops the program if it is out of range. ! ! Parameters: s -> string prompt ! i -> integer variable to input. ! min = max value ! max = min value. ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ getint(char *s, int *i, int min, int max) { printf("%s", s); scanf("%d", i); if ((min != -infinity) && (*i < min)) { printf("Value too small. Reading %s. Terminating.", s); printf("\n"); printf("Min allowable: "); printf("%d", min); printf("\n"); gabort("", 0); } if ((max != infinity) && (*i > max)) { printf("Value too large. Reading %s. Terminating.", s); printf("\n"); printf("Max allowable: "); printf("%d", max); printf("\n"); gabort("", 0); } } /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! getint and skip; ! ---------------- ! ! Displays a prompt and reads in an integer, skipping ! to the end of the line. Checks the range of the integer ! and stops the program if it is out of range. ! ! Parameters: s -> string prompt ! i -> integer variable to input. ! min = max value ! max = min value. ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ getintandskip(char *s, int *i, int min, int max) { char ch; printf(s); printf(" "); scanf("%d", i); do { ch = getchar(); } while (ch != '\n'); if ((min != -infinity) && (*i < min)) { printf("Value too small. Reading %s. Terminating.", s); printf("\n"); printf("Min allowable: "); printf("%d", min); printf("\n"); gabort("", 0); } if ((max != infinity) && (*i > max)) { printf("Value too large. Reading %s. Terminating.", s); printf("\n"); printf("Max allowable: "); printf("%d", max); printf("\n"); gabort("", 0); } } /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ printreal(s,r, x, y) char *s; double r; int x, y; { printf("%s %f\n", s, r); } /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! printint; ! --------- ! ! Prints out the integer with leading spaces x after the string s. ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ printint (s, i, x) char *s; int i, x; { printf("%s %d", s, i); printf("\n"); } /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! print tail ! ---------- ! ! Prints a line of dashes. ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ printtail() { int j; printf("\n"); for (j=1; j<=80; j++) { printf("-"); } printf("\n\n"); } /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! cointoss ! -------- ! ! Uses random number to return false with probability 0.5 otherwise ! returns a non zero integer. ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ int cointoss() { if (uniform() > 0.5) return(0); return(1); } /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! printline ! ---------- ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ printline (s) char *s; { printf(s); printf("\n"); } spaces(n) int n; { int i; for (i=1; i<=n; i++) printf(" "); } /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! getreal and skip; ! ---------------- ! ! Displays a prompt and reads in an real, skipping ! to the end of the line. Checks the range of the integer ! and stops the program if it is out of range. ! ! Parameters: s -> string prompt ! i -> integer variable to input. ! min = max value ! max = min value. ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ getrealandskip(char *s, double *i, double min, double max) { char ch; printf(s); printf(" "); scanf("%lf", i); do { ch = getchar(); } while (ch != '\n'); if ((min != -infinity) && (*i < min)) { printf("Value too small. Reading %s. Terminating.", s); printf("\n"); printf("Min allowable: "); printf("%f", min); printf("\n"); gabort("", 0); } if ((max != infinity) && (*i > max)) { printf("Value too large. Reading %s. Terminating.", s); printf("\n"); printf("Max allowable: "); printf("%f", max); printf("\n"); gabort("", 0); } } double calculaterealmean(double *a, int n) { double sum; int i; sum = 0.0; for (i=1; i<=n; i++) { sum = sum + a[i]; } return(sum/(double)n); } tracestart() { printf("Enter trace level "); scanf("%d", &tracelevel); } trace(s, i) { if (tracelevel==0) return(0); printf("%s %d\n", s, i); } outputrep(int j, int howoften) { if ((double)j/(double)howoften - floor((double)j/(double)howoften) == 0.0) printf("Completed iteration %d\n", j); } outputrepdot(int j, int reps) { int howoften; howoften = reps/10; if ((double)j/(double)howoften - floor((double)j/(double)howoften) == 0.0) { printf("%d.", j/howoften); if (j==reps) printf("\n"); fflush(stdout); } } monitorinput() { inputcounter--; if (inputcounter <= 0) { printf("Enter int to continue "); scanf("%d", &inputcounter); } } double normalheight(double x, double mu, double var) { double res; res = (1.0/sqrt(2.0*pi*var))*exp(-(x-mu)*(x-mu)/(2.0*var)); return(res); } /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! simpson ! ------- ! ! Computes the area under the function using simpsons rule for the set of ! points given. ! ! Parameters: x -> array of pairs of points. ! points = no. of points. ! a = lower value ! v = upper value ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ double simpson (double *x, int points, double a, double b) { int j, coeff; double res, h; if (2*(points/2) == points) { printf("FATAL ERROR: Even no. of points for SIMPSON.\n"); monitorinput(); } h = (b-a) / ((double)points-1.0); res = 0.0; for (j = 1; j<=points; j++) { if ((j == points) || (j==1 )) { coeff = 1; } else if (j == 2) { coeff = 4; } else if (coeff == 2) coeff = 4; else coeff = 2; /* %if trace level > 0 %then printstring("Coeff, x(j) ") %and write(coeff, 3) %and print(x(j), 2, 4) %and newline*/ res = res + (double)coeff*x[j]; } return((h/3.0) * res); } int odd(int i) { int x; x = i/2; if ((double)(i)/2.0 - (double)x == 0.0) return(false); else return(true); } /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! solve quadratic ! --------------- ! ! Returns the roots of quadratic of parameters given. ! ! Parameters: a, b, c = parameters of quadratic. ! root1, root2 = roots of quadratic. ! ! Returns : true => real roots. ! false => no real root. ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ int solvequadratic(double a, double b, double c, double *r1, double *r2) { double x; x = b*b - 4.0*a*c; if (x < 0.0) return(false); *r1 = (-b + sqrt(x))/(2.0*a); *r2 = (-b - sqrt(x))/(2.0*a); return(true); } int skiptoendofline(FILE *fptr) { int status; char ch; do { status = fscanf(fptr, "%c", &ch); if (status==EOF) break; /* printf("skiptoendofline ch %c\n", ch);*/ } while (ch!='\n'); return(status); } /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1 ! ! aitken ! ------ ! ! Uses Aitken's formula to predict the asymptote from the three last points ! in the array given. ! ! Parameters: x-> array of points. ! t = max. point in array. ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ double aitken (double *a, int t) { double x; x = a[t-2] - 2.0*a[t-1] + a[t]; if (x == 0) return(a[t]); return(-((a[t-1] - a[t])*(a[t-1] - a[t]))/x + a[t]); } int factorial(int i) { int res; res = 1; for (;;) { if (i==0) break; res = res*i; i--; } return(res); } double doublefactorial(double x) { double res; x = floor(x); res = 1.0; for (;;) { if (x==0.0) break; res = res*x; x = x - 1.0; } return(res); } double logdoublefactorial(double x) { double res; x = floor(x); res = 0.0; for (;;) { if (x==0.0) break; res = res + log(x); x = x - 1.0; } return(res); } /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! gammaalpha ! ---------- ! ! Returns the value of the parameter alpha of the gamma function. ! ! ! Parameters: beta = parameter of gamma func. ! epsilon = sqrt(E(a*a)) ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ double gammaalpha( beta, epsilon) double beta, epsilon; { double res; res = sqrt(beta*(beta + 1.0))/epsilon; return(res); } double asymptote_gamma(double z) { double res; res = (z - 0.5)*log(z) -z +0.5*log(2.0*pi) + 1.0/(12.0*z) - 1.0/(360.0*z*z*z) + 1.0/(1260.0*z*z*z*z*z) - 1.0/(1680.0*z*z*z*z*z*z*z); return(exp(res)); } double series_gamma(double z) /* return gamma(z) using series expansion 6.1.34 of Abramowitz and Stegun */ { #define maxc 26 double c[maxc+1], res; int i; if (z > 2.0) return(asymptote_gamma(z)); c[1] = 1.0; c[2] = 0.5772156649015329; c[3] =-0.6558780715202538; c[4] =-0.0420026350340952; c[5] = 0.1665386113822915; c[6] =-0.0421977345555443; c[7] =-0.0096219715278770; c[8] = 0.0072189432466630; c[9] =-0.0011651675918591; c[10]=-0.0002152416741149; c[11]= 0.0001280502823882; c[12]=-0.0000201348547807; c[13]=-0.0000012504934821; c[14]= 0.0000011330272320; c[15]=-0.0000002056338417; c[16]= 0.0000000061160950; c[17]= 0.0000000050020075; c[18]=-0.0000000011812746; c[19]= 0.0000000001043427; c[20]= 0.0000000000077823; c[21]=-0.0000000000036968; c[22]= 0.0000000000005100; c[23]=-0.0000000000000206; c[24]=-0.0000000000000054; c[25]= 0.0000000000000014; c[26]= 0.0000000000000001; res = 0.0; for (i=1; i<=26; i++) { res += c[i]*pow(z, (double)i); /* printf("gamma(z) %15.12f\n", 1.0/res); */ } return(1.0/res); } /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! gammaht ! ------- ! ! Returns the height at point a of a gamma distribution. ! ! Parameters: epsilon, beta = gamma parameters. ! a = value to evaluate. ! ! Returns gamma fn. ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ double gammaht(double epsilon, double beta, double a) { double gammabeta, res, a1, a2, a3, alpha; if (a==0.0) { printf("Illegal value (0.0) for gammaht()\n"); monitorinput(); } if (beta < 0.0) gabort("gammaht: invalid beta\n", beta); alpha = gammaalpha(beta, epsilon); gammabeta = series_gamma(beta); a1 = pow(alpha, beta); a2 = exp(-alpha*a); a3 = pow(a, beta - 1.0); res = a1*a2*a3/gammabeta; return(res); } /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! half points ! ----------- ! ! This routine is called to check that the simpson numerical integration ! is converging satisfactorily. It halves the number of points in ! the array specified. ! ! Parameters: a -> array of points. ! points -> no. of points. ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ halfpoints(double *a, int *points) { int ptr1, ptr2, newpoints; if (odd(*points)==false) { printf("Half points: ERROR: no. of points for simpson must be odd.35\n"); monitorinput(); } ptr1 = 1; ptr2 = 1; do { a[ptr1] = a[ptr2]; newpoints = ptr1; ptr1++; ptr2 = ptr2 + 2; } while (ptr2 <= *points); *points = newpoints; } setuppoints(int pts, double *points, double lower, double upper, fun1 fn) { int i; double interval, x, a; interval = (upper - lower)/((double)pts - 1.0); x = lower; for (i = 1; i<=pts; i++) { a = fn(x); points[i] = a; x = x + interval; } } /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1 ! ! numerical integ ! --------------- ! ! Numerically integrates the function fn and returns the result in res. ! Integrates over a number of ranges with different numbers of points per ! range. Points must be a number like 65, 129, 257, 513... in each ! range. Halves number of points to do integration 3 times as a check on ! convergence ! ! Parameters: ! ! ! resvec: contains vector of result for different numbers of points ! start, finish: values limiting the function ! fn(x): is the function to integrate ! ranges: no. of ranges of points to evaluate. ! points per range: no of points in each range. ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ double numericalinteg(double *resvec, double start, double finish, fun1 fn, int ranges, int *pointsperrange) { double lower, upper, r; double res[maxranges+2][4]; /* The first dimension is contains the integral for each range, the last element containing the total. The second dimension contains results for each halving of the points. */ double points[maxsimpsonpoints+1]; int i, j, k, fac, p; static int tmoutfileflag = 0; if (tmoutfileflag==0) { /* tmoutfile = fopen("numericalinteg.out", "w");*/ tmoutfileflag = 1; } /* printf("Start %f, finish %f, ranges %d\n", start, finish, ranges);*/ upper = start; for (i = 1; i<= ranges; i++) { lower = upper; upper = lower + (finish - start)/(double)ranges; p = pointsperrange[i]; if (p > maxsimpsonpoints) gabort("too many points for simpson",p); setuppoints(p, points, lower, upper, fn); for (j = 1; j<=3; j++) { r = simpson(points, p, lower, upper); res[i][j] = r; if (j != 3) halfpoints(points, &p); } } for (i = 1; i<=3; i++) { res[ranges+1][i] = 0.0; for (j = 1; j<=ranges; j++) res[ranges+1][i] = res[ranges+1][i] + res[j][i]; resvec[i] = res[ranges+1][i]; } /* fprintf(tmoutfile, "Results of numerical integration\n"); for (i=1; i<=ranges; i++) fprintf(tmoutfile, " Pts Range %d", i); fprintf(tmoutfile, " All"); fprintf(tmoutfile, "\n"); */ fac = 1; /* for (i = 1; i<=3; i++) { for (j = 1; j<=ranges+1; j++) { if (j!=ranges+1) fprintf(tmoutfile, "%4d", (pointsperrange[j]-1)/fac + 1); fprintf(tmoutfile, "%10.4f", res[j][i]); } fac = fac*2; fprintf(tmoutfile, "\n"); } */ return(res[ranges+1][1]); } FILE *openforread(char *str) { FILE *f; f = fopen(str, "r"); if (f==0) { printf("ERROR: File %s not found.\n", str); exit(0); } else //printf("Opened file %s for read.\n", str); return(f); } FILE *openforwrite(char *str, char *mode) { FILE *f; f = fopen(str, mode); if (f==0) { printf("ERROR: Unable to open file %s for write.\n", str); exit(0); } else //printf("Opened file %s for write, ", str); if (mode[0]=='a') printf("append mode.\n"); else if (mode[0]=='w') printf("overwrite mode.\n"); else gabort("Invalid mode given in openforwrite\n", 0); return(f); } FILE *openforreadsilent(char *str) { FILE *f; f = fopen(str, "r"); if (f==0) { printf("ERROR: File %s not found.\n", str); exit(0); } return(f); } FILE *openforwritesilent(char *str, char *mode) { FILE *f; f = fopen(str, mode); if (f==0) { printf("ERROR: Unable to open file %s for write.\n", str); exit(0); } if (mode[0]=='a') { } else if (mode[0]=='w') { } else gabort("Invalid mode given in openforwrite\n", 0); return(f); } printmsefile(f, s, r) FILE *f; char *s; struct acc *r; { fprintf(f, "%s %f +/- %f\n", s, accmean(r), se(r)); } quadratic_regression(double n, double sumx, double sumx2, double sumy, double sumx3, double sumxy, double sumx4, double sumx2y, double *b1, double *b2, double *b3) { /* Solve system of 3 simultaneous equations: a*b1 + b*b2 + c*b3 = d (1) e*b1 + f*b2 + g*b3 = h (2) i*b1 + j*b2 + k*b3 = l (3) The actual parameters are appropriate for solving a quadratic regression - y = b3*x^2 + b2*x + b3 See assignments below. */ double a, b, c, d, e, f, g, h, i, j, k, l; double z1, z2, z3, z4, z5, z6; a = n; b = sumx; c = sumx2; d = sumy; e = b; f = c; g = sumx3; h = sumxy; i = c; j = g; k = sumx4; l = sumx2y; /* printf("\n%lf %lf %lf %lf\n", a, b, c, d); printf("%lf %lf %lf %lf\n", e, f, g, h); printf("%lf %lf %lf %lf\n\n", i, j, k, l); */ /* (1) - (2) -> b1*z1 + b2*z2 = z3 (4) */ z1 = a/c - e/g; z2 = b/c - f/g; z3 = d/c - h/g; /* (1) - (3) -> b1*z4 + b2*z5 = z6 (5) */ z4 = a/c - i/k; z5 = b/c - j/k; z6 = d/c - l/k; /* (4) - (5) */ *b1 = (z3/z2 - z6/z5)/(z1/z2 - z4/z5); *b3 = ((d - a*(*b1))/b - (h - e**b1)/f) / (c/b - g/f); *b2 = (d - c*(*b3) - a*(*b1))/b; } int findtext(char *s, FILE *inptr) { int len, i, curchar, dum; char c; curchar = 0; len = 0; for (i=0; i<=100; i++) { if (s[i] == '\0') break; len++; } for (;;) { c = getc(inptr); if (c == EOF) return(false); if (c==s[curchar]) { curchar++; if (curchar==len) return(true); } else curchar = 0; } } /* FIND1DMAX */ /* Finds the maximum of 3 points using a quadratic approximation */ find1dmax(double *xvec, double *yvec, double *xmax, double *ymax) { int i; double a, b, c, x1, x2, x3, y1, y2, y3, temp; double num, denom; /* for (i=1; i<=3; i++) { printf("xvec[%1d] %lf yvec[%1d] %lf\n", i, xvec[i], i, yvec[i]); } */ x1 = xvec[1]; x2 = xvec[2]; x3 = xvec[3]; y1 = yvec[1]; y2 = yvec[2]; y3 = yvec[3]; if (y1==y3) y1+= 0.000000000000001; if (y3==y2) y2+= 0.0000000000000001; /* printf("x1 %f x2 %f x3 %f y1 %f y2 %f y3 %f\n", x1, x2, x3, y1, y2, y3);*/ num = (y1 - y3)*(x1 - x2)/(x1 - x3) - y1 + y2; denom = (x1*x1 - x3*x3)*(x1 - x2)/(x1 - x3) - (x1*x1 - x2*x2); a = num/denom; num = y1 - y2 - a*(x1*x1 - x2*x2); b = num/(x1 - x2); c = y1 - a*x1*x1 - b*x1; temp = -b/(2.0*a); *xmax = temp; *ymax = a*temp*temp + b*temp + c; } /* FIND2DMAX */ /* Finds the maximum of a 3x3 grid using a sequential quadratic approximation */ double find2dmax(double *xvec, double *yvec, double zmatrix[4][4], double *xmax, double *ymax) { int i, j; double vec[4], vec1[4], temp, max, max1, max2; /* for (i=1; i<=3; i++) { for (j=1; j<=3; j++) { if (zmatrix[i][j]==undefined) return(undefined); } } */ /* find the maximum for columns */ for (i=1; i<=3; i++) { for (j=1; j<=3; j++) { vec[j] = zmatrix[i][j]; } find1dmax(yvec, vec, &temp, &max); /* printf("Find1smax: zmax %lf ymax %lf\n", max, temp);*/ vec1[i] = max; } find1dmax(xvec, vec1, xmax, &max1); /* printf("Columns: max %lf xmax %lf\n", max1, *xmax);*/ /* find the maximum for rows */ for (i=1; i<=3; i++) { for (j=1; j<=3; j++) { vec[j] = zmatrix[j][i]; } find1dmax(xvec, vec, &temp, &max); /* printf("Find1dmax: zmax %lf ymax %lf\n", max, temp);*/ vec1[i] = max; } find1dmax(yvec, vec1, ymax, &max2); /* printf("Rows: max %lf ymax %lf\n", max2, *ymax);*/ max = (max1 + max2)/2.0; return(max); } int bnldev(double pp, int n) { int j, bnl; double p; p = (pp < 0.5 ? pp : 1.0 - pp); bnl = 0; for (j=1; j<=n; j++) if (uniform() < p) ++bnl; if (p!=pp) bnl = n - bnl; return bnl; } void metropolis(double y[], int ndim, double(*func)(double []), int limit, double delta[], double prevres, double *temperature) { #define step_change 0.2 int i, j, param, accept; double step, res, diff, u; param = 0; *temperature = 1.0; for (i=1; i<=limit; i++) { /* printf("%d ", i);*/ param++; if (param > ndim) param = 1; step = normal(0.0, delta[param]); /* printf("param %d delta[param] %lf, step %lf\n", param, delta[param], step);*/ y[param] += step; res = (*func)(y); if (res > prevres) { diff = prevres - res; u = uniform(); /* printf("diff %lf, exp(diff) %lf, u %lf\n", diff, exp(diff), u);*/ if (u < pow(exp(diff), 1.0/(*temperature))) { accept = true; /* printf("Accepted\n");*/ } else { accept = false; /* printf("Rejected\n");*/ } } else { accept = true; /* printf("Accepted unconditionally\n");*/ } if (accept == true) /* Note assume to be minimizing not maximizing */ { prevres = res; /* accept the change */ delta[param] *= (1.0 + step_change); /* Increase the step size */ } else { y[param] -=step; /* reject the change */ delta[param] *= (1.0 - step_change); /* Decrease the step size */ } /* printf("Dump of delta vector: "); for (j=1; j<=ndim; j++) { printf("%lf ", delta[j]); } printf("\n"); monitorinput(); */ *temperature -= 2.0/(double)limit; if (*temperature < 0.001) *temperature = 0.001; } } /* A slower way of generating poissons that the tabular method in poisson */ int genpoisson(double xm) { static double sq, alxm, g, oldm = (-1.0); double em, t, y; // if (xm>300) gabort("genpoisson: xm too large", 0); if (xm>=200.0) /* Use normal generator for very high xm */ { return normal(0.0, sqrt(xm)) + xm; } if (xm!=oldm) { oldm = xm; g = exp(-xm); } em = -1; t = 1.0; do { ++em; t *= uniform(); } while (t > g); return em; } void qsortreals (double *a, int from, int to) { int l, v; double d; if (from >= to) return; l = from; v = to; d = a[v]; for (;;) { while ((l < v) && (a[l] <= d)) { l = l + 1 ; } if (l==v) break; a[v] = a[l]; while ((v > l) && (a[v] >= d)) { v = v - 1; } if (v==l) break; a[l] = a[v]; } /* ! now l=v*/ a[v] = d; l = l-1; v = v+1; qsortreals(a, from, l); qsortreals(a, v, to); } #define maxofrs 100 FILE *openfilecheck2dir(char *str) /* Attempts to open file str, if fails first time attempts to open ../str or ../../str */ { FILE *f; static char s[maxofrs]; int i; f = fopen(str, "r"); if (f==0) { s[0] = '.'; s[1] = '.'; s[2] = '/'; i=0; for (;;) { if (i+3 > maxofrs) gabort("String too long", i); s[i+3] = str[i]; if (str[i] == '\0') break; i++; } f = fopen(s, "r"); if (f==0) { s[0] = '.'; s[1] = '.'; s[2] = '/'; s[3] = '.'; s[4] = '.'; s[5] = '/'; i=0; for (;;) { if (i+6 > maxofrs) gabort("String too long", i); s[i+6] = str[i]; if (str[i] == '\0') break; i++; } f = fopen(s, "r"); if (f==0) { printf("ERROR: File %s not found.\n", str); exit(0); } else printf("Opened file %s for read.\n", s); } else printf("Opened file %s for read.\n", s); } else printf("Opened file %s for read.\n", str); return(f); } float rtsafe(void (*funcd)(float, float *, float *), float x1, float x2, float xacc) { #define MAXIT 100 int j; float df, dx, dxold, f, fh, fl; float temp, xh, xl, rts; (*funcd)(x1, &fl, &df); (*funcd)(x2, &fh, &df); if ((fl > 0.0 && fh > 0.0) || (fl < 0.0 && fh < 0.0)) gabort("Rtsafe: roots must be bracketed", 0); if (fl == 0.0) return(x1); if (fh == 0.0) return(x2); if (fl < 0.0) { xl = x1; xh = x2; } else { xh = x1; xl = x2; } rts = 0.5*(x1+x2); dxold = fabs(x2-x1); dx = dxold; (*funcd)(rts, &f, &df); for (j=1; j<=MAXIT; j++) { if ((((rts-xh)*df-f)*((rts-xl)*df-f) >=0.0) || (fabs(2.0*f) > fabs(dxold*df))) { dxold = dx; dx = 0.5*(xh-xl); rts = xl +dx; if (xl==rts) return rts; } else { dxold = dx; dx = f/df; temp = rts; rts -= dx; if (temp==rts) return (rts); } if (fabs(dx) < xacc) return rts; (*funcd)(rts, &f, &df); if (f < 0.0) xl = rts; else xh = rts; } printf("warning: rtsafe: Maximum interations exceeded\n"); monitorinput(); return (rts); } /* Algorith to generate bivariate normal deviates provided by Ian White */ bivariatenormal(double *z1, double *z2, double var1, double var2, double cov) { double s; quicknormal(z1, z2); /* uncorrelated normal deviates mean 0 SD 1 */ *z1 *= sqrt(var1); /* Scale Z1 according to the standard deviation */ s = var2 - cov*cov/var1; if (s<0) gabort("Invalid parameters for bivnormal", s); *z2 = (cov/var1)*(*z1) + sqrt(s)*(*z2); } get_silent_mode(int argc, char *argv[], int *silent_mode) { int n_command_line_param, i; *silent_mode = 0; n_command_line_param = argc; // printf("n_command_line_param %d\n", n_command_line_param); for (i=1; i<n_command_line_param; i++) { // printf("argv[%d] %s\n", i, argv[i]); } if (n_command_line_param==2) { if (strcmp(argv[1], "-s")==0) { // printf("Silent mode switched on\n"); *silent_mode = 1; } } } make_numbered_file_name(char *outfilename, char *filestr, int ind) { int len, i; int i1; char ch; len = strlen(filestr); for (i=0; i<len; i++) outfilename[i] = filestr[i]; if (ind > 99) gabort("makefilename: file index too large", ind); if (ind > 9) { i1 = ind/10; ch = i1 + '0'; outfilename[len] = ch; // printf("Char 1 ind %d i1 %d ch %c\n", ind, i1, ch); monitorinput(); i1 = ind - (ind/10)*10; ch = i1 + '0'; // printf("Char 2 ind %d i1 %d ch %c\n", ind, i1, ch); monitorinput(); outfilename[len+1] = ch; outfilename[len+2] = '\0'; } else { ch = ind + '0'; // printf("Char 1 ind %d i1 %d ch %c\n", ind, i1, ch); monitorinput(); outfilename[len] = ch; outfilename[len+1] = '\0'; } // printf("makefilename: results %s\n", outfilename); } // -------------------------------------------------------------------- // Routine for grid searching a function f that takes integer values as // it's paramters // -------------------------------------------------------------------- double fill_out_grid(double **grid, int x0, int x1, int y0, int y1, int step_size_x, int step_size_y, double (*f)(int, int), int *max_x, int *max_y, int *nfunc) { double max_fun, f_result; int i, j, evaluated; *max_x = -1; *max_y = -1; max_fun = undefined; i = x0; for (;;) { j = y0; for (;;) { evaluated = 0; if (grid[i][j]==undefined) { f_result = (*f)(i, j); (*nfunc)++; grid[i][j] = f_result; evaluated = 1; } else f_result = grid[i][j]; // printf("i %d j %d f_result %lf ", i, j, f_result); // if (evaluated == 1) printf("evaluated\n"); // else printf("not evaluated\n"); if ((f_result > max_fun)||(max_fun==undefined)) { max_fun = f_result; *max_x = i; *max_y = j; } if (j==y1) break; j += step_size_y; if (j > y1) j = y1; } if (i==x1) break; i += step_size_x; if (i > x1) i = x1; } return max_fun; } int_to_string(int v, char *str, int max_len) { int divisor = 10000000, i1, ind = 0, digit_encountered = 0; char ch; if (v > divisor) gabort("int_to_string: integer parameter to large", v); for (;;) { i1 = v/divisor; // printf("i1 %d divisor %d\n", i1, divisor); if (i1 >= 0) { ch = i1 + '0'; if (ch!='0') digit_encountered = 1; // printf("ch %c\n", ch); if (digit_encountered) { str[ind] = ch; ind++; if (ind == max_len) gabort("int_to_string: string too long", ind); } v = v - i1*divisor; } divisor /= 10; if (divisor == 1) break; // monitorinput(); } ch = v + '0'; // printf("ch %c\n", ch); str[ind] = ch; ind++; if (ind == max_len) gabort("int_to_string: string too long", ind); str[ind] = '\0'; } // bilinear_interpolation: // First 4 parameters are positions on x and y axes // Second 4 are function values // x and y are positions to be evaluated. double bilinear_interpolation(double x1, double x2, double y1, double y2, double x1y1, double x1y2, double x2y1, double x2y2, double x, double y) { double res; res = (x2 - x)*(y2 - y)*x1y1 + (x - x1)*(y2 - y)*x2y1 + (x2 - x)*(y - y1)*x1y2 + (x - x1)*(y - y1)*x2y2; res /= ((x2 - x1)*(y2 - y1)); return res; } // -------------------- // kimura_fixation_prob // -------------------- // Returns fixation probability of an additive mutation, assuming that s // is small in a diploid population // // Parameters // --------- // s - selection coefficient, difference between the homozygotes. // N - Population effective size. // double kimura_fixation_prob(double s, int N) { double num, denom; if ((s < 0.0)&&((double)N*s > -0.0000001)) // Trap numerical problems { num = 1.0; denom = 2.0*(double)N; } else if ((s > 0.0)&&((double)N*s < 0.0000001)) { num = 1.0; denom = 2.0*(double)N; } else { num = 1 - exp(-s); denom = 1 - exp(-2*(double)N*s); } // printf("s %14.14lf N %d num %lf denom %lf num/denom %lf\n", /// s, N, num, denom, num/denom); // monitorinput(); return num/denom; } // -------------------- // kimura_fixation_prob // -------------------- // Returns fixation probability of an additive mutation, assuming that s // is small in a diploid population // // Parameters // --------- // s - selection coefficient, difference between the homozygotes. // N - Population effective size. // double kimura_fixation_prob_X_loci(double s, int N) { double num, denom; if ((s < 0.0)&&((double)N*s > -0.0000001)) // Trap numerical problems { num = 1.0; denom = 2.0*(double)N; } else if ((s > 0.0)&&((double)N*s < 0.0000001)) { num = 1.0; denom = 2.0*(double)N; } else { num = 1 - exp(-s); denom = 1 - exp(-2*(double)N*s); } // printf("s %14.14lf N %d num %lf denom %lf num/denom %lf\n", /// s, N, num, denom, num/denom); // monitorinput(); return num/denom; } //---------------------------------------- // normal_cumulative_probability_function // --------------------------------------- // // Returns the area under the normal pdf from -infinity to x. // From algorithm described in Abramowitz and Stegun. double normal_cumulative_probability_function(const double x) { const double b1 = 0.319381530; const double b2 = -0.356563782; const double b3 = 1.781477937; const double b4 = -1.821255978; const double b5 = 1.330274429; const double p = 0.2316419; const double c = 0.39894228; if(x >= 0.0) { double t = 1.0 / ( 1.0 + p * x ); return (1.0 - c * exp( -x * x / 2.0 ) * t * ( t *( t * ( t * ( t * b5 + b4 ) + b3 ) + b2 ) + b1 )); } else { double t = 1.0 / ( 1.0 - p * x ); return ( c * exp( -x * x / 2.0 ) * t * ( t *( t * ( t * ( t * b5 + b4 ) + b3 ) + b2 ) + b1 )); } } //---------------------------------------- // dump_matrix //---------------------------------------- // // Prints out the matrix X with 1..rows, 1..cols rows and columns, respectively. // // s -> string to print // X -> matrix, usually allocated using dmatrix(), dimension rows, cols // rows = rows, 1 relative // cols = cols, 1 relative dump_matrix(char *s, double **X, int rows, int cols) { int i, j; printf ("%s\n", s); for (i = 1; i <=rows; i++) { for (j = 1; j <= cols; j++) { printf("%lf ", X[i][j]); } printf("\n"); } } //---------------------------------------- // compute_matrix_transpose //---------------------------------------- // // Generates the transpose of X. // // X -> matrix, usually allocated using dmatrix(), dimension rows, cols // rows = rows of X, 1 relative // cols = cols of X, 1 relative // XT -> result matrix, allocated using dmatrix(), dimension cols, rows compute_matrix_transpose(double **X, double **XT, int rows, int cols) { int i, j; for (i=1; i<=rows; i++) { for (j=1; j<=cols; j++) { XT[j][i] = X[i][j]; } } } //---------------------------------------- // multiply_matrices //---------------------------------------- // // Carry out matrix operation XY, putting result in RES. // // RES -> result matrix dimension rows_X, cols_X, usually allocated using // dmatrix() // X -> matrix dimension rows_X, cols_X, usually allocated using dmatrix() // Y -> matrix dimension rows_Y, cols_Y, usually allocated using dmatrix() // rows_X = rows of X, 1 relative // cols_X = cols of X, 1 relative // rows_Y = rows of Y, 1 relative // cols_Y = cols of Y, 1 relative multiply_matrices(double **RES, double **X, double **Y, int rows_X, int cols_X, int rows_Y, int cols_Y) // Matrix X has dimension rows_X, cols_X and Y has dimension rows_Y, cols_Y. The // result has dimension rows_X, cols_Y. { int i, j, k; double element; if (cols_X != rows_Y) { gabort("multiply_matrices: cols_X != rows_Y", 0); } // printf("multiply_matrices: rows_X %d cols_X %d\n", rows_X, cols_X); // dump_matrix("multiply_matrices: Matrix X", X, rows_X, cols_X); // monitorinput(); // printf("multiply_matrices: rows_Y %d cols_Y %d\n", rows_Y, cols_Y); // dump_matrix("multiply_matrices: Matrix Y", Y, rows_Y, cols_Y); // monitorinput(); for (i=1; i<=rows_X; i++) { for (j=1; j<=cols_Y; j++) { element = 0.0; for (k=1; k<=cols_X; k++) { // printf("X[%d][%d] %lf X[%d][%d] %lf\n", // i, k, X[i][k], k, j, Y[k][j]); element += X[i][k]*Y[k][j]; // printf("i %d j %d k %d element %lf\n", i, j, k, element); // monitorinput(); } // printf("RES[%d][%d] %lf\n", i, j, element); monitorinput(); RES[i][j] = element; } } } // ---------------------------------------------- // normal_approx_to_binomial // ---------------------------------------------- // // Uses the normal approximation to calculate the probability of i successes // from n trials if the probabilituy of one sucess is p double normal_approx_to_binomial(int i, int n, double p) { double m, s, z_upper, z_lower, area_lower, area_upper; m = p*(double)n; s = sqrt((1.0-p)*p*(double)n); // printf("m %lf s %lf\n", m, s); z_lower = ((double)i - 0.5 - m)/s; area_lower = normal_cumulative_probability_function(z_lower); z_upper = ((double)i + 0.5 - m)/s; area_upper = normal_cumulative_probability_function(z_upper); // printf("z_lower %lf area_lower %lf z_upper %lf area_upper %lf\n", // z_lower, area_lower, z_upper, area_upper); return(area_upper - area_lower); } // ---------------------------------------------- // loadparam // paramvec = vector with 2 elements: element 0 = 0 => parameter not variable // element 0 = 1 => parameter variable // element 1 location to get parameter value // curpos = index - 1 from which to load parameter // p: matrix into which parameter loaded // loadparam(double *paramvec, int *curpos, double **p) { if (paramvec[0]!=0.0) { *curpos = *curpos + 1; p[1][*curpos] = paramvec[1]; } } // ---------------------------------------------- // unloadparam // paramvec = vector with 2 elements: element 0 = 0 => parameter not variable // element 0 = 1 => parameter variable // curpos = index -1 in which to unload parameter // x = vector containing parameter value unloadparam(double *paramvec, int *curpos, double x[]) { if (paramvec[0]!=0.0) { *curpos = *curpos + 1; paramvec[1] = x[*curpos]; } }
{ "alphanum_fraction": 0.4868127643, "avg_line_length": 22.6567944251, "ext": "c", "hexsha": "dc91be14d9274a12590135953b856d09627d866b", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "0cb64ad4955eaa861a08233fcdd70e59ec15c350", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kousathanas/simsfs_fast", "max_forks_repo_path": "genlib.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0cb64ad4955eaa861a08233fcdd70e59ec15c350", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "kousathanas/simsfs_fast", "max_issues_repo_path": "genlib.c", "max_line_length": 120, "max_stars_count": null, "max_stars_repo_head_hexsha": "0cb64ad4955eaa861a08233fcdd70e59ec15c350", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kousathanas/simsfs_fast", "max_stars_repo_path": "genlib.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 16165, "size": 52020 }
/* block/gsl_block_uint.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_BLOCK_UINT_H__ #define __GSL_BLOCK_UINT_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_errno.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 struct gsl_block_uint_struct { size_t size; unsigned int *data; }; typedef struct gsl_block_uint_struct gsl_block_uint; GSL_FUN gsl_block_uint *gsl_block_uint_alloc (const size_t n); GSL_FUN gsl_block_uint *gsl_block_uint_calloc (const size_t n); GSL_FUN void gsl_block_uint_free (gsl_block_uint * b); GSL_FUN int gsl_block_uint_fread (FILE * stream, gsl_block_uint * b); GSL_FUN int gsl_block_uint_fwrite (FILE * stream, const gsl_block_uint * b); GSL_FUN int gsl_block_uint_fscanf (FILE * stream, gsl_block_uint * b); GSL_FUN int gsl_block_uint_fprintf (FILE * stream, const gsl_block_uint * b, const char *format); GSL_FUN int gsl_block_uint_raw_fread (FILE * stream, unsigned int * b, const size_t n, const size_t stride); GSL_FUN int gsl_block_uint_raw_fwrite (FILE * stream, const unsigned int * b, const size_t n, const size_t stride); GSL_FUN int gsl_block_uint_raw_fscanf (FILE * stream, unsigned int * b, const size_t n, const size_t stride); GSL_FUN int gsl_block_uint_raw_fprintf (FILE * stream, const unsigned int * b, const size_t n, const size_t stride, const char *format); GSL_FUN size_t gsl_block_uint_size (const gsl_block_uint * b); GSL_FUN unsigned int * gsl_block_uint_data (const gsl_block_uint * b); __END_DECLS #endif /* __GSL_BLOCK_UINT_H__ */
{ "alphanum_fraction": 0.7652336449, "avg_line_length": 35.1973684211, "ext": "h", "hexsha": "f125a9903f00fb7fa5e849805282949f60a286f6", "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": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_block_uint.h", "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/gsl/gsl_block_uint.h", "max_line_length": 136, "max_stars_count": null, "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/gsl/gsl_block_uint.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 707, "size": 2675 }
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_monte.h> #include <gsl/gsl_monte_plain.h> #include <gsl/gsl_monte_miser.h> #include <gsl/gsl_monte_vegas.h> double calculateIntegralValue(int sampleCount) { int correctSamples = 0; srand(time(NULL)); FILE* file = fopen("sqrt.txt", "w"); for (int i = 0; i < sampleCount; ++i){ double x = (double)rand() / RAND_MAX; // double [0, 1] double y = (double)rand() / RAND_MAX; // double [0, 1000] if (y <= 1.0/sqrt(x)){ fprintf (file,"%g %g\n", x, y); //Save correct samples to file correctSamples++; } } return (double)correctSamples / (double)sampleCount; // (b-a) is (1.0-0.0) so we can ignore this multiply } void calculateIntegralError(int maxSamples) { srand(time(NULL)); FILE* file = fopen("sqrt_err.txt", "w"); for (int sampleCount = 1; sampleCount < maxSamples; ++sampleCount){ int correctSamples = 0; for (int i = 0; i < sampleCount; ++i){ double x = (double)rand() / RAND_MAX; // double [0, 1] double y = (double)rand() / RAND_MAX; // double [0, 1] if (y <= x * x){ correctSamples++; } } double sum = (double)correctSamples / (double)sampleCount; // (b-a) is (1.0-0.0) so we can ignore this multiply double sumError = sum - 1.0/3.0; fprintf(file, "%d %g\n", sampleCount, sqrt(sumError * sumError)); } } void monteCarloPLAIN() { double res, err; double xl[3] = {0,0,0}; double xu[3] = {M_PI, M_PI, M_PI}; const gsl_rng_type *T; gsl_rng *r; gsl_monte_function G; } int main(void) { // printf("Sum: %g\n", sum); return 0; }
{ "alphanum_fraction": 0.5716666667, "avg_line_length": 25.7142857143, "ext": "c", "hexsha": "4e19fb38a31877c012a7dd55b13eadbb5532f3b7", "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": "5fca38f9856cb17e129007eb3ad50112520af16e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "komilll/mownit_linux", "max_forks_repo_path": "zad7/monte_carlo.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5fca38f9856cb17e129007eb3ad50112520af16e", "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": "komilll/mownit_linux", "max_issues_repo_path": "zad7/monte_carlo.c", "max_line_length": 119, "max_stars_count": null, "max_stars_repo_head_hexsha": "5fca38f9856cb17e129007eb3ad50112520af16e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "komilll/mownit_linux", "max_stars_repo_path": "zad7/monte_carlo.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 548, "size": 1800 }
#pragma once #include <gsl/gsl> #include <mutex> #include <condition_variable> #include <arcana/threading/affinity.h> namespace Babylon { class SafeTimespanGuarantor { public: SafeTimespanGuarantor(); void BeginSafeTimespan(); void EndSafeTimespan(); using SafetyGuarantee = gsl::final_action<std::function<void()>>; SafetyGuarantee GetSafetyGuarantee(); private: arcana::affinity m_affinity{}; uint32_t m_count{}; std::mutex m_mutex{}; std::unique_lock<std::mutex> m_lock{}; std::condition_variable m_condition{}; }; }
{ "alphanum_fraction": 0.644338118, "avg_line_length": 20.2258064516, "ext": "h", "hexsha": "8db71f844291454019e93e01aa338fecb86ed997", "lang": "C", "max_forks_count": 114, "max_forks_repo_forks_event_max_datetime": "2022-03-11T21:13:27.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-10T18:07:19.000Z", "max_forks_repo_head_hexsha": "7f1f9fd23bf649c9c8a1260f2b93752145b0c024", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "chiamaka-123/BabylonNative", "max_forks_repo_path": "Core/Graphics/Source/SafeTimespanGuarantor.h", "max_issues_count": 593, "max_issues_repo_head_hexsha": "7f1f9fd23bf649c9c8a1260f2b93752145b0c024", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:25:09.000Z", "max_issues_repo_issues_event_min_datetime": "2019-05-31T23:56:36.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "chiamaka-123/BabylonNative", "max_issues_repo_path": "Core/Graphics/Source/SafeTimespanGuarantor.h", "max_line_length": 73, "max_stars_count": 474, "max_stars_repo_head_hexsha": "7f1f9fd23bf649c9c8a1260f2b93752145b0c024", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "chiamaka-123/BabylonNative", "max_stars_repo_path": "Core/Graphics/Source/SafeTimespanGuarantor.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:09:35.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-29T09:41:22.000Z", "num_tokens": 148, "size": 627 }
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include <unistd.h> #include <dirent.h> #include "hdf5.h" #include <math.h> #include <time.h> #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_sf_bessel.h> #include "mclib_3d.h" #include <omp.h> #define R_DIM 1260 #define THETA_DIM 280 #define PHI_DIM 280 void read_hydro(char hydro_prefix[200], int frame, double r_inj, double **x, double **y, double **z, double **szx, double **szy, double **r, double **theta, double **phi,\ double **velx, double **vely, double **velz, double **dens, double **pres, double **gamma, double **dens_lab, double **temp, int *number, int ph_inj_switch, double min_r, double max_r, double fps, FILE *fPtr) { FILE *hydroPtr=NULL; char hydrofile[200]="", file_num[200]="", full_file[200]="",file_end[200]="" ; char buf[10]=""; int i=0, j=0, k=0, elem=0, elem_factor=0; int phi_min_index=0, phi_max_index=0, r_min_index=0, r_max_index=0, theta_min_index=0, theta_max_index=0; //all_index_buffer contains phi_min, phi_max, theta_min, theta_max, r_min, r_max indexes to get from grid files int r_index=0, theta_index=0, phi_index=0, hydro_index=0, all_index_buffer=0, adjusted_remapping_index=0, dr_index=0; int *remapping_indexes=NULL; float buffer=0; float *dens_unprc=NULL; float *vel_r_unprc=NULL; float *vel_theta_unprc=NULL; float *vel_phi_unprc=NULL; float *pres_unprc=NULL; double ph_rmin=0, ph_rmax=0; double r_in=1e10, r_ref=2e13; double *r_edge=NULL; double *dr=NULL; double *r_unprc=malloc(sizeof(double)*R_DIM); double *theta_unprc=malloc(sizeof(double)*THETA_DIM); double *phi_unprc=malloc(sizeof(double)*PHI_DIM); if (ph_inj_switch==0) { ph_rmin=min_r; ph_rmax=max_r; } snprintf(file_end,sizeof(file_end),"%s","small.data" ); //density snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 1,"-" ); modifyFlashName(file_num, hydrofile, frame,1); fprintf(fPtr,">> Opening file %s\n", file_num); fflush(fPtr); snprintf(full_file, sizeof(full_file), "%s%s", file_num, file_end); /* fprintf(fPtr,"Reading Density: %s\n", full_file); fflush(fPtr); */ hydroPtr=fopen(full_file, "rb"); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&phi_min_index, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid fread(&phi_max_index, sizeof(int)*1, 1,hydroPtr); fread(&theta_min_index, sizeof(int)*1, 1,hydroPtr); fread(&theta_max_index, sizeof(int)*1, 1,hydroPtr); fread(&r_min_index, sizeof(int)*1, 1,hydroPtr); fread(&r_max_index, sizeof(int)*1, 1,hydroPtr); fclose(hydroPtr); //fortran indexing starts @ 1, but C starts @ 0 r_min_index--; r_max_index--; theta_min_index--; theta_max_index--; phi_min_index--; phi_max_index--; //number of elements defined by this now elem=(r_max_index+1-r_min_index)*(theta_max_index+1-theta_min_index)*(phi_max_index+1-phi_min_index); //add 1 b/c max_index is 1 less than max number of elements in file /* fprintf(fPtr,"Elem %d\n", elem); fprintf(fPtr,"Limits %d, %d, %d, %d, %d, %d\n", phi_min_index, phi_max_index, theta_min_index, theta_max_index, r_min_index, r_max_index); fflush(fPtr); */ //now with number of elements allocate data, remember last element is some garbage that only fortran uses dens_unprc=malloc(elem*sizeof(float)); vel_r_unprc=malloc(elem*sizeof(float)); vel_theta_unprc=malloc(elem*sizeof(float)); pres_unprc=malloc(elem*sizeof(float)); vel_phi_unprc=malloc(elem*sizeof(float)); hydroPtr=fopen(full_file, "rb"); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid, dont need anymore so just save to dummy variable fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(dens_unprc, sizeof(float),elem, hydroPtr); //data fclose(hydroPtr); /* for (i=0;i<R_DIM*THETA_DIM*PHI_DIM;i++) { if ((i>98784000-5) || (i<5)) { fprintf(fPtr,"Density %d: %0.7e\n", i, *(dens_unprc+i)); fflush(fPtr); } } */ //velocities divided by c //v_r snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 2,"-" ); modifyFlashName(file_num, hydrofile, frame,1); snprintf(full_file, sizeof(full_file), "%s%s", file_num, file_end); /* fprintf(fPtr,"Reading v_r: %s\n", full_file); fflush(fPtr); */ hydroPtr=fopen(full_file, "rb"); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid, dont need anymore so just save to dummy variable fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(vel_r_unprc, sizeof(float),elem, hydroPtr); fclose(hydroPtr); /* for (i=0;i<5;i++) { fprintf(fPtr,"V_r %d: %e\n", i, *(vel_r_unprc+i)); fflush(fPtr); } */ //v_theta snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 3,"-" ); modifyFlashName(file_num, hydrofile, frame,1); snprintf(full_file, sizeof(full_file), "%s%s", file_num, file_end); /* fprintf(fPtr,"Reading v_theta: %s\n", full_file); fflush(fPtr); */ hydroPtr=fopen(full_file, "rb"); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid, dont need anymore so just save to dummy variable fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(vel_theta_unprc, sizeof(float),elem, hydroPtr); fclose(hydroPtr); /* for (i=0;i<5;i++) { fprintf(fPtr,"V_theta %d: %e\n", i, *(vel_theta_unprc+i)); fflush(fPtr); } */ //v_phi snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 4,"-" ); modifyFlashName(file_num, hydrofile, frame,1); snprintf(full_file, sizeof(full_file), "%s%s", file_num, file_end); /* fprintf(fPtr,"Reading v_phi: %s\n", full_file); fflush(fPtr); */ hydroPtr=fopen(full_file, "rb"); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid, dont need anymore so just save to dummy variable fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(vel_phi_unprc, sizeof(float),elem, hydroPtr); fclose(hydroPtr); /* for (i=0;i<5;i++) { fprintf(fPtr,"V_phi %d: %e\n", i, *(vel_phi_unprc+i)); fflush(fPtr); } */ //pressure (divided by c^2) snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 8,"-" ); modifyFlashName(file_num, hydrofile, frame,1); snprintf(full_file, sizeof(full_file), "%s%s", file_num, file_end); /* fprintf(fPtr,"Reading pres: %s\n", full_file); fflush(fPtr); */ hydroPtr=fopen(full_file, "rb"); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid, dont need anymore so just save to dummy variable fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(pres_unprc, sizeof(float),elem, hydroPtr); fclose(hydroPtr); /* for (i=PHI_DIM-1;i<PHI_DIM;i++) { for (j=THETA_DIM-1;j<THETA_DIM;j++) { for (k=R_DIM-5;k<R_DIM;k++) { fprintf(fPtr,"Pres %d: %e\n", (i*R_DIM*THETA_DIM + j*R_DIM + k ), *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k ))); fflush(fPtr); } } } */ // see how many elements there are to test if reading correctly /* hydroPtr=fopen(full_file, "rb"); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran while (1 == fread(&buffer,sizeof(float),1,hydroPtr)) { elem++; } //fread(pres_unprc, sizeof(double)*HYDRO_DIM,HYDRO_DIM, hydroPtr); fclose(hydroPtr); fprintf(fPtr,"Elem %d\n", elem); */ //R //remapping_indexes=getIndexesForRadialRemapping(hydro_prefix); //can run this once in debug mode to find out delta index for each remapping and number of total r elements //for given set of remappings on July 12th 2017, grid00-x1.data[420]=grid01-x1.data[0], grid01-x1.data[420]=grid02-x1.data[0], etc. total number of r is 3780 if (frame<=1300) { snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"grid0", 0,"-x1.data" ); //adjusted_remapping_index=(*(remapping_indexes+0))+r_min_index ; //this if I am not hardcoding the dr index values adjusted_remapping_index=(0*420)+r_min_index; } else if (frame<=2000) { snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"grid0", 1,"-x1.data" ); //adjusted_remapping_index=(*(remapping_indexes+1))+r_min_index; adjusted_remapping_index=(1*420)+r_min_index; } else if (frame<=10000) { snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"grid0", 2,"-x1.data" ); //adjusted_remapping_index=(*(remapping_indexes+2))+r_min_index; adjusted_remapping_index=(2*420)+r_min_index; } else if (frame<=20000) { snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"grid0", 3,"-x1.data" ); //adjusted_remapping_index=(*(remapping_indexes+3))+r_min_index; adjusted_remapping_index=(3*420)+r_min_index; } else if (frame<=35000) { snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"grid0", 4,"-x1.data" ); //adjusted_remapping_index=(*(remapping_indexes+4))+r_min_index; adjusted_remapping_index=(4*420)+r_min_index; } else if (frame<=50000) { snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"grid0", 5,"-x1.data" ); //adjusted_remapping_index=(*(remapping_indexes+5))+r_min_index; adjusted_remapping_index=(5*420)+r_min_index; } else if (frame<=60000) { snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"grid0", 6,"-x1.data" ); //adjusted_remapping_index=(*(remapping_indexes+6))+r_min_index; adjusted_remapping_index=(6*420)+r_min_index; } fprintf(fPtr,"Reading Radius: %s\n", hydrofile); fflush(fPtr); hydroPtr=fopen(hydrofile, "r"); i=0; while (i<R_DIM) { fscanf(hydroPtr, "%lf", (r_unprc+i)); //read value fgets(buf, 3,hydroPtr); //read comma /* if (i<5) { fprintf(fPtr,"R %d: %e\n", i, *(r_unprc+i)); fflush(fPtr); } */ i++; } fclose(hydroPtr); r_edge=malloc(sizeof(double)*(3780+1)); dr=malloc(sizeof(double)*(3780)); //calculate radial grid edges *(r_edge+0)=r_in; i=0; for (i=1;i<3780;i++) { *(r_edge+i)=(*(r_edge+i-1))+((*(r_edge+i-1))*(M_PI/560)/(1+((*(r_edge+i-1))/r_ref))); //r_i = r_(i-1) + Dq r_(i-1) [1 + r_(i-1)/r0]-1 *(dr+i-1)=(*(r_edge+i))-(*(r_edge+i-1)); /* if (i<5) { fprintf(fPtr,"R Edge: %d: %e Dr: %e\n", i, *(r_edge+i), *(dr+i-1)); fflush(fPtr); } */ } free(r_edge); //Theta snprintf(hydrofile,sizeof(hydrofile),"%s%s",hydro_prefix,"grid-x2.data" ); fprintf(fPtr,"Reading Theta: %s\n", hydrofile); fflush(fPtr); hydroPtr=fopen(hydrofile, "r"); i=0; while (i<THETA_DIM) { fscanf(hydroPtr, "%lf", (theta_unprc+i)); //read value fgets(buf, 3,hydroPtr); //read comma /* if (i<5) { fprintf(fPtr,"R %d: %e\n", i, *(theta_unprc+i)); fflush(fPtr); } */ i++; } fclose(hydroPtr); //Phi snprintf(hydrofile,sizeof(hydrofile),"%s%s",hydro_prefix,"grid-x3.data" ); /* fprintf(fPtr,"Reading Phi: %s\n", hydrofile); fflush(fPtr); */ hydroPtr=fopen(hydrofile, "r"); i=0; while (i<PHI_DIM) { fscanf(hydroPtr, "%lf", (phi_unprc+i)); //read value fgets(buf, 3,hydroPtr); //read comma /* if (i<5) { fprintf(fPtr,"R %d: %e\n", i, *(phi_unprc+i)); fflush(fPtr); } */ i++; } fclose(hydroPtr); //limit number of array elements PUT WHILE LOOP TO MAKE SURE NUMBER OF ELEMENTS >0 elem_factor=0; elem=0; while (elem==0) { elem=0; elem_factor++; for (i=0;i<(phi_max_index+1-phi_min_index);i++) { for (j=0;j<(theta_max_index+1-theta_min_index);j++) { for (k=0;k<(r_max_index+1-r_min_index);k++) { r_index=r_min_index+k; //if I have photons do selection differently than if injecting photons if (ph_inj_switch==0) { //printf("R's:%d, %e\n", k, *(r_unprc+r_index)); //if calling this function when propagating photons, choose blocks based on where the photons are if (((ph_rmin - elem_factor*C_LIGHT/fps)<(*(r_unprc+r_index))) && (*(r_unprc+r_index) < (ph_rmax + elem_factor*C_LIGHT/fps) )) { // *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k ) elem++; } } else { //if calling this function to inject photons choose blocks based on injection parameters, r_inj, which is sufficient if (((r_inj - elem_factor*C_LIGHT/fps)<(*(r_unprc+r_index))) && (*(r_unprc+r_index) < (r_inj + elem_factor*C_LIGHT/fps) )) { // *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k ) elem++; } } } } } } fprintf(fPtr,"Number of post restricted Elems: %d %e\n", elem, r_inj); //fprintf(fPtr,"Ph_min, Ph_max: %e, %e\n With c: min: %e max: %e \n", ph_rmin, ph_rmax, (ph_rmin - 2*C_LIGHT/fps), (ph_rmax + 2*C_LIGHT/fps)); fflush(fPtr); //allocate space for new set of data (*pres)=malloc (elem * sizeof (double )); (*velx)=malloc (elem * sizeof (double )); (*vely)=malloc (elem * sizeof (double )); (*velz)=malloc (elem * sizeof (double )); (*dens)=malloc (elem * sizeof (double )); (*x)=malloc (elem * sizeof (double )); (*y)=malloc (elem * sizeof (double )); (*z)=malloc (elem * sizeof (double )); (*r)=malloc (elem * sizeof (double )); (*theta)=malloc (elem * sizeof (double )); (*phi)=malloc (elem * sizeof (double )); (*gamma)=malloc (elem * sizeof (double )); (*dens_lab)=malloc (elem * sizeof (double )); (*szx)=malloc (elem * sizeof (double )); //theta and phi resolution (*szy)=malloc (elem * sizeof (double )); //r resolution (*temp)=malloc (elem * sizeof (double )); //limit number of array elements elem=0; for (i=0;i<(phi_max_index+1-phi_min_index);i++) { for (j=0;j<(theta_max_index+1-theta_min_index);j++) { for (k=0;k<(r_max_index+1-r_min_index);k++) { r_index=r_min_index+k; //look at indexes of r that are included in small hydro file theta_index=theta_min_index+j; phi_index=phi_min_index+i; dr_index=adjusted_remapping_index+k; hydro_index=(i*(r_max_index+1-r_min_index)*(theta_max_index+1-theta_min_index) + j*(r_max_index+1-r_min_index) + k ); //if I have photons do selection differently than if injecting photons if (ph_inj_switch==0) { //if calling this function when propagating photons, choose blocks based on where the photons are if (((ph_rmin - elem_factor*C_LIGHT/fps)<(*(r_unprc+r_index))) && (*(r_unprc+r_index) < (ph_rmax + elem_factor*C_LIGHT/fps) )) { (*pres)[elem] = *(pres_unprc+hydro_index); (*dens)[elem] = *(dens_unprc+hydro_index); (*temp)[elem] = pow(3*(*(pres_unprc+hydro_index))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0); (*gamma)[elem] = pow(pow(1.0-(pow(*(vel_r_unprc+hydro_index),2)+ pow(*(vel_theta_unprc+hydro_index),2)+pow(*(vel_phi_unprc+hydro_index),2)),0.5),-1); (*dens_lab)[elem] = (*(dens_unprc+hydro_index))*pow(pow(1.0-(pow(*(vel_r_unprc+hydro_index),2)+ pow(*(vel_theta_unprc+hydro_index),2)+pow(*(vel_phi_unprc+hydro_index),2)),0.5),-1); (*r)[elem] = *(r_unprc+r_index); (*theta)[elem] = *(theta_unprc+theta_index); (*phi)[elem] = *(phi_unprc+phi_index); (*x)[elem] = (*(r_unprc+r_index))*sin(*(theta_unprc+theta_index))*cos(*(phi_unprc+phi_index)); (*y)[elem] = (*(r_unprc+r_index))*sin(*(theta_unprc+theta_index))*sin(*(phi_unprc+phi_index)); (*z)[elem] = (*(r_unprc+r_index))*cos(*(theta_unprc+theta_index)); (*szx)[elem] = *(dr+dr_index); (*szy)[elem] = M_PI/560; (*velx)[elem]=((*(vel_r_unprc+hydro_index))*sin(*(theta_unprc+theta_index))*cos(*(phi_unprc+phi_index))) + ((*(vel_theta_unprc+hydro_index))*cos(*(theta_unprc+theta_index))*cos(*(phi_unprc+phi_index))) - ((*(vel_phi_unprc+hydro_index))*sin(*(phi_unprc+phi_index))); (*vely)[elem]=((*(vel_r_unprc+hydro_index))*sin(*(theta_unprc+theta_index))*sin(*(phi_unprc+phi_index))) + ((*(vel_theta_unprc+hydro_index))*cos(*(theta_unprc+theta_index))*sin(*(phi_unprc+phi_index))) + ((*(vel_phi_unprc+hydro_index))*cos(*(phi_unprc+phi_index))); (*velz)[elem]=((*(vel_r_unprc+hydro_index))*cos(*(theta_unprc+theta_index))) - ((*(vel_theta_unprc+hydro_index))*sin(*(theta_unprc+theta_index))); elem++; } } else { //if calling this function to inject photons choose blocks based on injection parameters, r_inj, which is sufficient if (((r_inj - elem_factor*C_LIGHT/fps)<(*(r_unprc+r_index))) && (*(r_unprc+r_index) < (r_inj + elem_factor*C_LIGHT/fps) )) { (*pres)[elem] = *(pres_unprc+hydro_index); (*dens)[elem] = *(dens_unprc+hydro_index); (*temp)[elem] = pow(3*(*(pres_unprc+hydro_index))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0); (*gamma)[elem] = pow(pow(1.0-(pow(*(vel_r_unprc+hydro_index),2)+ pow(*(vel_theta_unprc+hydro_index),2)+pow(*(vel_phi_unprc+hydro_index),2)),0.5),-1); (*dens_lab)[elem] = (*(dens_unprc+hydro_index))*pow(pow(1.0-(pow(*(vel_r_unprc+hydro_index),2)+ pow(*(vel_theta_unprc+hydro_index),2)+pow(*(vel_phi_unprc+hydro_index),2)),0.5),-1); (*r)[elem] = *(r_unprc+r_index); (*theta)[elem] = *(theta_unprc+theta_index); (*phi)[elem] = *(phi_unprc+phi_index); (*x)[elem] = (*(r_unprc+r_index))*sin(*(theta_unprc+theta_index))*cos(*(phi_unprc+phi_index)); (*y)[elem] = (*(r_unprc+r_index))*sin(*(theta_unprc+theta_index))*sin(*(phi_unprc+phi_index)); (*z)[elem] = (*(r_unprc+r_index))*cos(*(theta_unprc+theta_index)); (*szx)[elem] = *(dr+dr_index); (*szy)[elem] = M_PI/560; (*velx)[elem]=((*(vel_r_unprc+hydro_index))*sin(*(theta_unprc+theta_index))*cos(*(phi_unprc+phi_index))) + ((*(vel_theta_unprc+hydro_index))*cos(*(theta_unprc+theta_index))*cos(*(phi_unprc+phi_index))) - ((*(vel_phi_unprc+hydro_index))*sin(*(phi_unprc+phi_index))); (*vely)[elem]=((*(vel_r_unprc+hydro_index))*sin(*(theta_unprc+theta_index))*sin(*(phi_unprc+phi_index))) + ((*(vel_theta_unprc+hydro_index))*cos(*(theta_unprc+theta_index))*sin(*(phi_unprc+phi_index))) + ((*(vel_phi_unprc+hydro_index))*cos(*(phi_unprc+phi_index))); (*velz)[elem]=((*(vel_r_unprc+hydro_index))*cos(*(theta_unprc+theta_index))) - ((*(vel_theta_unprc+hydro_index))*sin(*(theta_unprc+theta_index))); elem++; } } } } } *number=elem; free(pres_unprc); free(dens_unprc); free(r_unprc); free(theta_unprc); free(phi_unprc);free(dr);free(vel_r_unprc); free(vel_theta_unprc); free(vel_phi_unprc); } void photonInjection3D( struct photon **ph, int *ph_num, double r_inj, double ph_weight, int min_photons, int max_photons, char spect, int array_length, double fps, double theta_min, double theta_max,\ double *x, double *y, double *z, double *szx, double *szy, double *r, double *theta, double *phi, double *temps, double *vx, double *vy, double *vz, gsl_rng * rand, FILE *fPtr) { int i=0, block_cnt=0, *ph_dens=NULL, ph_tot=0, j=0,k=0; double ph_dens_calc=0.0, fr_dum=0.0, y_dum=0.0, yfr_dum=0.0, fr_max=0, bb_norm=0, position_phi, ph_weight_adjusted, theta_prime=0; double com_v_phi, com_v_theta, *p_comv=NULL, *boost=NULL; //comoving phi, theta, comoving 4 momentum for a photon, and boost for photon(to go to lab frame) double *l_boost=NULL; //pointer to hold array of lorentz boost, to lab frame, values float num_dens_coeff; if (spect=='w') //from MCRAT paper, w for wien spectrum { num_dens_coeff=8.44; //printf("in wien spectrum\n"); } else { num_dens_coeff=20.29; //this is for black body spectrum //printf("in BB spectrum"); } //find how many blocks are near the injection radius within the angles defined in mc.par, get temperatures and calculate number of photons to allocate memory for //and then rcord which blocks have to have "x" amount of photons injected there printf("%e, %e\n",*(phi+i), theta_max); for(i=0;i<array_length;i++) { //look at all boxes in width delta r=c/fps and within angles we are interested in NEED TO modify for RIKEN data- dont need r anymore, just theta and phi? (didnt work), just look at pojection on x-z plane theta_prime=acos(*(y+i)/(*(r+i))); //jet axis here is the y axis if ( (theta_prime< theta_max) && (theta_prime >= theta_min) ) //(*(r+i) > (r_inj - C_LIGHT/fps)) && (*(r+i) < (r_inj + C_LIGHT/fps) ) && { //printf("%e\n", theta_prime ); block_cnt++; } } printf("Blocks: %d\n", block_cnt); ph_dens=malloc(block_cnt * sizeof(int)); //calculate the photon density for each block and save it to the array j=0; ph_tot=0; ph_weight_adjusted=ph_weight; //printf("%d %d\n", max_photons, min_photons); while ((ph_tot>max_photons) || (ph_tot<min_photons) ) { j=0; ph_tot=0; //allocate memory to record density of photons for each block //ph_dens=malloc(block_cnt * sizeof(int)); for (i=0;i<array_length;i++) { //printf("%d\n",i); //printf("%e, %e, %e, %e, %e, %e\n", *(r+i),(r_inj - C_LIGHT/fps), (r_inj + C_LIGHT/fps), *(theta+i) , theta_max, theta_min); //NEED TO modify for RIKEN data - modified theta_prime=acos(*(y+i)/(*(r+i))); if ( (theta_prime< theta_max) && (theta_prime >= theta_min) ) { //NEED TO modify for RIKEN data - modified ph_dens_calc=(num_dens_coeff*pow(*(temps+i),3.0)*pow(*(r+i),2)*sin(*(theta+i))* pow(*(szy+i),2.0)*(*(szx+i)) /(ph_weight_adjusted))*pow(pow(1.0-(pow(*(vx+i),2)+pow(*(vy+i),2)+pow(*(vz+i),2)),0.5),-1) ; //a*T^3/(weight) dV, dV=2*PI*x*dx^2, (*(ph_dens+j))=gsl_ran_poisson(rand,ph_dens_calc) ; //choose from poission distribution with mean of ph_dens_calc //printf("%d, %lf \n",*(ph_dens+j), ph_dens_calc); //sum up all the densities to get total number of photons ph_tot+=(*(ph_dens+j)); j++; } } if (ph_tot>max_photons) { //if the number of photons is too big make ph_weight larger ph_weight_adjusted*=10; //free(ph_dens); } else if (ph_tot<min_photons) { ph_weight_adjusted*=0.5; //free(ph_dens); } //printf("dens: %d, photons: %d\n", *(ph_dens+(j-1)), ph_tot); } printf("%d\n", ph_tot); //allocate memory for that many photons and also allocate memory to hold comoving 4 momentum of each photon and the velocity of the fluid (*ph)=malloc (ph_tot * sizeof (struct photon )); p_comv=malloc(4*sizeof(double)); boost=malloc(3*sizeof(double)); l_boost=malloc(4*sizeof(double)); //go through blocks and assign random energies/locations to proper number of photons ph_tot=0; k=0; for (i=0;i<array_length;i++) { theta_prime=acos(*(y+i)/(*(r+i))); if ( (theta_prime< theta_max) && (theta_prime >= theta_min) ) //NEED TO modify for RIKEN data - modified { //*(temps+i)=0.76*(*(temps+i)); for(j=0;j<( *(ph_dens+k) ); j++ ) { //have to get random frequency for the photon comoving frequency y_dum=1; //initalize loop yfr_dum=0; while (y_dum>yfr_dum) { fr_dum=gsl_rng_uniform_pos(rand)*6.3e11*(*(temps+i)); //in Hz //printf("%lf, %lf ",gsl_rng_uniform_pos(rand), (*(temps+i))); y_dum=gsl_rng_uniform_pos(rand); //printf("%lf ",fr_dum); if (spect=='w') { yfr_dum=(1.0/(1.29e31))*pow((fr_dum/(*(temps+i))),3.0)/(exp((PL_CONST*fr_dum)/(K_B*(*(temps+i)) ))-1); //curve is normalized to maximum } else { fr_max=(5.88e10)*(*(temps+i));//(C_LIGHT*(*(temps+i)))/(0.29); //max frequency of bb bb_norm=(PL_CONST*fr_max * pow((fr_max/C_LIGHT),2.0))/(exp(PL_CONST*fr_max/(K_B*(*(temps+i))))-1); //find value of bb at fr_max yfr_dum=((1.0/bb_norm)*PL_CONST*fr_dum * pow((fr_dum/C_LIGHT),2.0))/(exp(PL_CONST*fr_dum/(K_B*(*(temps+i))))-1); //curve is normalized to vaue of bb @ max frequency } //printf("%lf, %lf,%lf,%e \n",(*(temps+i)),fr_dum, y_dum, yfr_dum); } //printf("%lf\n ",fr_dum); //position_phi= gsl_rng_uniform(rand)*2*M_PI; //NEED TO modify for RIKEN data-modified, dont need anymore com_v_phi=gsl_rng_uniform(rand)*2*M_PI; com_v_theta=acos((gsl_rng_uniform(rand)*2)-1); //printf("%lf, %lf, %lf\n", position_phi, com_v_phi, com_v_theta); //populate 4 momentum comoving array *(p_comv+0)=PL_CONST*fr_dum/C_LIGHT; *(p_comv+1)=(PL_CONST*fr_dum/C_LIGHT)*sin(com_v_theta)*cos(com_v_phi); *(p_comv+2)=(PL_CONST*fr_dum/C_LIGHT)*sin(com_v_theta)*sin(com_v_phi); *(p_comv+3)=(PL_CONST*fr_dum/C_LIGHT)*cos(com_v_theta); //populate boost matrix, not sure why multiplying by -1, seems to give correct answer in old python code... //NEED TO modify for RIKEN data - modified *(boost+0)=-1*(*(vx+i)); *(boost+1)=-1*(*(vy+i)); *(boost+2)=-1*(*(vz+i)); //printf("%lf, %lf, %lf\n", *(boost+0), *(boost+1), *(boost+2)); //boost to lab frame lorentzBoost(boost, p_comv, l_boost, 'p', fPtr); //printf("Assignemnt: %e, %e, %e, %e\n", *(l_boost+0), *(l_boost+1), *(l_boost+2),*(l_boost+3)); (*ph)[ph_tot].p0=(*(l_boost+0)); (*ph)[ph_tot].p1=(*(l_boost+1)); (*ph)[ph_tot].p2=(*(l_boost+2)); (*ph)[ph_tot].p3=(*(l_boost+3)); //NEED TO modify for RIKEN data-modified (*ph)[ph_tot].r0= (*(x+i)); //put photons @ center of box that they are supposed to be in with random phi (*ph)[ph_tot].r1=(*(y+i)) ; (*ph)[ph_tot].r2=(*(z+i)); //y coordinate in flash becomes z coordinate in MCRaT (*ph)[ph_tot].num_scatt=0; (*ph)[ph_tot].weight=ph_weight_adjusted; //printf("%d\n",ph_tot); ph_tot++; } k++; } } *ph_num=ph_tot; //save number of photons //printf(" %d: %d\n", *(ph_dens+(k-1)), *ph_num); free(ph_dens); free(p_comv);free(boost); free(l_boost); } void phMinMax(struct photon *ph, int ph_num, double *min, double *max, double *min_theta, double *max_theta, FILE *fPtr) { double temp_r_max=0, temp_r_min=DBL_MAX, temp_theta_max=0, temp_theta_min=DBL_MAX; int i=0, num_thread=omp_get_num_threads(); double ph_r=0, ph_theta=0; #pragma omp parallel for num_threads(num_thread) firstprivate(ph_r, ph_theta) reduction(min:temp_r_min) reduction(max:temp_r_max) reduction(min:temp_theta_min) reduction(max:temp_theta_max) for (i=0;i<ph_num;i++) { if ((ph+i)->weight != 0) { ph_r=pow(pow( ((ph+i)->r0), 2.0) + pow(((ph+i)->r1),2.0 ) + pow(((ph+i)->r2) , 2.0),0.5); ph_theta=acos(((ph+i)->r2) /ph_r); //this is the photons theta psition in the FLASH grid, gives in radians if (ph_r > temp_r_max ) { temp_r_max=ph_r; //fprintf(fPtr, "The new max is: %e from photon %d with x: %e y: %e z: %e\n", temp_r_max, i, ((ph+i)->r0), (ph+i)->r1, (ph+i)->r2); } //if ((i==0) || (ph_r<temp_r_min)) if (ph_r<temp_r_min) { temp_r_min=ph_r; //fprintf(fPtr, "The new min is: %e from photon %d with x: %e y: %e z: %e\n", temp_r_min, i, ((ph+i)->r0), (ph+i)->r1, (ph+i)->r2); } if (ph_theta > temp_theta_max ) { temp_theta_max=ph_theta; //fprintf(fPtr, "The new max is: %e from photon %d with x: %e y: %e z: %e\n", temp_r_max, i, ((ph+i)->r0), (ph+i)->r1, (ph+i)->r2); } //if ((i==0) || (ph_r<temp_r_min)) if (ph_theta<temp_theta_min) { temp_theta_min=ph_theta; //fprintf(fPtr, "The new min is: %e from photon %d with x: %e y: %e z: %e\n", temp_r_min, i, ((ph+i)->r0), (ph+i)->r1, (ph+i)->r2); } } } *max=temp_r_max; *min=temp_r_min; *max_theta=temp_theta_max; *min_theta=temp_theta_min; } int *getIndexesForRadialRemapping(char hydro_prefix[200]) { FILE *hydroPtr=NULL; char hydrofile[200]=""; char buf[10]=""; int i=0, j=0; int *remapping_start_index=malloc(sizeof(int)*7); //what index out of total range of r does each remapping begin at double r_in=1e10, r_ref=2e13; double *r_unprc_0=malloc(sizeof(double)*R_DIM), *r_unprc_1=malloc(sizeof(double)*R_DIM), *r_unprc_2=malloc(sizeof(double)*R_DIM), *r_unprc_3=malloc(sizeof(double)*R_DIM); double *r_unprc_4=malloc(sizeof(double)*R_DIM), *r_unprc_5=malloc(sizeof(double)*R_DIM), *r_unprc_6=malloc(sizeof(double)*R_DIM); double *r_edge=NULL, *dr=NULL, *rPtr=NULL; for (i=0;i<7;i++) { snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"grid0", i,"-x1.data" ); hydroPtr=fopen(hydrofile, "r"); j=0; while (j<R_DIM) { switch (i) { case 0: fscanf(hydroPtr, "%lf", (r_unprc_0+j)); //read value case 1: fscanf(hydroPtr, "%lf", (r_unprc_1+j)); case 2: fscanf(hydroPtr, "%lf", (r_unprc_2+j)); case 3: fscanf(hydroPtr, "%lf", (r_unprc_3+j)); case 4: fscanf(hydroPtr, "%lf", (r_unprc_4+j)); case 5: fscanf(hydroPtr, "%lf", (r_unprc_5+j)); case 6: fscanf(hydroPtr, "%lf", (r_unprc_6+j)); } fgets(buf, 3,hydroPtr); //read comma /* if (i<5) { fprintf(fPtr,"R %d: %e\n", i, *(r_unprc+i)); fflush(fPtr); } */ j++; } fclose(hydroPtr); } //calculate the indexes in which each remapping takes over j=0; //keeps track of indexes of all of the possible r values i=0; //keeps track of index within a certain remapping, when get to R_DIM know that were @ end of last remapping b/c remappings overlap with one another rPtr=r_unprc_0; //start off looking at 0th remapping *(remapping_start_index+1)=j; //0th remapping starts at index 0 while (i<R_DIM) { if (*(rPtr+i)== *(r_unprc_1+0)) { //if the element of the 0th remapping is equal to the 1st element of the 1st remapping, start to look at the 1st remapping rPtr=r_unprc_1; i=0; *(remapping_start_index+1)=j; } else if (*(rPtr+i)== *(r_unprc_2+0)) { rPtr=r_unprc_2; i=0; *(remapping_start_index+2)=j; } else if (*(rPtr+i)== *(r_unprc_3+0)) { rPtr=r_unprc_3; i=0; *(remapping_start_index+3)=j; } else if (*(rPtr+i)== *(r_unprc_4+0)) { rPtr=r_unprc_4; i=0; *(remapping_start_index+4)=j; } else if (*(rPtr+i)== *(r_unprc_5+0)) { rPtr=r_unprc_5; i=0; *(remapping_start_index+5)=j; } else if (*(rPtr+i)== *(r_unprc_6+0)) { rPtr=r_unprc_6; i=0; *(remapping_start_index+6)=j; } j++; i++; } printf("Indexes %d, %d, %d, %d, %d, %d, %d\n Elems: %d\n", *(remapping_start_index+0), *(remapping_start_index+1), *(remapping_start_index+2), *(remapping_start_index+3), *(remapping_start_index+4), *(remapping_start_index+5), *(remapping_start_index+6), j); //exit(0); r_edge=malloc(sizeof(double)*(j+1)); dr=malloc(sizeof(double)*j); //calculate radial grid edges *(r_edge+0)=r_in; i=0; for (i=1;i<j;i++) { *(r_edge+i)=(*(r_edge+i-1))+((*(r_edge+i-1))*(M_PI/560)/(1+((*(r_edge+i-1))/r_ref))); //r_i = r_(i-1) + Dq r_(i-1) [1 + r_(i-1)/r0]-1 *(dr+i-1)=(*(r_edge+i))-(*(r_edge+i-1)); /* if (i<5) { fprintf(fPtr,"R Edge: %d: %e Dr: %e\n", i, *(r_edge+i), *(dr+i-1)); fflush(fPtr); } */ } free(r_edge); free(r_unprc_0); free(r_unprc_1); free(r_unprc_2); free(r_unprc_3); free(r_unprc_4); free(r_unprc_5); free(r_unprc_6); return remapping_start_index; }
{ "alphanum_fraction": 0.559830714, "avg_line_length": 42.9611973392, "ext": "c", "hexsha": "8a3c6a30178cf630efc32daadbe7129ce90a7aac", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-11-20T09:12:08.000Z", "max_forks_repo_forks_event_min_datetime": "2021-06-09T16:11:50.000Z", "max_forks_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "outflows/MCRaT", "max_forks_repo_path": "OLDER_MCRaT_VERSIONS/HYBRID_PARALLEL/mclib_3d.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "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": "outflows/MCRaT", "max_issues_repo_path": "OLDER_MCRaT_VERSIONS/HYBRID_PARALLEL/mclib_3d.c", "max_line_length": 289, "max_stars_count": 4, "max_stars_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "outflows/MCRaT", "max_stars_repo_path": "OLDER_MCRaT_VERSIONS/HYBRID_PARALLEL/mclib_3d.c", "max_stars_repo_stars_event_max_datetime": "2021-04-05T14:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2020-10-20T08:37:35.000Z", "num_tokens": 11284, "size": 38751 }
#include <stdio.h> #include <stdlib.h> #include <cblas.h> #include <clBlas.h> void cblas_dgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const double alpha, const double *A, const int lda, const double *B, const int ldb, const double beta, double *C, const int ldc) { cl_int err; cl_platform_id platform = 0; cl_device_id device = 0; cl_context_properties props[3] = {CL_CONTEXT_PLATFORM, 0, 0}; cl_context ctx = 0; cl_command_queue queue = 0; cl_mem bufA , bufB, bufC; cl_event event = NULL; cl_uint available = 0; int ret = 0; // HACK: ignore order / trans clblasOrder order = clblasColumnMajor; clblasTranspose transA = clblasNoTrans; clblasTranspose transB = clblasNoTrans; /* Setup OpenCL environment. */ err = clGetPlatformIDs(1, &platform, &available); if (err != CL_SUCCESS) { printf("clGetPlatformIDs() failed with %d and %d\n", err, available); exit(1); } printf("found %d OpenCL platforms\n", available); // CL_DEVICE_TYPE_GPU forces GPU use err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_DEFAULT, 1, &device, &available); if (err != CL_SUCCESS) { printf("clGetDeviceIDs() failed with %d\n", err); exit(1); } printf("found %d OpenCL devices\n", available); props[1] = (cl_context_properties) platform; ctx = clCreateContext(props, 1, &device, NULL, NULL, &err); if (err != CL_SUCCESS) { printf("clCreateContext() failed with %d\n", err); exit(1); } printf("created context\n"); queue = clCreateCommandQueue(ctx, device, 0, &err); if (err != CL_SUCCESS) { printf("clCreateCommandQueue() failed with %d\n", err); clReleaseContext(ctx); exit(1); } printf("created command queue\n"); /* Setup clblas. */ err = clblasSetup(); if (err != CL_SUCCESS) { printf("clblasSetup() failed with %d\n", err); clReleaseCommandQueue(queue); clReleaseContext(ctx); exit(1); } printf("setup clblas\n"); /* Prepare OpenCL memory objects and place matrices inside them. */ bufA = clCreateBuffer(ctx, CL_MEM_READ_ONLY, M * K * sizeof(*A), NULL, &err); bufB = clCreateBuffer(ctx, CL_MEM_READ_ONLY, K * N * sizeof(*B), NULL, &err); bufC = clCreateBuffer(ctx, CL_MEM_READ_WRITE, M * N * sizeof(*C), NULL, &err); printf("created buffers\n"); err = clEnqueueWriteBuffer(queue, bufA, CL_TRUE, 0, M * K * sizeof(double), A, 0, NULL, NULL); err = clEnqueueWriteBuffer(queue, bufB, CL_TRUE, 0, K * N * sizeof(double), B, 0, NULL, NULL); err = clEnqueueWriteBuffer(queue, bufC, CL_TRUE, 0, M * N * sizeof(double), C, 0, NULL, NULL); printf("enqueud buffers\n"); /* * Call clblas extended function. Perform gemm for the lower right * sub-matrices */ err = clblasDgemm(order, transA, transB, M, N, K, alpha, bufA, 0, lda, bufB, 0, ldb, beta, bufC, 0, ldc, 1, &queue, 0, NULL, &event); if (err != CL_SUCCESS) { printf("clblasSgemmEx() failed with %d\n", err); ret = 1; } else { printf("no errors for calculation\n"); fflush(stdout); /* Wait for calculations to be finished. */ err = clWaitForEvents(1, &event); /* Fetch results of calculations from GPU memory. */ err = clEnqueueReadBuffer(queue, bufC, CL_TRUE, 0, M * N * sizeof(double), C, 0, NULL, NULL); printf("got result\n"); } /* Release OpenCL memory objects. */ clReleaseMemObject(bufC); clReleaseMemObject(bufB); clReleaseMemObject(bufA); printf("released\n"); /* Finalize work with clblas. */ clblasTeardown(); printf("teardown clblas\n"); /* Release OpenCL working objects. */ clReleaseCommandQueue(queue); printf("release command queue\n"); clReleaseContext(ctx); printf("release context\n"); }
{ "alphanum_fraction": 0.6621196222, "avg_line_length": 30.496, "ext": "c", "hexsha": "44e1ad86b8bcd47d2ebf5ef553033c9d0a39ae8c", "lang": "C", "max_forks_count": 154, "max_forks_repo_forks_event_max_datetime": "2021-09-07T04:58:57.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-03T22:48:26.000Z", "max_forks_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "debasish83/netlib-java", "max_forks_repo_path": "perf/src/main/c/clwrapper.c", "max_issues_count": 59, "max_issues_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3", "max_issues_repo_issues_event_max_datetime": "2017-07-24T14:20:38.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-01T10:34:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "debasish83/netlib-java", "max_issues_repo_path": "perf/src/main/c/clwrapper.c", "max_line_length": 95, "max_stars_count": 624, "max_stars_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "debasish83/netlib-java", "max_stars_repo_path": "perf/src/main/c/clwrapper.c", "max_stars_repo_stars_event_max_datetime": "2022-03-26T22:06:35.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-10T02:29:22.000Z", "num_tokens": 1107, "size": 3812 }
/** * @copyright (c) 2017 King Abdullah University of Science and Technology (KAUST). * All rights reserved. **/ /** * @file codelet_zgytlr.c * * HiCMA codelets kernel * HiCMA is a software package provided by King Abdullah University of Science and Technology (KAUST) * * @version 0.1.0 * @author Kadir Akbudak * @date 2017-11-16 * @precisions normal z -> c d s **/ #include "morse.h" #include "runtime/starpu/chameleon_starpu.h" //#include "runtime/starpu/include/runtime_codelet_z.h" #include "runtime/starpu/runtime_codelets.h" ZCODELETS_HEADER(gytlr) #include <assert.h> #include <stdio.h> #include <sys/time.h>//FIXME for gettimeofday #include <stdlib.h>//FIXME for malloc #include "starsh.h" #include "starsh-spatial.h" #include "starsh-randtlr.h" #ifdef MKL #include <mkl.h> #include <mkl_lapack.h> //#pragma message("MKL is used") #else #ifdef ARMPL #include <armpl.h> #else #include <cblas.h> #endif #ifdef LAPACKE_UTILS #include <lapacke_utils.h> #endif #include <lapacke.h> //#pragma message("MKL is NOT used") #endif extern STARSH_blrf *mpiF; extern int print_index; int print_index_end; extern int store_only_diagonal_tiles; extern int global_check; extern int print_mat; extern void _printmat(double * A, int m, int n, int ld); //extern int global_always_fixed_rank; //FIXME this does not work, I do not know why //extern int global_fixed_rank; int global_always_fixed_rank; int global_fixed_rank; int gytlr_tile_ii = -1; int gytlr_tile_jj = -1; void zgytlr( int m, int n, /*dimension of squareAD*/ double *AU, double *AV, double *AD, double *Ark, int lda, int ldu, int ldv, int bigM, int ii, int jj, unsigned long long int seed, int maxrank, double tol, int compress_diag, double *Dense ) { if(gytlr_tile_ii >= 0) { ii = gytlr_tile_ii; printf("%s %d: Using fixed i:%d\n", __FILE__, __LINE__, ii); } if(gytlr_tile_jj >= 0) { jj = gytlr_tile_jj; printf("%s %d: Using fixed j:%d\n", __FILE__, __LINE__, jj); } int64_t i, j; //printf("m:%d n:%d bigM:%d m0:%d n0:%d\n", m, n, bigM, m0, n0); struct timeval tvalBefore, tvalAfter; // removed comma gettimeofday (&tvalBefore, NULL); if(print_index){ fprintf(stderr, "+GYTLR\t|(%d,%d) m:%d n:%d lda:%d ldu:%d ldv:%d\n", ii, jj, m, n, lda, ldu, ldv); } int shape[2]; int rank = 0; int oversample = 10; double *work; int *iwork; STARSH_cluster *RC = mpiF->row_cluster, *CC = RC; void *RD = RC->data, *CD = RD; double *saveAD; // allocate space for dense tile if((ii != jj && store_only_diagonal_tiles == 1) // if tile is off diagonal and // and only diagonal tiles are stored in a tall and skinny matrix // store_only_diagonal_tiles is here because // code can use AD to store dense tiles || // OR compress_diag == 1) { // diagonals are also compressed so AD may not used perhaps saveAD = AD; //AD = malloc(sizeof(double) * m * n); AD = malloc(sizeof(double) * lda * n); assert(m==lda); } //starsh_blrf_get_block(mpiF, ii, jj, shape, &AD); mpiF->problem->kernel(m, n, RC->pivot+RC->start[ii], CC->pivot+CC->start[jj], RD, CD, AD, lda); /* {*/ /*if (ii != jj || compress_diag == 1) { */ /*if(store_only_diagonal_tiles == 1) {*/ /*assert(AD != saveAD);*/ /*free(AD);*/ /*}*/ /*}*/ /*return; //TODO*/ /*}*/ if(global_check == 1){ char chall = 'A'; dlacpy_(&chall, &m, &n, AD, &lda, Dense, &lda); //printf("Original problem is copied :%d,%d\n", ii,jj); } int mn = m; int mn2 = maxrank+oversample; if(mn2 > mn) mn2 = mn; // Get size of temporary arrays size_t lwork = n, lwork_sdd = (4*mn2+7)*mn2; if(lwork_sdd > lwork) lwork = lwork_sdd; lwork += (size_t)mn2*(2*n+m+mn2+1); size_t liwork = 8*mn2; // Allocate temporary arrays //STARSH_MALLOC(iwork, liwork); iwork = malloc(sizeof(*iwork) * liwork); if(iwork == NULL) { fprintf(stderr, "%s %s %d:\t Allocation failed. No memory! liwork:%d", __FILE__, __func__, __LINE__, liwork); exit(-1); } //STARSH_MALLOC(work, lwork); work = malloc(sizeof(*work) * lwork); if(work == NULL) { fprintf(stderr, "%s %s %d:\t Allocation failed. No memory! lwork:%d", __FILE__, __func__, __LINE__, lwork); exit(-1); } if (ii != jj || compress_diag == 1) { // do not try to compress diagonal blocks if it is not enforced //AD is m x n. AU and AV are m x maxrank and n x maxrank correspondingly //starsh_kernel_drsdd(m, n, AD, AU, AV, &rank, maxrank, oversample, tol, work, lwork, iwork); //starsh_dense_dlrrsdd(m, n, AD, AU, AV, &rank, maxrank, oversample, tol, work, lwork, iwork); starsh_dense_dlrrsdd(m, n, AD, lda, AU, ldu, AV, ldv, &rank, maxrank, oversample, tol, work, lwork, iwork); if(0)cblas_dgemm( //for testing purposes CblasColMajor, CblasNoTrans, CblasTrans, m, n, rank, 1.0, AU, ldu, AV, ldv, 0.0, Dense, lda); if(rank == -1){ //means that tile is dense. rank = m; fprintf(stderr, "%s %s %d: Dense off-diagonal block (%d,%d). maxrank:%d\n", __FILE__, __func__, __LINE__, ii, jj, maxrank); exit(0); } if(rank == 0) rank = 1; Ark[0] = rank; if(store_only_diagonal_tiles == 1) { assert(AD != saveAD); free(AD); } if(global_always_fixed_rank == 1) { global_fixed_rank = rank; } if(print_mat){ printf("%d\tgytlr-UV-output\n", __LINE__); _printmat(AD, m, n, lda); _printmat(AU, m, rank, ldu); _printmat(AV, ldv, rank, ldv); } } else { Ark[0] = m; if(print_mat){ printf("%d\tgytlr-DENSE-output\n", __LINE__); _printmat(AD, m, m, lda); } } /*printf("m:%d n:%d Tile %d,%d rk:%d lda:%d maxrank:%d oversample:%d tol:%.2e AD:%p AU:%p AV:%p\n", */ /*m, n, ii, jj, rank, lda, maxrank, oversample, tol, AD, AU, AV);*/ /*double *tmp = AD;*/ /*for (i = 0; i < m; ++i) {*/ /*for (j=0; j<n; ++j ) {*/ /*printf("%+.2e ",tmp[j*lda+i]);*/ /*}*/ /*printf("\n");*/ /*}*/ /*printf("\n");*/ free(work); free(iwork); if(print_index || print_index_end ){ gettimeofday (&tvalAfter, NULL); fprintf(stderr, "-GYTLR\t|(%d,%d) rk:%g m:%d n:%d lda:%d ldu:%d ldv:%d\t\t\t\t\tGYTLR: %.4f\n",ii,jj,Ark[0],m, n, lda, ldu, ldv, (tvalAfter.tv_sec - tvalBefore.tv_sec) +(tvalAfter.tv_usec - tvalBefore.tv_usec)/1000000.0 ); } } /* MORSE_TASK_zgytlr - Generate a tile for random matrix. */ void HICMA_TASK_zgytlr( const MORSE_option_t *options, int m, int n, const MORSE_desc_t *AUV, const MORSE_desc_t *Ark, int Am, int An, int lda, int ldu, int ldv, int bigM, int m0, int n0, unsigned long long int seed, int maxrank, double tol, int compress_diag, MORSE_desc_t *Dense ) { struct starpu_codelet *codelet = &cl_zgytlr; //void (*callback)(void*) = options->profiling ? cl_zgytlr_callback : NULL; void (*callback)(void*) = NULL; int nAUV = AUV->nb; MORSE_BEGIN_ACCESS_DECLARATION; MORSE_ACCESS_W(AUV, Am, An); MORSE_ACCESS_W(Ark, Am, An); MORSE_ACCESS_RW(Dense, Am, An); MORSE_END_ACCESS_DECLARATION; //printf("%s:%d: Am:%d An:%d lda:%d bigM:%d m0:%d n0:%d\n ", __FILE__, __LINE__, Am, An, lda, bigM, m0, n0); //printf("%s %d: Am:%d An:%d ADm:%d ADn:%d ptr:%p\n", __func__, __LINE__, Am, An, ADm, ADn, ptr); starpu_insert_task( starpu_mpi_codelet(codelet), STARPU_VALUE, &m, sizeof(int), STARPU_VALUE, &n, sizeof(int), STARPU_VALUE, &nAUV, sizeof(int), STARPU_W, RTBLKADDR(AUV, double, Am, An), STARPU_W, RTBLKADDR(Ark, double, Am, An), STARPU_RW, RTBLKADDR(Dense, double, Am, An), // _R must be _W SERIOUSLY. BUT _W STALLS ON SHAHEEN. FIXME STARPU_VALUE, &lda, sizeof(int), STARPU_VALUE, &ldu, sizeof(int), STARPU_VALUE, &ldv, sizeof(int), STARPU_VALUE, &bigM, sizeof(int), STARPU_VALUE, &Am, sizeof(int), STARPU_VALUE, &An, sizeof(int), STARPU_VALUE, &seed, sizeof(unsigned long long int), STARPU_VALUE, &maxrank, sizeof(int), STARPU_VALUE, &tol, sizeof(double), STARPU_VALUE, &compress_diag, sizeof(int), STARPU_PRIORITY, options->priority, STARPU_CALLBACK, callback, #if defined(CHAMELEON_CODELETS_HAVE_NAME) STARPU_NAME, "zgytlr", #endif 0); } /* cl_zgytlr_cpu_func - Generate a tile for random matrix. */ #if !defined(CHAMELEON_SIMULATION) static void cl_zgytlr_cpu_func(void *descr[], void *cl_arg) { int m; int n; int nAUV; double *AUV; double *AD = NULL; double *Ark; double *Dense; int lda; int ldu; int ldv; int bigM; int m0; int n0; unsigned long long int seed; int maxrank; double tol; int compress_diag; AUV = (double *)STARPU_MATRIX_GET_PTR(descr[0]); Ark = (double *)STARPU_MATRIX_GET_PTR(descr[1]); Dense = (double *)STARPU_MATRIX_GET_PTR(descr[2]); starpu_codelet_unpack_args(cl_arg, &m, &n, &nAUV, &lda, &ldu, &ldv, &bigM, &m0, &n0, &seed, &maxrank, &tol, &compress_diag ); double *AU = AUV; int nAU = nAUV/2; assert(ldu == ldv); size_t nelm_AU = (size_t)ldu * (size_t)nAU; double *AV = &(AUV[nelm_AU]); //printf("(%d,%d)%d %s %d %d\n", m0/m,n0/n,MORSE_My_Mpi_Rank(), __func__, __LINE__, AD == Dense); zgytlr( m, n, AU, AV, AD, Ark, lda, ldu, ldv, bigM, m0, n0, seed, maxrank, tol, compress_diag, Dense ); } #endif /* !defined(CHAMELEON_SIMULATION) */ /* * Codelet definition */ CODELETS_CPU(zgytlr, 3, cl_zgytlr_cpu_func)
{ "alphanum_fraction": 0.5300337658, "avg_line_length": 33.7957957958, "ext": "c", "hexsha": "4dac56d04bda973f700a8c979d77afc1d0c70ce1", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-03T22:26:56.000Z", "max_forks_repo_forks_event_min_datetime": "2017-11-21T07:35:55.000Z", "max_forks_repo_head_hexsha": "1807f9628df516d20d6265fdf0573c9bc9bf033b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "SamCao1991/hicma", "max_forks_repo_path": "runtime/starpu/codelets/codelet_zgytlr.c", "max_issues_count": 3, "max_issues_repo_head_hexsha": "1807f9628df516d20d6265fdf0573c9bc9bf033b", "max_issues_repo_issues_event_max_datetime": "2020-06-27T07:44:31.000Z", "max_issues_repo_issues_event_min_datetime": "2020-01-21T12:24:22.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "SamCao1991/hicma", "max_issues_repo_path": "runtime/starpu/codelets/codelet_zgytlr.c", "max_line_length": 136, "max_stars_count": 19, "max_stars_repo_head_hexsha": "1807f9628df516d20d6265fdf0573c9bc9bf033b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "SamCao1991/hicma", "max_stars_repo_path": "runtime/starpu/codelets/codelet_zgytlr.c", "max_stars_repo_stars_event_max_datetime": "2022-03-29T09:37:50.000Z", "max_stars_repo_stars_event_min_datetime": "2017-11-27T11:17:49.000Z", "num_tokens": 3300, "size": 11254 }
#ifndef IAIF_H #define IAIF_H #include <utility> #include <tuple> #include <gsl/gsl_vector.h> #include "constants.h" #include "lpc.h" #include "filter.h" void computeIAIF(gsl_vector *g, gsl_vector *dg, gsl_vector *x); #endif // IAIF_H
{ "alphanum_fraction": 0.7178423237, "avg_line_length": 14.1764705882, "ext": "h", "hexsha": "dc65fd75ab1434aa53b8c1310c90298d766465c0", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-03-27T14:41:25.000Z", "max_forks_repo_forks_event_min_datetime": "2019-04-27T00:23:35.000Z", "max_forks_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ichi-rika/glottal-inverse", "max_forks_repo_path": "inc/iaif.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "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": "ichi-rika/glottal-inverse", "max_issues_repo_path": "inc/iaif.h", "max_line_length": 63, "max_stars_count": 6, "max_stars_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ichi-rika/glottal-inverse", "max_stars_repo_path": "inc/iaif.h", "max_stars_repo_stars_event_max_datetime": "2021-05-26T16:22:08.000Z", "max_stars_repo_stars_event_min_datetime": "2019-01-24T17:01:28.000Z", "num_tokens": 69, "size": 241 }
#include <bindings.cmacros.h> #include <gsl/gsl_monte_plain.h> #include <gsl/gsl_monte_miser.h> #include <gsl/gsl_monte_vegas.h> BC_INLINE2(GSL_MONTE_FN_EVAL,gsl_monte_function*,double*,double)
{ "alphanum_fraction": 0.8102564103, "avg_line_length": 27.8571428571, "ext": "c", "hexsha": "17f650b95d6f5ca113f0d5e33164357b6396423e", "lang": "C", "max_forks_count": 19, "max_forks_repo_forks_event_max_datetime": "2021-09-10T19:31:38.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-03T20:43:08.000Z", "max_forks_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "flip111/bindings-dsl", "max_forks_repo_path": "bindings-gsl/src/Bindings/Gsl/MonteCarloIntegration.c", "max_issues_count": 23, "max_issues_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_issues_repo_issues_event_max_datetime": "2021-04-07T09:49:12.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-04T06:32:10.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "flip111/bindings-dsl", "max_issues_repo_path": "bindings-gsl/src/Bindings/Gsl/MonteCarloIntegration.c", "max_line_length": 64, "max_stars_count": 25, "max_stars_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "flip111/bindings-dsl", "max_stars_repo_path": "bindings-gsl/src/Bindings/Gsl/MonteCarloIntegration.c", "max_stars_repo_stars_event_max_datetime": "2022-02-06T09:29:03.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-29T00:31:20.000Z", "num_tokens": 61, "size": 195 }
/** * * @file core_dssssm.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 Hatem Ltaief * @author Mathieu Faverge * @author Jakub Kurzak * @date 2010-11-15 * @generated d Tue Jan 7 11:44:45 2014 * **/ #include <cblas.h> #include "common.h" /***************************************************************************//** * * @ingroup CORE_double * * CORE_dssssm applies the LU factorization update from a complex * matrix formed by a lower triangular IB-by-K tile L1 on top of a * M2-by-K tile L2 to a second complex matrix formed by a M1-by-N1 * tile A1 on top of a M2-by-N2 tile A2 (N1 == N2). * * This is the right-looking Level 2.5 BLAS version of the algorithm. * ******************************************************************************* * * @param[in] M1 * The number of rows of the tile A1. M1 >= 0. * * @param[in] N1 * The number of columns of the tile A1. N1 >= 0. * * @param[in] M2 * The number of rows of the tile A2 and of the tile L2. * M2 >= 0. * * @param[in] N2 * The number of columns of the tile A2. N2 >= 0. * * @param[in] K * The number of columns of the tiles L1 and L2. K >= 0. * * @param[in] IB * The inner-blocking size. IB >= 0. * * @param[in,out] A1 * On entry, the M1-by-N1 tile A1. * On exit, A1 is updated by the application of L (L1 L2). * * @param[in] LDA1 * The leading dimension of the array A1. LDA1 >= max(1,M1). * * @param[in,out] A2 * On entry, the M2-by-N2 tile A2. * On exit, A2 is updated by the application of L (L1 L2). * * @param[in] LDA2 * The leading dimension of the array A2. LDA2 >= max(1,M2). * * @param[in] L1 * The IB-by-K lower triangular tile as returned by * CORE_dtstrf. * * @param[in] LDL1 * The leading dimension of the array L1. LDL1 >= max(1,IB). * * @param[in] L2 * The M2-by-K tile as returned by CORE_dtstrf. * * @param[in] LDL2 * The leading dimension of the array L2. LDL2 >= max(1,M2). * * @param[in] IPIV * The pivot indices array of size K as returned by * CORE_dtstrf. * ******************************************************************************* * * @return * \retval PLASMA_SUCCESS successful exit * \retval <0 if INFO = -k, the k-th argument had an illegal value * ******************************************************************************/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_dssssm = PCORE_dssssm #define CORE_dssssm PCORE_dssssm #endif int CORE_dssssm(int M1, int N1, int M2, int N2, int K, int IB, double *A1, int LDA1, double *A2, int LDA2, const double *L1, int LDL1, const double *L2, int LDL2, const int *IPIV) { static double zone = 1.0; static double mzone =-1.0; int i, ii, sb; int im, ip; /* Check input arguments */ if (M1 < 0) { coreblas_error(1, "Illegal value of M1"); return -1; } if (N1 < 0) { coreblas_error(2, "Illegal value of N1"); return -2; } if (M2 < 0) { coreblas_error(3, "Illegal value of M2"); return -3; } if (N2 < 0) { coreblas_error(4, "Illegal value of N2"); return -4; } if (K < 0) { coreblas_error(5, "Illegal value of K"); return -5; } if (IB < 0) { coreblas_error(6, "Illegal value of IB"); return -6; } if (LDA1 < max(1,M1)) { coreblas_error(8, "Illegal value of LDA1"); return -8; } if (LDA2 < max(1,M2)) { coreblas_error(10, "Illegal value of LDA2"); return -10; } if (LDL1 < max(1,IB)) { coreblas_error(12, "Illegal value of LDL1"); return -12; } if (LDL2 < max(1,M2)) { coreblas_error(14, "Illegal value of LDL2"); return -14; } /* Quick return */ if ((M1 == 0) || (N1 == 0) || (M2 == 0) || (N2 == 0) || (K == 0) || (IB == 0)) return PLASMA_SUCCESS; ip = 0; for(ii = 0; ii < K; ii += IB) { sb = min(K-ii, IB); for(i = 0; i < sb; i++) { im = IPIV[ip]-1; if (im != (ii+i)) { im = im - M1; cblas_dswap(N1, &A1[ii+i], LDA1, &A2[im], LDA2); } ip = ip + 1; } cblas_dtrsm( CblasColMajor, CblasLeft, CblasLower, CblasNoTrans, CblasUnit, sb, N1, (zone), &L1[LDL1*ii], LDL1, &A1[ii], LDA1); cblas_dgemm( CblasColMajor, CblasNoTrans, CblasNoTrans, M2, N2, sb, (mzone), &L2[LDL2*ii], LDL2, &A1[ii], LDA1, (zone), A2, LDA2); } return PLASMA_SUCCESS; }
{ "alphanum_fraction": 0.4929155857, "avg_line_length": 27.2336956522, "ext": "c", "hexsha": "367b1c5015a39e04207a6c35177712993ad2a3c5", "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_dssssm.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_dssssm.c", "max_line_length": 82, "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_dssssm.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1565, "size": 5011 }
/* Copyright [2017-2020] [IBM Corporation] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef __SHARD_CONNECTION_H__ #define __SHARD_CONNECTION_H__ #ifdef __cplusplus #include "tls_session.h" #include "buffer_manager.h" #include "fabric_connection_base.h" // default to fabric transport #include "mcas_config.h" #include "pool_manager.h" #include "protocol.h" #include "protocol_ostream.h" #include "region_manager.h" #include "connection_state.h" #include <api/components.h> #include <api/fabric_itf.h> #include <api/kvstore_itf.h> #include <common/exceptions.h> #include <common/logging.h> #include <gsl/pointers> #include <cassert> #include <map> #include <queue> #include <utility> /* swap */ #include <vector> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Weffc++" namespace mcas { using Connection_base = Fabric_connection_base; /** * Connection handler is instantiated for each "connected" client */ class Connection_handler : public Connection_base, public Region_manager, private Connection_TLS_session { friend class Connection_TLS_session; friend struct TLS_transport; public: enum { TICK_RESPONSE_CONTINUE = 0, TICK_RESPONSE_BOOTSTRAP_SPAWN = 1, TICK_RESPONSE_WAIT_SECURITY = 2, TICK_RESPONSE_CLOSE = 0xFF, }; enum { ACTION_NONE = 0, ACTION_RELEASE_VALUE_LOCK_EXCLUSIVE, ACTION_POOL_DELETE, }; private: Connection_state _state = Connection_state::INITIAL; unsigned option_DEBUG = mcas::global::debug_level; /* list of pre-registered memory regions; normally one region */ std::vector<component::IKVStore::memory_handle_t> _mr_vector; uint64_t _tick_count alignas(8); uint64_t _auth_id; std::queue<buffer_t *> _pending_msgs; std::queue<action_t> _pending_actions; Pool_manager _pool_manager; /* instance shared across connections */ /* Adaptor point for different transports */ using Connection = component::IFabric_server; using Factory = component::IFabric_server_factory; struct stats { uint64_t response_count; uint64_t recv_msg_count; uint64_t send_msg_count; uint64_t wait_send_value_misses; uint64_t wait_msg_recv_misses; uint64_t wait_respond_complete_misses; uint64_t last_count; uint64_t next_stamp; stats() : response_count(0), recv_msg_count(0), send_msg_count(0), wait_send_value_misses(0), wait_msg_recv_misses(0), wait_respond_complete_misses(0), last_count(0), next_stamp(0) { } } _stats alignas(8); void dump_stats() { PINF("-----------------------------------------"); PINF("| Connection Handler Statistics |"); PINF("-----------------------------------------"); PINF("Ticks : %lu", _tick_count); PINF("Open pools : %lu", _pool_manager.open_pool_count()); PINF("NEW_MSG_RECV misses : %lu", _stats.wait_msg_recv_misses); PINF("Recv message count : %lu", _stats.recv_msg_count); PINF("Send message count : %lu", _stats.send_msg_count); PINF("Response count : %lu", _stats.response_count); PINF("WAIT_SEND_VALUE misses : %lu", _stats.wait_send_value_misses); PINF("WAIT_RESPOND_COMPLETE misses: %lu", _stats.wait_respond_complete_misses); PINF("-----------------------------------------"); } /** * Change state in FSM * * @param s */ inline void set_state(Connection_state s) { if (2 < option_DEBUG) { const std::map<Connection_state, const char *> m{ {Connection_state::INITIAL, "INITIAL"}, {Connection_state::WAIT_HANDSHAKE, "WAIT_HANDSHAKE"}, {Connection_state::WAIT_TLS_HANDSHAKE, "WAIT_TLS_HANDSHAKE"}, {Connection_state::CLIENT_DISCONNECTED, "CLIENT_DISCONNECTED"}, {Connection_state::CLOSE_CONNECTION, "CLOSE_CONNECTION"}, {Connection_state::WAIT_NEW_MSG_RECV, "WAIT_NEW_MSG_RECV"}}; PLOG("state %s -> %s", m.find(_state)->second, m.find(s)->second); } _state = s; /* we could add transition checking later */ } static void static_send_callback2(void *cnxn, buffer_t *iob) noexcept { auto base = static_cast<Fabric_connection_base *>(cnxn); static_cast<Connection_handler *>(base)->send_callback2(iob); } void send_callback2(buffer_t *iob) noexcept { assert(iob->value_adjunct); if (0 < option_DEBUG) { PLOG("Completed send2 (value_adjunct %p)", common::p_fmt(iob->value_adjunct)); } _deferred_unlock.push(iob->value_adjunct); send_callback(iob); } /** * Send handshake response * * @param start_tls Set if a TLS handshake needs to be started */ void respond_to_handshake(bool start_tls); public: explicit Connection_handler(unsigned debug_level, gsl::not_null<Factory *> factory, gsl::not_null<Connection *> connection); virtual ~Connection_handler(); inline bool client_connected() { return _state != Connection_state::CLIENT_DISCONNECTED; } auto allocate_send() { return allocate(static_send_callback); } auto allocate_recv() { return allocate(static_recv_callback); } /** * Initialize security session * * @param bind_ipaddr * @param bind_port */ void configure_security(const std::string& bind_ipaddr, const unsigned bind_port, const std::string& cert_file, const std::string& key_file); /** * State machine transition tick. It is really important that this tick * execution duration is small, so that other connections are not impacted by * the thread not returning to them. * */ int tick(); /** * Check for network completions * */ Fabric_connection_base::Completion_state check_network_completions() { auto state = poll_completions(); while (!_deferred_unlock.empty()) { // void *deferred_unlock = nullptr; //??? std::swap(deferred_unlock, _deferred_unlock.front()); void *deferred_unlock = _deferred_unlock.front(); if (option_DEBUG > 2) PLOG("adding action for deferred unlocking value @ %p", deferred_unlock); add_pending_action(action_t{ACTION_RELEASE_VALUE_LOCK_EXCLUSIVE, deferred_unlock}); _deferred_unlock.pop(); } return state; } /** * Peek at pending message from the connection. Used when the resources * required to process a pending nessage may depend on the content of the * message. * * @param msg [out] Pointer to base protocol message * * @return Pointer to buffer holding the message or null if there are none */ inline mcas::protocol::Message *peek_pending_msg() const { return _pending_msgs.empty() ? nullptr : static_cast<mcas::protocol::Message *>(_pending_msgs.front()->base().get()); } /** * Discard a pending message from the connection. Used along with tick * (which adds pending messages) and peek (which peeks at them). * * @param msg [out] Pointer to base protocol message * * @return Pointer to buffer holding the message or null if there are none */ inline buffer_t *pop_pending_msg() { assert(!_pending_msgs.empty()); auto iob = _pending_msgs.front(); _pending_msgs.pop(); return iob; } /** * Get deferred actions * * @param action [out] Action * * @return True if action */ inline bool get_pending_action(action_t &action) { if (_pending_actions.empty()) return false; action = _pending_actions.front(); if (option_DEBUG > 2) PLOG("Connection_handler: popped pending action (%u, %p)", action.op, action.parm); _pending_actions.pop(); return true; } template <typename MT> void msg_log(const unsigned level_, const MT *msg_, const char *desc_, const char *direction_) { if (level_ < Connection_base::debug_level()) { std::ostringstream m; m << *msg_; PLOG("%s (%s) %s", direction_, desc_, m.str().c_str()); } } template <typename MT> void msg_recv_log(const MT *m, const char *desc) { msg_recv_log(1, m, desc); } template <typename MT> void msg_recv_log(const unsigned level, const MT *msg, const char *desc) { msg_log(level, msg, desc, "RECV"); } template <typename MT> void msg_send_log(const MT *m, const char *desc) { msg_send_log(1, m, desc); } template <typename MT> void msg_send_log(const unsigned level, const MT *msg, const char *desc) { msg_log(level, msg, desc, "SEND"); } /** * Add an action to the pending queue * * @param action Action to add */ inline void add_pending_action(const action_t& action) { _pending_actions.push(action); } template <typename Msg> void post_send_buffer(gsl::not_null<buffer_t *> buffer, Msg *msg, const char *desc) { msg_send_log(msg, desc); Connection_base::post_send_buffer(buffer); } template <typename Msg> void post_send_buffer_with_value(gsl::not_null<buffer_t *> buffer, const ::iovec & val_iov, void * val_desc, Msg * msg, const char * func_name) { msg_send_log(msg, func_name); Connection_base::post_send_buffer2(buffer, val_iov, val_desc); } /** * Post a response * * @param iob IO buffer to post */ template <typename Msg> inline void post_response_with_value(gsl::not_null<buffer_t *> iob, const ::iovec & val_iov, void * val_desc, Msg * msg, const char * func_name) { iob->set_completion(static_send_callback2, val_iov.iov_base); post_send_buffer_with_value(iob, val_iov, val_desc, msg, func_name); /* don't wait for this, let it be picked up in the check_completions cycle */ _stats.response_count++; } /** * Post a response * * @param iob IO buffer to post */ template <typename Msg> inline void post_response(gsl::not_null<buffer_t *> iob, Msg *msg, const char *desc) { post_send_buffer(iob, msg, desc); /* don't wait for this, let it be picked up in the check_completions cycle */ _stats.response_count++; } /** * Set up for pending value send/recv * * @param target * @param target_len * @param region */ void add_memory_handle(component::IKVStore::memory_handle_t handle) { _mr_vector.push_back(handle); } component::IKVStore::memory_handle_t pop_memory_handle() { if (_mr_vector.empty()) return nullptr; auto mr = _mr_vector.back(); _mr_vector.pop_back(); return mr; } inline uint64_t auth_id() const { return _auth_id; } inline void set_auth_id(uint64_t id) { _auth_id = id; } inline size_t max_message_size() const { return _max_message_size; } inline Pool_manager & pool_manager() { return _pool_manager; } private: common::Byte_buffer _tls_buffer; }; } // namespace mcas #pragma GCC diagnostic pop #endif #endif // __CONNECTION_HANDLER_H__
{ "alphanum_fraction": 0.6320072333, "avg_line_length": 29.8918918919, "ext": "h", "hexsha": "ad531007a56bf55c8f5dd4f152058a7aea202844", "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": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "moshik1/mcas", "max_forks_repo_path": "src/server/mcas/src/connection_handler.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "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": "moshik1/mcas", "max_issues_repo_path": "src/server/mcas/src/connection_handler.h", "max_line_length": 109, "max_stars_count": null, "max_stars_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "moshik1/mcas", "max_stars_repo_path": "src/server/mcas/src/connection_handler.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2857, "size": 12166 }
#include <stdio.h> #include <stdlib.h> #include "parmt_utils.h" #ifdef PARMT_USE_INTEL #include <mkl_cblas.h> #else #include <cblas.h> #endif #include "iscl/array/array.h" /*! * @brief The iloc'th location and iobs'th observation this sets the forward * modeling matrix G s.t. Gm = u * * @param[in] iobs observation number * @param[in] iloc location number * @param[in] npmax leading dimension of G * @param[in] data data data structure with Green's functions which will be * set on G * * @param[out] G column major modeling matrix s.t. Gm=u where * G is packed * \f$ \{ G_{xx}, G_{yy}, G_{zz}, * G_{xy}, G_{xz}, G_{yz} \} \f$ * and m is in NED ordering [npmax x 6] * * @result 0 indicates success * */ int parmt_utils_setDataOnG(const int iobs, const int iloc, const int npmax, const struct parmtData_struct data, double *__restrict__ G) { const char *fcnm = "parmt_utils_setDataOnG\0"; int k; if (iobs < 0 || iobs >= data.nobs) { printf("%s: Error invalid observation\n", fcnm); return -1; } if (iloc < 0 || iloc >= data.nlocs) { printf("%s: Error invalid location\n", fcnm); return -1; } k = iobs*data.nlocs + iloc; if (npmax > data.sacGxx[k].npts || npmax > data.sacGyy[k].npts || npmax > data.sacGzz[k].npts || npmax > data.sacGxy[k].npts || npmax > data.sacGxz[k].npts || npmax > data.sacGyz[k].npts) { printf("%s: npmax is too small\n", fcnm); return -1; } if (data.sacGxx[k].data == NULL || data.sacGyy[k].data == NULL || data.sacGzz[k].data == NULL || data.sacGxy[k].data == NULL || data.sacGxz[k].data == NULL || data.sacGyz[k].data == NULL) { printf("%s: Greens function is null\n", fcnm); return -1; } // Get the Green's functions onto the matrix G array_zeros64f_work(6*npmax, G); cblas_dcopy(data.sacGxx[k].header.npts, data.sacGxx[k].data, 1, &G[0*npmax], 1); cblas_dcopy(data.sacGyy[k].header.npts, data.sacGyy[k].data, 1, &G[1*npmax], 1); cblas_dcopy(data.sacGzz[k].header.npts, data.sacGzz[k].data, 1, &G[2*npmax], 1); cblas_dcopy(data.sacGxy[k].header.npts, data.sacGxy[k].data, 1, &G[3*npmax], 1); cblas_dcopy(data.sacGxz[k].header.npts, data.sacGxz[k].data, 1, &G[4*npmax], 1); cblas_dcopy(data.sacGyz[k].header.npts, data.sacGyz[k].data, 1, &G[5*npmax], 1); return 0; }
{ "alphanum_fraction": 0.5480662983, "avg_line_length": 35.2597402597, "ext": "c", "hexsha": "45d172d47bb96d31f1eb0aa973022b9dababaf2e", "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": "utils/setDataOnG.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": "utils/setDataOnG.c", "max_line_length": 78, "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": "utils/setDataOnG.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 874, "size": 2715 }
/* * Tema 2 ASC * 2019 Spring * Catalin Olaru / Vlad Spoiala */ #include <cblas.h> #include "utils.h" /* * Add your BLAS implementation here */ double* my_solver(int N, double *A, double *B) { double *first_multiplication = malloc(N * N * sizeof(double)); double *second_multiplication = malloc(N * N * sizeof(double)); double *final_result = malloc(N * N * sizeof(double)); double alpha = 1.0; double beta = 0.0; double *identity_matrix = malloc(N * N * sizeof(double)); int i, j; /* Compute identity matrix so we can use it later on. */ for (i = 0; i < N; ++i) for (j = 0; j < N; ++j) identity_matrix[i * N + j] = j == i ? 1.0 : 0.0; /* Compute Transpose(A) * B in first_multiplication. */ cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, N, N, N, alpha, A, N, B, N, beta, first_multiplication, N); /* Compute Transpose(B) * A in second_multiplication. */ cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, N, N, N, alpha, B, N, A, N, beta, second_multiplication, N); /* Add the previous 2 results in second multiplication. */ cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, N, N, N, alpha, first_multiplication, N, identity_matrix, N, alpha, second_multiplication, N); /* Apply zerotr(second_multiplication) as everything involving * CblasLower or CblasUpper didn't work for some reason. :( */ for (i = 0; i < N; ++i) for (j = 0; j < i; ++j) second_multiplication[i * N + j] = 0; /* Multiply second_multiplication by itself so we get the * result in final_result. */ cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, N, N, N, alpha, second_multiplication, N, second_multiplication, N, beta, final_result, N); /* Free everything aside from the return value. */ free(first_multiplication); free(second_multiplication); free(identity_matrix); return final_result; }
{ "alphanum_fraction": 0.6227897839, "avg_line_length": 19.7669902913, "ext": "c", "hexsha": "c477747b1d62ee85f0cf00516e8bf22e715d3aa8", "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": "a51a56f814998561a0960deebb7e6be780c6f512", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "AlexFazakas/matrix-multiplication-optimizations", "max_forks_repo_path": "solver_blas.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "a51a56f814998561a0960deebb7e6be780c6f512", "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": "AlexFazakas/matrix-multiplication-optimizations", "max_issues_repo_path": "solver_blas.c", "max_line_length": 64, "max_stars_count": null, "max_stars_repo_head_hexsha": "a51a56f814998561a0960deebb7e6be780c6f512", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "AlexFazakas/matrix-multiplication-optimizations", "max_stars_repo_path": "solver_blas.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 608, "size": 2036 }
#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_stack_code.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_neurotrace.h" #include "tz_locseg_chain.h" #include "tz_trace_utils.h" #include "tz_stack_threshold.h" #include "tz_darray.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]; #if 1 sprintf(file_path, "../data/%s/bundle_seed.tif", neuron_name); Stack *stack = Read_Stack(file_path); Voxel_List *list = Stack_To_Voxel_List(stack); sprintf(file_path, "../data/%s/bundle_seeds.pa", neuron_name); Pixel_Array *pa = Pixel_Array_Read(file_path); Voxel *seed; int i; double *pa_array = (double *) pa->array; printf("mean: %g, std: %g\n", gsl_stats_mean(pa_array, 1, pa->size), sqrt(gsl_stats_variance(pa_array, 1, pa->size))); double threshold = gsl_stats_mean(pa_array, 1, pa->size) + 3.0 * sqrt(gsl_stats_variance(pa_array, 1, pa->size)); double max_r = gsl_stats_max(pa_array, 1, pa->size); printf("%g, %g\n", threshold, max_r); max_r = max_r * 2; Set_Neuroseg_Max_Radius(max_r / 2.0); dim_type dim[3]; dim[0] = stack->width; dim[1] = stack->height; dim[2] = stack->depth; Kill_Stack(stack); sprintf(file_path, "../data/%s/bundle.tif", neuron_name); stack = Read_Stack(file_path); Rgb_Color color; Set_Color(&color, 255, 0, 0); sprintf(file_path, "../data/%s.tif", neuron_name); Stack *signal = Read_Stack(file_path); Stack *canvas = NULL; char trace_mask_path[100]; sprintf(trace_mask_path, "../data/%s/trace_mask.tif", neuron_name); char trace_file_path[100]; sprintf(trace_file_path, "../data/%s/traced.tif", neuron_name); if (fexist(trace_file_path) == 1) { canvas = Read_Stack((char *) trace_file_path); } else { canvas = Translate_Stack(signal, COLOR, 0); } Stack *traced = NULL; if (fexist(trace_mask_path) == 1) { traced = Read_Stack((char *) trace_mask_path); if (traced->kind != GREY16) { Translate_Stack(traced, GREY16, 1); } } else { traced = Make_Stack(GREY16, signal->width, signal->height, signal->depth); Zero_Stack(traced); } Neurochain *chain = NULL; double z_scale = 1.0; sprintf(file_path, "../data/%s.res", neuron_name); if (fexist(file_path)) { double res[3]; int length; darray_read2(file_path, res, &length); if (res[0] != res[1]) { perror("Different X-Y resolutions."); TZ_ERROR(ERROR_DATA_VALUE); } z_scale = res[0] / res[2]; } /* sprintf(file_path, "../data/%s/soma.tif", neuron_name); Stack *soma = Read_Stack(file_path); Stack_Threshold(soma, 1); Stack_Binarize(soma); Stack_Not(soma, soma); Stack_And(traced, soma, traced); Kill_Stack(soma); */ tic(); FILE *fp = NULL; char chain_file_path[100]; char vrml_file_path[100]; int seg_idx = 229; int min_chain_length = 4; #define TRY_NEXT_SEED(current_seed) \ Kill_Voxel(current_seed); \ continue; #define STOP_TRACING(current_seed) \ Kill_Voxel(current_seed); \ break; Trace_Workspace *tw = New_Trace_Workspace(); tw->length = 200; tw->fit_first = FALSE; tw->tscore_option = 1; tw->min_score = 0.4; tw->trace_direction = DL_BOTHDIR; tw->trace_mask = traced; tw->dyvar[0] = max_r; tw->test_func = Locseg_Chain_Trace_Test; int chain_id = 100; char chain_info_file_path[100]; sprintf(chain_info_file_path, "../data/%s/chain_info.txt", neuron_name); FILE *chain_info_file = fopen(chain_info_file_path, "w"); for (i = 0; i < pa->size; i++) { /* do not skip seed dequeueing */ seed = Voxel_Queue_De(&list); printf("---------------------------------> seed: %d / %d\n", i, pa->size); sprintf(chain_file_path, "../data/%s/chain%d.bn", neuron_name, i); sprintf(vrml_file_path, "../data/%s/chain%d.wrl", neuron_name, i); if (fexist(chain_file_path) == 1) { chain = Read_Neurochain(chain_file_path); if (Neurochain_Length(chain, FORWARD) >= min_chain_length) { Write_Neurochain_Vrml(vrml_file_path, chain); } Neurochain_Label(canvas, chain, z_scale); Free_Neurochain(chain); TRY_NEXT_SEED(seed); } /* for debugging */ if (i < seg_idx) { //TRY_NEXT_SEED(seed); } /****************/ if (*STACK_PIXEL_16(traced, seed->x, seed->y, seed->z, 0) > 0) { TRY_NEXT_SEED(seed); } double width = pa_array[i]; if (width > max_r) { TRY_NEXT_SEED(seed); } Print_Voxel(seed); printf("%g\n", width); int max_level = (int) (width + 0.5); if (max_level < 1.1) { TRY_NEXT_SEED(seed); //max_level = 6; } /* for debugging */ if (i > seg_idx) { //STOP_TRACING(seed); } /****************/ double cpos[3]; cpos[0] = seed->x; cpos[1] = seed->y; cpos[2] = seed->z; cpos[2] *= z_scale; Local_Neuroseg *startseg = New_Local_Neuroseg();; Set_Neuroseg_Position(startseg, cpos, NEUROSEG_CENTER); Reset_Neuroseg(&(startseg->seg)); startseg->seg.r1 = width; startseg->seg.r2 = width; Stack_Fit_Score fs; fs.n = 1; fs.options[0] = tw->tscore_option; printf("Search orientation ...\n"); Local_Neuroseg_Orientation_Search_C(startseg, signal, z_scale, &fs); Print_Local_Neuroseg(startseg); printf("Start: \n"); Locseg_Chain* locseg_chain = Locseg_Chain_Trace_Init(signal, z_scale, startseg, &fs); if (fs.scores[0] >= tw->min_score) { Locseg_Chain_Iterator_Start(locseg_chain, DL_HEAD); Local_Neuroseg *head = Locseg_Chain_Next(locseg_chain); if ((head->seg.r1 < max_r) && (head->seg.r2 < max_r)) { Trace_Locseg(signal, z_scale, locseg_chain, tw); chain = Neurochain_From_Locseg_Chain(locseg_chain); //chain = Trace_Neuron2(signal, chain, BOTH, traced, z_scale, 100); printf("Remove ends ...\n"); chain = Neurochain_Remove_Overlap_Ends(chain); chain = Neurochain_Remove_Turn_Ends(chain, 1.0); //Print_Neurochain(Neurochain_Head(chain)); //Stack_Draw_Object_Bwc(canvas, obj, color); Neurochain *chain_head = Neurochain_Head(chain); printf("Saving ...\n"); fp = fopen(chain_file_path, "w"); Neurochain_Fwrite(chain_head, fp); fclose(fp); if (Neurochain_Length(chain_head, FORWARD) >= min_chain_length) { printf("Labeling ...\n"); Write_Neurochain_Vrml(vrml_file_path, chain_head); Neurochain_Label_G(trac, chain_head, z_scale, 0, Neurochain_Length(chain_head, FORWARD), 1.5, 0.0, chain_id); fprintf(chain_info_file, "%d %d %d\n", i, chain_id, Neurochain_Length(chain_head, FORWARD)); chain_id++; Neurochain_Label(canvas, chain_head, z_scale); Write_Stack((char *) trace_mask_path, traced); } //Neurochain_Erase(traced, Neurochain_Head(chain), z_scale); Free_Neurochain(chain); } } else { printf("Ignored seed:\n"); } Kill_Locseg_Chain(locseg_chain); Kill_Voxel(seed); } fclose(chain_info_file); Write_Stack((char *) trace_file_path, canvas); Kill_Pixel_Array(pa); Voxel_List_Removeall(&list); printf("Time passed: %lld\n", toc()); #endif return 0; }
{ "alphanum_fraction": 0.6528872239, "avg_line_length": 25.6324503311, "ext": "c", "hexsha": "45e514888f44841025665ab0d18be8585309d454", "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/trace_fly_neuron3.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/trace_fly_neuron3.c", "max_line_length": 78, "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/trace_fly_neuron3.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": 2341, "size": 7741 }
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* ** ** ** 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. ** ** ** **~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/ #include <stdlib.h> #include <string.h> #include <assert.h> #include <mpi.h> #include <petsc.h> #include <petscvec.h> #include <petscmat.h> #include <petscksp.h> #include <petscpc.h> #include <petscsnes.h> #include <petscversion.h> #if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >=3) ) #if (PETSC_VERSION_MINOR >=6) #include <petsc/private/kspimpl.h> #else #include <petsc-private/kspimpl.h> /*I "petscksp.h" I*/ //#include "petsc-private/kspimpl.h" #endif #else #include "private/kspimpl.h" /*I "petscksp.h" I*/ #endif #include <StGermain/libStGermain/src/StGermain.h> #include <StgDomain/libStgDomain/src/StgDomain.h> #include <StgFEM/libStgFEM/src/StgFEM.h> #include <PICellerator/libPICellerator/src/PICellerator.h> #include <Underworld/libUnderworld/src/Underworld.h> #include "Solvers/SLE/src/SLE.h" /* to give the AugLagStokes_SLE type */ #include "Solvers/KSPSolvers/src/KSPSolvers.h" #include "BSSCR.h" #include "createK2.h" #include "writeMatVec.h" #include "ksp_pressure_nullspace.h" #define KSPBSSCR "bsscr" EXTERN_C_BEGIN EXTERN PetscErrorCode PETSCKSP_DLLEXPORT KSPCreate_BSSCR(KSP); EXTERN_C_END PetscErrorCode BSSCR_DRIVER_auglag( KSP ksp, Mat stokes_A, Vec stokes_x, Vec stokes_b, Mat approxS, MatStokesBlockScaling BA, PetscTruth sym, KSP_BSSCR * bsscrp_self ); PetscErrorCode BSSCR_DRIVER_flex( KSP ksp, Mat stokes_A, Vec stokes_x, Vec stokes_b, Mat approxS, KSP ksp_K, MatStokesBlockScaling BA, PetscTruth sym, KSP_BSSCR * bsscrp_self ); /*************************************************************************************************/ /****** START Helper Functions *******************************************************************/ #define BSSCR_GetPetscMatrix( matrix ) ( (Mat)(matrix) ) /****** END Helper Functions *********************************************************************/ /*************************************************************************************************/ typedef struct { void *ctx; KSP_BSSCR * bsscr; } BSSCR_KSPConverged_Ctx; /*************************************************************************************************/ /*************************************************************************************************/ #undef __FUNCT__ #define __FUNCT__ "BSSCR_KSPSetConvergenceMinIts" PetscErrorCode BSSCR_KSPSetConvergenceMinIts(KSP ksp, PetscInt n, KSP_BSSCR * bsscr) { BSSCR_KSPConverged_Ctx *ctx; PetscErrorCode ierr; PetscFunctionBegin; bsscr->min_it = n; /* set minimum its */ #if ( (PETSC_VERSION_MAJOR == 3) && (PETSC_VERSION_MINOR >= 5 ) ) ierr = Stg_PetscNew(BSSCR_KSPConverged_Ctx,&ctx);CHKERRQ(ierr); ierr = KSPConvergedDefaultCreate(&ctx->ctx);CHKERRQ(ierr); ctx->bsscr=bsscr; ierr = KSPSetConvergenceTest(ksp,BSSCR_KSPConverged,ctx,BSSCR_KSPConverged_Destroy);CHKERRQ(ierr); #endif #if ( (PETSC_VERSION_MAJOR == 3) && (PETSC_VERSION_MINOR <=4 ) ) ierr = Stg_PetscNew(BSSCR_KSPConverged_Ctx,&ctx);CHKERRQ(ierr); ierr = KSPDefaultConvergedCreate(&ctx->ctx);CHKERRQ(ierr); ctx->bsscr=bsscr; ierr = KSPSetConvergenceTest(ksp,BSSCR_KSPConverged,ctx,BSSCR_KSPConverged_Destroy);CHKERRQ(ierr); #endif #if ( PETSC_VERSION_MAJOR < 3) ierr = KSPSetConvergenceTest(ksp,BSSCR_KSPConverged,(void*)bsscr);CHKERRQ(ierr); #endif PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "BSSCR_KSPConverged" PetscErrorCode BSSCR_KSPConverged(KSP ksp,PetscInt n,PetscReal rnorm,KSPConvergedReason *reason,void *cctx) { PetscErrorCode ierr; #if(PETSC_VERSION_MAJOR == 3) BSSCR_KSPConverged_Ctx *ctx = (BSSCR_KSPConverged_Ctx *)cctx; KSP_BSSCR *bsscr = ctx->bsscr; #else KSP_BSSCR *bsscr = (KSP_BSSCR*)cctx; #endif PetscFunctionBegin; #if ( (PETSC_VERSION_MAJOR == 3) && (PETSC_VERSION_MINOR >=5 ) ) ierr = KSPConvergedDefault(ksp,n,rnorm,reason,ctx->ctx);CHKERRQ(ierr); #endif #if ( (PETSC_VERSION_MAJOR == 3) && (PETSC_VERSION_MINOR <=4 ) ) ierr = KSPDefaultConverged(ksp,n,rnorm,reason,ctx->ctx);CHKERRQ(ierr); #endif #if ( PETSC_VERSION_MAJOR < 3) ierr = KSPDefaultConverged(ksp,n,rnorm,reason,cctx);CHKERRQ(ierr); #endif if (*reason) { ierr = PetscInfo2(ksp,"default convergence test KSP iterations=%D, rnorm=%G\n",n,rnorm);CHKERRQ(ierr); } if(ksp->its < bsscr->min_it){ ksp->reason = KSP_CONVERGED_ITERATING; } PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "BSSCR_KSPConverged_Destroy" PetscErrorCode BSSCR_KSPConverged_Destroy(void *cctx) { BSSCR_KSPConverged_Ctx *ctx = (BSSCR_KSPConverged_Ctx *)cctx; PetscErrorCode ierr; PetscFunctionBegin; #if ( (PETSC_VERSION_MAJOR == 3) && (PETSC_VERSION_MINOR >=5 ) ) ierr = KSPConvergedDefaultDestroy(ctx->ctx);CHKERRQ(ierr); #else ierr = KSPDefaultConvergedDestroy(ctx->ctx);CHKERRQ(ierr); #endif ierr = PetscFree(ctx);CHKERRQ(ierr); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "KSPRegisterBSSCR" PetscErrorCode PETSCKSP_DLLEXPORT KSPRegisterBSSCR(const char path[]) { PetscErrorCode ierr; PetscFunctionBegin; ierr = Stg_KSPRegister(KSPBSSCR, path, "KSPCreate_BSSCR", KSPCreate_BSSCR );CHKERRQ(ierr); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "KSPSolve_BSSCR" PetscErrorCode KSPSolve_BSSCR(KSP ksp) { Mat Amat,Pmat; /* Stokes Matrix and it's Preconditioner matrix: Both 2x2 PetscExt block matrices */ Vec B, X; /* rhs and solution vectors */ //MatStructure pflag; PetscErrorCode ierr; KSP_BSSCR * bsscr; Stokes_SLE * SLE; //PETScMGSolver * MG; Mat K,D,ApproxS; MatStokesBlockScaling BA; PetscTruth flg, sym, augment; double TotalSolveTime; PetscFunctionBegin; TotalSolveTime = MPI_Wtime(); PetscPrintf( PETSC_COMM_WORLD, "\nBSSCR -- Block Stokes Schur Compliment Reduction Solver \n"); /** Get the stokes Block matrix and its preconditioner matrix */ ierr = Stg_PCGetOperators(ksp->pc,&Amat,&Pmat,PETSC_NULL);CHKERRQ(ierr); /** In Petsc proper, KSP's ksp->data is usually set in KSPCreate_XXX function. Here it is set in the _StokesBlockKSPInterface_Solve function instead so that we can ensure that the solver has everything it needs */ bsscr = (KSP_BSSCR*)ksp->data; //MG = (PETScMGSolver*)bsscr->mg; SLE = (Stokes_SLE*)bsscr->st_sle; X = ksp->vec_sol; B = ksp->vec_rhs; if( bsscr->do_scaling ){ (*bsscr->scale)(ksp); /* scales everything including the UW preconditioner */ BA = bsscr->BA; } if( (bsscr->k2type != 0) ){ if(bsscr->buildK2 != PETSC_NULL) { (*bsscr->buildK2)(ksp); /* building K2 from scaled version of stokes operators: K2 lives on bsscr struct = ksp->data */ } } /* get sub matrix / vector objects */ MatNestGetSubMat( Amat, 0,0, &K ); /* Underworld preconditioner matrix*/ ApproxS = PETSC_NULL; if( ((StokesBlockKSPInterface*)SLE->solver)->preconditioner ) { /* SLE->solver->st_sle == SLE here, by the way */ StiffnessMatrix *preconditioner; preconditioner = ((StokesBlockKSPInterface*)SLE->solver)->preconditioner; ApproxS = BSSCR_GetPetscMatrix( preconditioner->matrix ); } sym = bsscr->DIsSym; MatNestGetSubMat( Amat, 1,0, &D );if(!D){ PetscPrintf( PETSC_COMM_WORLD, "D does not exist but should!!\n"); exit(1); } /**********************************************************/ /******* SOLVE!! ******************************************/ /**********************************************************/ flg = PETSC_FALSE; augment = PETSC_TRUE; PetscOptionsGetTruth(PETSC_NULL, "-augmented_lagrangian", &augment, &flg); BSSCR_DRIVER_auglag( ksp, Amat, X, B, ApproxS, BA, sym, bsscr ); /**********************************************************/ /***** END SOLVE!! ****************************************/ /**********************************************************/ if( bsscr->do_scaling ){ (*bsscr->unscale)(ksp); } if( (bsscr->k2type != 0) && bsscr->K2 != PETSC_NULL ){ if(bsscr->k2type != K2_SLE){/* don't destroy here, as in this case, K2 is just pointing to an existing matrix on the SLE */ Stg_MatDestroy(&bsscr->K2 ); } bsscr->K2built = PETSC_FALSE; bsscr->K2 = PETSC_NULL; } ksp->reason = KSP_CONVERGED_RTOL; TotalSolveTime = MPI_Wtime() - TotalSolveTime; PetscPrintf( PETSC_COMM_WORLD, " Total BSSCR Linear solve time: %lf seconds\n\n", TotalSolveTime); bsscr->solver->stats.total_time=TotalSolveTime; PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "KSPDestroy_BSSCR" PetscErrorCode KSPDestroy_BSSCR(KSP ksp) { KSP_BSSCR *bsscr = (KSP_BSSCR *)ksp->data; Mat K2=bsscr->K2; Vec t,v; MatStokesBlockScaling BA=bsscr->BA; PetscErrorCode ierr; PetscFunctionBegin; t=bsscr->t; v=bsscr->v; if ( v ){ Stg_VecDestroy(&v); } if ( t ){ Stg_VecDestroy(&t); } if( K2 ){ Stg_MatDestroy(&K2 ); }/* shouldn't need this now */ if(BA) BSSCR_MatStokesBlockScalingDestroy( BA ); ierr = PetscFree(ksp->data);CHKERRQ(ierr); PetscFunctionReturn(0); } static const char *K2Types[] = {"NULL","DGMGD","GMG","GG","SLE","K2Type","K2_",0}; #undef __FUNCT__ #define __FUNCT__ "KSPSetFromOptions_BSSCR" #if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR <6) ) PetscErrorCode KSPSetFromOptions_BSSCR(KSP ksp) { PetscTruth flg; KSP_BSSCR *bsscr = (KSP_BSSCR *)ksp->data; PetscErrorCode ierr; PetscFunctionBegin; ierr = PetscOptionsHead("KSP BSSCR options");CHKERRQ(ierr); /* if this ksp has a prefix "XXX_" it will be automatically added to the options. e.g. -ksp_test -> -XXX_ksp_test */ /* ierr = PetscOptionsTruth("-ksp_test","Test KSP flag","nil",PETSC_FALSE,&test,PETSC_NULL);CHKERRQ(ierr); */ /* if(test){ PetscPrintf( PETSC_COMM_WORLD, "\n\n----- test flag set ------\n\n"); } */ ierr = PetscOptionsEnum("-ksp_k2_type","Augmented Lagrangian matrix type","",K2Types, bsscr->k2type,(PetscEnum*)&bsscr->k2type,&flg);CHKERRQ(ierr); //if(flg){ PetscPrintf( PETSC_COMM_WORLD, "----- k2 type is ------\n"); } ierr = PetscOptionsTail();CHKERRQ(ierr); PetscFunctionReturn(0); } #else PetscErrorCode KSPSetFromOptions_BSSCR(Stg_PetscOptions *PetscOptionsObject, KSP ksp) { PetscTruth flg; KSP_BSSCR *bsscr = (KSP_BSSCR *)ksp->data; PetscErrorCode ierr; PetscFunctionBegin; ierr = PetscOptionsHead(PetscOptionsObject,"KSP BSSCR options");CHKERRQ(ierr); /* if this ksp has a prefix "XXX_" it will be automatically added to the options. e.g. -ksp_test -> -XXX_ksp_test */ /* ierr = PetscOptionsTruth("-ksp_test","Test KSP flag","nil",PETSC_FALSE,&test,PETSC_NULL);CHKERRQ(ierr); */ /* if(test){ PetscPrintf( PETSC_COMM_WORLD, "\n\n----- test flag set ------\n\n"); } */ ierr = PetscOptionsEnum("-ksp_k2_type","Augmented Lagrangian matrix type","",K2Types, bsscr->k2type,(PetscEnum*)&bsscr->k2type,&flg);CHKERRQ(ierr); //if(flg){ PetscPrintf( PETSC_COMM_WORLD, "----- k2 type is ------\n"); } ierr = PetscOptionsTail();CHKERRQ(ierr); PetscFunctionReturn(0); } #endif #undef __FUNCT__ #define __FUNCT__ "KSPView_BSSCR" PetscErrorCode KSPView_BSSCR(KSP ksp,PetscViewer viewer) { PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "KSPSetUp_BSSCR" PetscErrorCode KSPSetUp_BSSCR(KSP ksp) { KSP_BSSCR *bsscr = (KSP_BSSCR *)ksp->data; Mat K; Stokes_SLE* stokesSLE = (Stokes_SLE*)bsscr->st_sle; PetscTruth ismumps,augment,scale,konly,found,conp,checkerp; PetscFunctionBegin; BSSCR_PetscExtStokesSolversInitialize(); K = stokesSLE->kStiffMat->matrix; bsscr->K2=PETSC_NULL; BSSCR_MatStokesBlockScalingCreate( &(bsscr->BA) );/* allocate memory for scaling struct */ found = PETSC_FALSE; augment = PETSC_TRUE; PetscOptionsGetTruth(PETSC_NULL, "-augmented_lagrangian", &augment, &found); if(augment){ bsscr->buildK2 = bsscr_buildK2; } else { bsscr->buildK2 = PETSC_NULL; } /***************************************************************************************************************/ /** Do scaling *************************************************************************************************/ /***************************************************************************************************************/ found = PETSC_FALSE; scale = PETSC_FALSE;/* scaling off by default */ PetscOptionsGetTruth(PETSC_NULL, "-rescale_equations", &scale, &found); Stg_PetscObjectTypeCompare((PetscObject)K, "mataijmumps", &ismumps);/** older versions of petsc have this */ if(ismumps && scale){ PetscPrintf( PETSC_COMM_WORLD, "\t* Not applying scaling to matrices as MatGetRowMax operation not defined for MATAIJMUMPS matrix type \n"); scale = PETSC_FALSE; } if( scale ) { bsscr->scale = KSPScale_BSSCR; bsscr->unscale = KSPUnscale_BSSCR; bsscr->do_scaling = PETSC_TRUE; bsscr->scaletype = KONLY; konly = PETSC_TRUE; found = PETSC_FALSE; PetscOptionsGetTruth(PETSC_NULL, "-k_scale_only", &konly, &found); if(!konly){ bsscr->scaletype = DEFAULT; } } /***************************************************************************************************************/ /** Set up functions for building Pressure Null Space Vectors *************************************************/ /***************************************************************************************************************/ found = PETSC_FALSE; checkerp = PETSC_FALSE; PetscOptionsGetTruth(PETSC_NULL, "-remove_checkerboard_pressure_null_space", &checkerp, &found ); if(checkerp){ bsscr->check_cb_pressureNS = PETSC_TRUE; bsscr->check_pressureNS = PETSC_TRUE; bsscr->buildPNS = KSPBuildPressure_CB_Nullspace_BSSCR; } found = PETSC_FALSE; conp = PETSC_FALSE; PetscOptionsGetTruth(PETSC_NULL, "-remove_constant_pressure_null_space", &conp, &found ); if(conp){ bsscr->check_const_pressureNS = PETSC_TRUE; bsscr->check_pressureNS = PETSC_TRUE; bsscr->buildPNS = KSPBuildPressure_Const_Nullspace_BSSCR; } /***************************************************************************************************************/ PetscFunctionReturn(0); } EXTERN_C_BEGIN #undef __FUNCT__ #define __FUNCT__ "KSPCreate_BSSCR" PetscErrorCode PETSCKSP_DLLEXPORT KSPCreate_BSSCR(KSP ksp) { KSP_BSSCR *bsscr; PetscErrorCode ierr; PetscFunctionBegin; ierr = Stg_PetscNew(KSP_BSSCR,&bsscr);CHKERRQ(ierr); ierr = PetscLogObjectMemory((PetscObject)ksp,sizeof(KSP_BSSCR));CHKERRQ(ierr); //ierr = PetscNewLog(ksp,KSP_BSSCR,&bsscr);CHKERRQ(ierr); ksp->data = (void*)bsscr; #if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >= 2 ) ) ierr = KSPSetSupportedNorm(ksp,KSP_NORM_PRECONDITIONED,PC_LEFT,0);CHKERRQ(ierr); ierr = KSPSetSupportedNorm(ksp,KSP_NORM_UNPRECONDITIONED,PC_LEFT,1);CHKERRQ(ierr); ierr = KSPSetSupportedNorm(ksp,KSP_NORM_NATURAL,PC_LEFT,0);CHKERRQ(ierr); ierr = KSPSetSupportedNorm(ksp,KSP_NORM_NONE,PC_LEFT,1);CHKERRQ(ierr); #endif /* Sets the functions that are associated with this data structure (in C++ this is the same as defining virtual functions) */ ksp->ops->setup = KSPSetUp_BSSCR; ksp->ops->solve = KSPSolve_BSSCR; ksp->ops->destroy = KSPDestroy_BSSCR; ksp->ops->view = KSPView_BSSCR; ksp->ops->setfromoptions = KSPSetFromOptions_BSSCR; ksp->ops->buildsolution = KSPDefaultBuildSolution; ksp->ops->buildresidual = KSPDefaultBuildResidual; // bsscr->k2type=K2_GMG; bsscr->k2type = 0; bsscr->do_scaling = PETSC_FALSE; bsscr->scaled = PETSC_FALSE; bsscr->K2built = PETSC_FALSE; bsscr->check_cb_pressureNS = PETSC_FALSE;/* checker board nullspace */ bsscr->check_const_pressureNS = PETSC_FALSE;/* constant nullspace */ bsscr->check_pressureNS = PETSC_FALSE;/* is true if either of above two are true */ bsscr->t = NULL;/* null space vectors for pressure */ bsscr->v = NULL; bsscr->nstol = 1e-7;/* null space detection tolerance */ bsscr->uStar = NULL; bsscr->been_here = 0; PetscFunctionReturn(0); } EXTERN_C_END
{ "alphanum_fraction": 0.5958974359, "avg_line_length": 40.4377880184, "ext": "c", "hexsha": "b6e20293ea5f5f10acbb5faccd2c9aae39a54d3b", "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/BSSCR.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/BSSCR.c", "max_line_length": 151, "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/BSSCR.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5040, "size": 17550 }
static char help[] = "Solves 2D advection-diffusion problems using FD discretization,\n" "structured-grid (DMDA), and -snes_fd_color. Option prefix -bth_.\n" "Equation:\n" " - eps Laplacian u + Div (a(x,y) u) = g(x,y),\n" "where the (vector) wind a(x,y) and (scalar) source g(x,y) are given smooth\n" "functions. The domain is S = (-1,1)^2 with Dirichlet boundary conditions:\n" " u = b(x,y) on boundary S\n" "where b(x,y) is a given smooth function. Problems include: NOWIND, LAYER,\n" "and GLAZE. The first of these has a=0 while LAYER and GLAZE are\n" "Examples 6.1.1 and 6.1.4 in Elman et al (2014), respectively.\n" "Advection can be discretized by first-order upwinding (none), centered, or a\n" "van Leer limiter scheme. Option allows switching to none limiter on all grids\n" "for which the mesh Peclet P^h exceeds a threshold (default: 1).\n\n"; #include <petsc.h> typedef enum {NONE, CENTERED, VANLEER} LimiterType; static const char *LimiterTypes[] = {"none","centered","vanleer", "LimiterType", "", NULL}; static PetscReal centered(PetscReal theta) { return 0.5; } static PetscReal vanleer(PetscReal theta) { const PetscReal abstheta = PetscAbsReal(theta); return 0.5 * (theta + abstheta) / (1.0 + abstheta); // 4 flops } typedef PetscReal (*LimiterFcn)(PetscReal); static LimiterFcn limiterptr[] = {NULL, &centered, &vanleer}; typedef enum {NOWIND, LAYER, GLAZE} ProblemType; static const char *ProblemTypes[] = {"nowind", "layer", "glaze", "ProblemType", "", NULL}; typedef struct { ProblemType problem; PetscReal eps, // diffusion eps > 0 a_scale, // scale for wind peclet_threshold, (*limiter_fcn)(PetscReal), (*g_fcn)(PetscReal, PetscReal, void*), // right-hand-side source (*b_fcn)(PetscReal, PetscReal, void*); // boundary condition PetscBool none_on_peclet, // if true use none limiter when P^h > threshold small_peclet_achieved; // true if on finest grid P^h <= threshold } AdCtx; // used for source functions static PetscReal zero(PetscReal x, PetscReal y, void *user) { return 0.0; } // problem NOWIND: same problem as ./fish -fsh_problem manuexp static PetscReal nowind_u(PetscReal x, PetscReal y, void *user) { // exact solution return - x * PetscExpReal(y); } static PetscReal nowind_g(PetscReal x, PetscReal y, void *user) { AdCtx* usr = (AdCtx*)user; return usr->eps * x * PetscExpReal(y); } static PetscReal nowind_b(PetscReal x, PetscReal y, void *user) { return nowind_u(x,y,user); } // problem LAYER: Elman page 237, Example 6.1.1 static PetscReal layer_u(PetscReal x, PetscReal y, void *user) { // exact solution AdCtx* usr = (AdCtx*)user; return x * (1.0 - PetscExpReal((y-1) / usr->eps)) / (1.0 - PetscExpReal(- 2.0 / usr->eps)); } static PetscReal layer_b(PetscReal x, PetscReal y, void *user) { return layer_u(x,y,user); } // problem GLAZE: Elman page 240, Example 6.1.4 static PetscReal glaze_b(PetscReal x, PetscReal y, void *user) { if (x > 0.0 && y < x && y > -x) return 1.0; // along x=1 boundary else return 0.0; } typedef PetscReal (*PointwiseFcn)(PetscReal,PetscReal,void*); static PointwiseFcn uexptr[] = {&nowind_u, &layer_u, NULL}; static PointwiseFcn gptr[] = {&nowind_g, &zero, &zero}; static PointwiseFcn bptr[] = {&nowind_b, &layer_b, &glaze_b}; /* This vector function returns q=0,1 component. It is used in FormFunctionLocal() to get a(x,y). */ static PetscReal wind_a(PetscReal x, PetscReal y, PetscInt q, AdCtx *user) { switch (user->problem) { case NOWIND: return 0.0; case LAYER: return (q == 0) ? 0.0 : 1.0; case GLAZE: return (q == 0) ? 2.0*y*(1.0-x*x) : -2.0*x*(1.0-y*y); default: return NAN; } } extern PetscErrorCode FormUExact(DMDALocalInfo*,AdCtx*, PetscReal (*)(PetscReal, PetscReal, void*),Vec); extern PetscErrorCode FormFunctionLocal(DMDALocalInfo*,PetscReal**,PetscReal**,AdCtx*); int main(int argc,char **argv) { PetscErrorCode ierr; DM da, da_after; SNES snes; Vec u_initial, u; DMDALocalInfo info; PointwiseFcn uexact_fcn; LimiterType limiter = NONE; PetscBool init_exact = PETSC_FALSE; AdCtx user; ierr = PetscInitialize(&argc,&argv,NULL,help); if (ierr) return ierr; user.eps = 0.005; user.none_on_peclet = PETSC_FALSE; user.small_peclet_achieved = PETSC_FALSE; user.problem = LAYER; user.a_scale = 1.0; // this could be made dependent on problem user.peclet_threshold = 1.0; ierr = PetscOptionsBegin(PETSC_COMM_WORLD,"bth_", "both (2D advection-diffusion solver) options",""); CHKERRQ(ierr); ierr = PetscOptionsReal("-eps","positive diffusion coefficient", "both.c",user.eps,&(user.eps),NULL); CHKERRQ(ierr); ierr = PetscOptionsBool("-init_exact","use exact solution for initialization", "both.c",init_exact,&init_exact,NULL); CHKERRQ(ierr); ierr = PetscOptionsEnum("-limiter","flux-limiter type", "both.c",LimiterTypes, (PetscEnum)limiter,(PetscEnum*)&limiter,NULL); CHKERRQ(ierr); ierr = PetscOptionsBool("-none_on_peclet", "on coarse grids such that mesh Peclet P^h exceeds threshold, switch to none limiter", "both.c",user.none_on_peclet,&(user.none_on_peclet),NULL); CHKERRQ(ierr); ierr = PetscOptionsReal("-peclet_threshold", "if mesh Peclet P^h is above this value, switch to none (used with -bth_none_on_peclet)", "both.c",user.peclet_threshold,&(user.peclet_threshold),NULL); CHKERRQ(ierr); ierr = PetscOptionsEnum("-problem","problem type", "both.c",ProblemTypes, (PetscEnum)(user.problem),(PetscEnum*)&(user.problem),NULL); CHKERRQ(ierr); ierr = PetscOptionsEnd(); CHKERRQ(ierr); if (user.eps <= 0.0) { SETERRQ1(PETSC_COMM_SELF,1,"eps=%.3f invalid ... eps > 0 required",user.eps); } user.limiter_fcn = limiterptr[limiter]; uexact_fcn = uexptr[user.problem]; user.g_fcn = gptr[user.problem]; user.b_fcn = bptr[user.problem]; ierr = DMDACreate2d(PETSC_COMM_WORLD, DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DMDA_STENCIL_STAR, 3,3, // default to hx=hy=1 grid PETSC_DECIDE,PETSC_DECIDE, 1,2, // d.o.f, stencil width NULL,NULL,&da); CHKERRQ(ierr); ierr = DMSetFromOptions(da); CHKERRQ(ierr); ierr = DMSetUp(da); CHKERRQ(ierr); if (user.problem == NOWIND) { ierr = DMDASetUniformCoordinates(da,0.0,1.0,0.0,1.0,-1.0,1.0); CHKERRQ(ierr); } else { ierr = DMDASetUniformCoordinates(da,-1.0,1.0,-1.0,1.0,-1.0,1.0); CHKERRQ(ierr); } ierr = DMSetApplicationContext(da,&user); CHKERRQ(ierr); ierr = SNESCreate(PETSC_COMM_WORLD,&snes);CHKERRQ(ierr); ierr = SNESSetDM(snes,da);CHKERRQ(ierr); ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES, (DMDASNESFunction)FormFunctionLocal,&user);CHKERRQ(ierr); ierr = SNESSetApplicationContext(snes,&user); CHKERRQ(ierr); ierr = SNESSetFromOptions(snes);CHKERRQ(ierr); ierr = DMGetGlobalVector(da,&u_initial); CHKERRQ(ierr); if (init_exact) { ierr = FormUExact(&info,&user,uexact_fcn,u_initial); CHKERRQ(ierr); } else { ierr = VecSet(u_initial,0.0); CHKERRQ(ierr); } ierr = SNESSolve(snes,NULL,u_initial); CHKERRQ(ierr); ierr = DMRestoreGlobalVector(da,&u_initial); CHKERRQ(ierr); ierr = DMDestroy(&da); CHKERRQ(ierr); ierr = SNESGetSolution(snes,&u); CHKERRQ(ierr); ierr = SNESGetDM(snes,&da_after); CHKERRQ(ierr); ierr = DMDAGetLocalInfo(da_after,&info); CHKERRQ(ierr); if (user.none_on_peclet && !user.small_peclet_achieved) { ierr = PetscPrintf(PETSC_COMM_WORLD, "WARNING: -bth_none_on_peclet set but finest grid used NONE limiter\n"); CHKERRQ(ierr); } ierr = PetscPrintf(PETSC_COMM_WORLD, "done on %d x %d grid (problem = %s, eps = %g, limiter = %s)\n", info.mx,info.my,ProblemTypes[user.problem],user.eps,LimiterTypes[limiter]); CHKERRQ(ierr); if (uexact_fcn != NULL) { Vec u_exact; PetscReal xymin[2], xymax[2], hx, hy, err2; ierr = DMCreateGlobalVector(da_after,&u_exact); CHKERRQ(ierr); ierr = FormUExact(&info,&user,uexact_fcn,u_exact); CHKERRQ(ierr); ierr = VecAXPY(u,-1.0,u_exact); CHKERRQ(ierr); // u <- u + (-1.0) u_exact ierr = VecNorm(u,NORM_2,&err2); CHKERRQ(ierr); ierr = DMGetBoundingBox(da_after,xymin,xymax); CHKERRQ(ierr); hx = (xymax[0] - xymin[0]) / (info.mx - 1); hy = (xymax[1] - xymin[1]) / (info.my - 1); err2 *= PetscSqrtReal(hx * hy); ierr = PetscPrintf(PETSC_COMM_WORLD, "numerical error: |u-uexact|_2 = %.4e\n",err2); CHKERRQ(ierr); ierr = VecDestroy(&u_exact); CHKERRQ(ierr); } ierr = SNESDestroy(&snes); CHKERRQ(ierr); return PetscFinalize(); } PetscErrorCode FormUExact(DMDALocalInfo *info, AdCtx *usr, PetscReal (*uexact)(PetscReal, PetscReal, void*), Vec uex) { PetscErrorCode ierr; PetscInt i, j; PetscReal xymin[2], xymax[2], hx, hy, x, y, **auex; if (uexact == NULL) { SETERRQ(PETSC_COMM_SELF,1,"exact solution not available"); } ierr = DMGetBoundingBox(info->da,xymin,xymax); CHKERRQ(ierr); hx = (xymax[0] - xymin[0]) / (info->mx - 1); hy = (xymax[1] - xymin[1]) / (info->my - 1); ierr = DMDAVecGetArray(info->da, uex, &auex);CHKERRQ(ierr); for (j=info->ys; j<info->ys+info->ym; j++) { y = xymin[1] + j * hy; for (i=info->xs; i<info->xs+info->xm; i++) { x = xymin[0] + i * hx; auex[j][i] = (*uexact)(x,y,usr); } } ierr = DMDAVecRestoreArray(info->da, uex, &auex);CHKERRQ(ierr); return 0; } /* compute residuals: F_ij = hx * hy * (- eps Laplacian u + Div (a(x,y) u) - g(x,y)) at boundary points: F_ij = c (u - b(x,y)) note compass notation for faces of cells; advection scheme evaluates flux at each E,N face once and then includes it in two residuals: N ------- | | W | * | E | | ------- S */ PetscErrorCode FormFunctionLocal(DMDALocalInfo *info, PetscReal **au, PetscReal **aF, AdCtx *usr) { PetscErrorCode ierr; PetscInt i, j, p; PetscReal xymin[2], xymax[2], hx, hy, Ph, hx2, hy2, scF, scBC, x, y, uE, uW, uN, uS, uxx, uyy, ap, flux, u_up, u_dn, u_far, theta; PetscReal (*limiter)(PetscReal); PetscBool iowned, jowned, ip1owned, jp1owned; PetscLogDouble ff; ierr = DMGetBoundingBox(info->da,xymin,xymax); CHKERRQ(ierr); hx = (xymax[0] - xymin[0]) / (info->mx - 1); hy = (xymax[1] - xymin[1]) / (info->my - 1); limiter = usr->limiter_fcn; if (usr->none_on_peclet) { Ph = usr->a_scale * PetscMax(hx,hy) / usr->eps; // mesh Peclet number if (Ph > usr->peclet_threshold) limiter = NULL; else usr->small_peclet_achieved = PETSC_TRUE; } hx2 = hx * hx; hy2 = hy * hy; scF = hx * hy; // scale residuals scBC = scF * usr->eps * 2.0 * (1.0 / hx2 + 1.0 / hy2); // scale b.c. residuals // for owned cells, compute non-advective parts of residual at cell center for (j=info->ys; j<info->ys+info->ym; j++) { y = xymin[1] + j * hy; for (i=info->xs; i<info->xs+info->xm; i++) { x = xymin[0] + i * hx; if (i == 0 || i == info->mx-1 || j == 0 || j == info->my-1) { aF[j][i] = scBC * (au[j][i] - (*usr->b_fcn)(x,y,usr)); } else { uE = (i+1 == info->mx-1) ? (*usr->b_fcn)(xymax[0],y,usr) : au[j][i+1]; uW = (i-1 == 0) ? (*usr->b_fcn)(xymin[0],y,usr) : au[j][i-1]; uxx = (uE - 2.0 * au[j][i] + uW) / hx2; uN = (j+1 == info->my-1) ? (*usr->b_fcn)(x,xymax[1],usr) : au[j+1][i]; uS = (j-1 == 0) ? (*usr->b_fcn)(x,xymin[1],usr) : au[j-1][i]; uyy = (uN - 2.0 * au[j][i] + uS) / hy2; aF[j][i] = scF * (- usr->eps * (uxx + uyy) - (*usr->g_fcn)(x,y,usr)); } } } ierr = PetscLogFlops(14.0*info->xm*info->ym); CHKERRQ(ierr); // for each E,N face of an *owned* cell at (x,y) and (i,j), compute flux at // the face center and then add that to the correct residual // note start offset of -1; gets W,S faces of owned cells living on ownership // boundaries for i,j resp. // there are (xm+1)*(ym+1)*2 fluxes to evaluate for (j=info->ys-1; j<info->ys+info->ym; j++) { y = xymin[1] + j * hy; // if y<0 or y=1 at cell center then no need to compute *any* E,N face-center fluxes if (j < 0 || j == info->my-1) continue; for (i=info->xs-1; i<info->xs+info->xm; i++) { x = xymin[0] + i * hx; // if x<0 or x=1 at cell center then no need to compute *any* E,N face-center fluxes if (i < 0 || i == info->mx-1) continue; // get E (p=0) and N (p=1) cell face-center flux contributions for (p = 0; p < 2; p++) { // get pth component of wind and locations determined by wind direction ap = (p == 0) ? wind_a(x+hx/2.0,y,p,usr) : wind_a(x,y+hy/2.0,p,usr); if (p == 0) if (ap >= 0.0) { u_up = (i == 0) ? (*usr->b_fcn)(xymin[0],y,usr) : au[j][i]; u_dn = (i+1 == info->mx-1) ? (*usr->b_fcn)(xymax[0],y,usr) : au[j][i+1]; u_far = (i-1 <= 0) ? (*usr->b_fcn)(xymin[0],y,usr) : au[j][i-1]; } else { u_up = (i+1 == info->mx-1) ? (*usr->b_fcn)(xymax[0],y,usr) : au[j][i+1]; u_dn = (i == 0) ? (*usr->b_fcn)(xymin[0],y,usr) : au[j][i]; u_far = (i+2 >= info->mx-1) ? (*usr->b_fcn)(xymax[0],y,usr) : au[j][i+2]; } else // p == 1 if (ap >= 0.0) { u_up = (j == 0) ? (*usr->b_fcn)(x,xymin[1],usr) : au[j][i]; u_dn = (j+1 == info->my-1) ? (*usr->b_fcn)(x,xymax[1],usr) : au[j+1][i]; u_far = (j-1 <= 0) ? (*usr->b_fcn)(x,xymin[1],usr) : au[j-1][i]; } else { u_up = (j+1 == info->my-1) ? (*usr->b_fcn)(x,xymax[1],usr) : au[j+1][i]; u_dn = (j == 0) ? (*usr->b_fcn)(x,xymin[1],usr) : au[j][i]; u_far = (j+2 >= info->my-1) ? (*usr->b_fcn)(x,xymax[1],usr) : au[j+2][i]; } // first-order upwind flux plus correction if have limiter flux = ap * u_up; if (limiter != NULL && u_dn != u_up) { theta = (u_up - u_far) / (u_dn - u_up); flux += ap * (*limiter)(theta) * (u_dn - u_up); } // update non-boundary and owned residual F_ij on both sides of computed flux // note: 1) aF[] does not have stencil width, 2) F_ij is scaled by scF = hx * hy iowned = (i >= info->xs); jowned = (j >= info->ys); ip1owned = (i+1 < info->xs + info->xm); jp1owned = (j+1 < info->ys + info->ym); switch (p) { case 0: // flux at E if (i > 0 && j > 0 && iowned && jowned) aF[j][i] += hy * flux; // flux out of i,j at E if (i+1 < info->mx-1 && j > 0 && ip1owned && jowned) aF[j][i+1] -= hy * flux; // flux into i+1,j at W break; case 1: // flux at N if (j > 0 && i > 0 && iowned && jowned) aF[j][i] += hx * flux; // flux out of i,j at N if (j+1 < info->my-1 && i > 0 && iowned && jp1owned) aF[j+1][i] -= hx * flux; // flux into i,j+1 at S break; } } } } // ff = flops per flux evaluation ff = (limiter == NULL) ? 6.0 : 13.0; if (limiter == &vanleer) ff += 4.0; ierr = PetscLogFlops(ff*2.0*(1.0+info->xm)*(1.0+info->ym)); CHKERRQ(ierr); return 0; }
{ "alphanum_fraction": 0.5389850396, "avg_line_length": 43.9304123711, "ext": "c", "hexsha": "472a49c0ba3a44f13d9b3ab4df30d7ff27b4ab09", "lang": "C", "max_forks_count": 46, "max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z", "max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z", "max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "thw1021/p4pdes", "max_forks_repo_path": "c/ch11/both.c", "max_issues_count": 52, "max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z", "max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "thw1021/p4pdes", "max_issues_repo_path": "c/ch11/both.c", "max_line_length": 104, "max_stars_count": 115, "max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "thw1021/p4pdes", "max_stars_repo_path": "c/ch11/both.c", "max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z", "num_tokens": 5343, "size": 17045 }
/*! \file GMatrix.h * \brief this file defines the \ref Math::GMatrix class that is part of the Math namespace */ #ifndef GMATRIX_H #define GMATRIX_H #include <iostream> #include <complex> #include <cstdlib> #include <cstdio> #include <cmath> #include <sstream> #include <stdexcept> #include <Precision.h> #include <Coordinate.h> #include <Matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> using namespace std; namespace Math { /*! \class Math::GMatrix \brief General n x m matrix General matrix class that eventually should replace \ref Math::Matrix class. will have to adjust error checks for this class and adjust inverse and make most calls inline to increase speed. */ class GMatrix { private: int row,col; Double_t *matrix; protected: ///useful comparison functions which can be used with qsort int compare_Double(const void* a,const void* b) { Double_t arg1 = *((Double_t*) a); Double_t arg2 = *((Double_t*) b); if( arg1 < arg2 ) return -1; else if( arg1==arg2 ) return 0; else return 1; } public: /// \name Constructors & Destructors //@{ /// Constructor (where data can be is initilized) otherwise set to zero GMatrix(int r, int c, Double_t *data=NULL) { if (r*c>0){ row=r;col=c; matrix=new Double_t[row*col]; if (data!=NULL){ for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) matrix[i*col+j] = data[i*col+j]; } else{ for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) matrix[i*col+j] = 0.; } } else { row=0;col=0;matrix=NULL; printf("Error, net size 0 with row,col=%d,%d\n",row,col); } } /// Constructor based on Coordinate. GMatrix(const Coordinate &c) { row=3;col=1; matrix=new Double_t[row*col]; for (int i = 0; i < row; i++) matrix[i] = c[i]; } /// Constructor Matrix GMatrix(const Matrix &m) { row=3;col=3; matrix=new Double_t[row*col]; for (int i=0; i<row; i++) for (int j=0;j<col;j++) matrix[i*col+j] = m(i,j); } /// Copy Constructor GMatrix(const GMatrix &m) { row=m.row;col=m.col; matrix=new Double_t[row*col]; for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) matrix[i*col+j] = m.matrix[i*col+j]; } /// Identity Matrix of dimension N GMatrix(int N) { row=N;col=N; matrix=new Double_t[row*col]; for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) matrix[i*col+j] = (i==j); } ~GMatrix(){ if (row>0&&col>0) delete[] matrix; } //@} /// \name Get & Set functions //@{ ///get row dimensions int Row()const {return row;} ///get col dimensions int Col()const {return col;} ///get rank int Rank()const {return min(row,col);} //@} /// \name Overloaded Operators //@{ /// How to access a matrix element: M(i, j) Double_t& operator () (int i, int j) { //if (j<col&&i<row) return matrix[j + col * i]; //else {printf("Error, (i,j)=(%d, %d) exceed matrix dimesions of %d %d \n", i,j,row,col); return 0;} } const Double_t& operator() (int i, int j) const { //if (j<col&&i<row) return matrix[j + col * i]; //else {printf("Error, (i,j)=(%d, %d) exceed matrix dimesions of %d %d \n", i,j,row,col); return 0;} } std::runtime_error incompatible_dimensions_error(const GMatrix &m) { std::ostringstream os; os << "Error, incompatible dimensions: " << "(" << row << "," << col << ") + " << "(" << m.row << "," << m.col << ")"; return std::runtime_error(os.str()); } /// Matrix addition GMatrix operator + (const GMatrix& m) { if (row==m.row&&col==m.col){ Double_t data[row*col]; for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) data[i*col+j] = matrix[i*col+j]+m.matrix[i*col+j]; return GMatrix(row,col,data); } throw incompatible_dimensions_error(m); } /// Matrix subtraction GMatrix operator - (const GMatrix& m) { if (row==m.row&&col==m.col){ Double_t data[row*col]; for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) data[i*col+j] = matrix[i*col+j]-m.matrix[i*col+j]; return GMatrix(row,col,data); } throw incompatible_dimensions_error(m); } /// Multiply by a scalar: a * M friend GMatrix operator * (Double_t a, const GMatrix& m); /// Multiply by a scalar: M * a GMatrix operator * (Double_t a) { Double_t data[row*col]; for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) data[i*col+j] = matrix[i*col+j]*a; return GMatrix(row,col,data); } /// Multiply by another Gmatrix GMatrix operator * (const GMatrix& m) { if (col==m.row){ Double_t data[row*m.col]; for (int i = 0; i < row; i++) for (int j = 0; j < m.col; j++){ data[i*m.col+j]=0.; for (int k=0;k<col;k++) data[i*m.col+j]+=matrix[i*col+k]*m.matrix[k*m.col+j]; } return GMatrix(row,m.col,data); } else { printf("Error, incompatible dimensions (%d,%d) + (%d,%d)\n",row,col,m.row,m.col); return GMatrix(0,0); } } /// Asignment constructor GMatrix& operator = (const GMatrix m) { delete[] matrix; row=m.row; col=m.col; matrix=new Double_t[row*col]; for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) matrix[i*col+j] = m.matrix[i*col+j]; return *this; } //@} /// \name Mathematical Operations //@{ /// Trace the matrix. Double_t Trace() const { Double_t trace=1.0; for (int i = 0; i < row; i++)trace*=matrix[i*col+i]; return trace; } /// return the Transpose of the matrix. GMatrix Transpose() const { Double_t data[col*row]; for (int i = 0; i < col; i++) for (int j = 0; j < row; j++) data[i*row+j]=(*this)(i,j); return GMatrix(col,row,data); } /// Transpose matrix in place (changes the matrix permanently!) void TransposeInPlace() { Double_t data[col*row]; int temp; for (int i = 0; i < col; i++) for (int j = 0; j < row; j++) data[i*row+j]=(*this)(i,j); temp=row;row=col;col=temp; for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) matrix[i*col+j]=data[i*col+j]; } ///Get the diagonals GMatrix Diag(){ GMatrix D(row,col); for (int i = 0; i < col; i++) D(i,i)=matrix[i*col+i]; return D; } /// Return Pivot matrix P of A, where P*A=B, such that B(i,i)!=0 GMatrix Pivot() const { Double_t a[row*col]; GMatrix P(row,col); for (int j=0;j<row;j++) P(j,j)=1; if (Trace()==0) { for (int j=0;j<row;j++) for (int k=0;k<row;k++) a[j*col+k]=matrix[j*col+k]; for (int j=0;j<row;j++) if (a[j*col+j]*a[j*col+j]<1e-32) { int k=j+1,ipivot; if (k==row)k=0; ipivot=(P(k,k)==1); while (!(a[j*col+k]*a[j*col+k]>1e-32&&ipivot)){ k++; if (k==row)k=0; ipivot=(P(k,k)==1); } P(j,j)=0;P(k,k)=0; P(j,k)=1;P(k,j)=1; for (int l=0;l<row;l++) { Double_t temp=a[l*col+j]; a[l*col+j]=a[l*col+k]; a[l*col+k]=temp; } } } return P; } /// Return Pivot matrix P of A, where P*A=B, such that B(i,i)!=0 GMatrix PivotInPlace() { GMatrix P(row,col); for (int j=0;j<row;j++) P(j,j)=1; if (Trace()==0) { for (int j=0;j<row;j++) if (matrix[j*col+j]*matrix[j*col+j]<1e-32) { int k=j+1,ipivot; if (k==row)k=0; ipivot=(P(k,k)==1); while (!(matrix[j*col+k]*matrix[j*col+k]>1e-32&&ipivot)){ k++; if (k==row)k=0; ipivot=(P(k,k)==1); } P(j,j)=0;P(k,k)=0; P(j,k)=1;P(k,j)=1; for (int l=0;l<row;l++) { Double_t temp=matrix[l*col+j]; matrix[l*col+j]=matrix[l*col+k]; matrix[l*col+k]=temp; } } } return P; } /// return a SubMatrix of the matrix from row ra to row rb and col ca to cb GMatrix SubMatrix(int ra, int rb, int ca, int cb) const { int r=(rb-ra+1), c=(cb-ca+1); Double_t data[r*c]; for (int i = ra; i <= rb; i++) for (int j = ca; j <=cb; j++) data[(i-ra)*c+(j-ca)]=(*this)(i,j); return GMatrix((rb-ra+1),(cb-ca+1),data); } /// return a submatrix ignore column r, c GMatrix ExtractMatrix(int r, int c) const { Double_t data[(row-1)*(col-1)]; int tempi=0; for (int i = 0; i < row; i++) for (int j = 0; j <col; j++) if (i!=r&&j!=c) data[tempi++]=(*this)(i,j); return GMatrix((row-1),(col-1),data); } /// Check if matrix square symmetric int isSymmetric() const { if (row!=col) return 0; for (int i=0;i<row;i++) for (int j=i+1;j<col-1;j++) if (((*this)(i,j)-(*this)(j,i))*((*this)(i,j)-(*this)(j,i))/(*this)(i,j)/(*this)(i,j)>1e-8) return 0; return 1; } /// Check if matrix is zero matrix int isZero() const { Double_t sm=0; for (int i=0;i<row;i++) for (int j=0;j<col;j++) sm+=matrix[i*row+j]*matrix[i*row+j]; if (sm==0.0) return 1; else return 0; } /// Determinant of matrix, for now recursively implemented. Double_t Det() const { Double_t total =0.; int tempi; if (row==col) { if (row==2) return matrix[0]*matrix[3]-matrix[1]*matrix[2]; else { for (int i = 0; i < col; i++) { Double_t data[(row-1)*(row-1)]; tempi=0; for (int j=1;j<row;j++) for (int k=0;k<col;k++) if (k!=i) data[tempi++]=(*this)(j,k); total+=matrix[i]*(GMatrix(row-1,col-1,data)).Det(); } return total; } } else { printf("not a square matrix %d, %d returning 0\n",row,col); return 0.; } } /*! \brief Lower-Upper decompistion LU decomposition of matrix stored in such a fashion that matrix return is (for 3x3): \f[ \left(\begin{array}{ccc} L11 & U12 &U13\\ L21 & L22 & U23\\ L31 & L32 & L33 \end{array}\right) \f] L is lower triangular matrix, U is upper unit triangular matrix. \n Crout's algorithm is used to determine the L and U matrices. System of equations to solve are : \n \f[ \begin{array}{lcl} i<j : & l_{i1}*u_{1j}+l_{i2}*u_{2j}+...+l_{ii}*u_{ij}&=a_{ij} \\ i=j : & l_{i1}*u_{1j}+l_{i2}*u_{2j}+...+l_{ii}*u_{jj}&=a_{ij} \\ i>j : & l_{i1}*u_{1j}+l_{i2}*u_{2j}+...+l_{ij}*u_{ij}&=a_{ij} \end{array} \f] with condition that \f$ l_{ii}=1 \f$. \n If matrix singular and no decomposition, print error and return zero matrix. Here matrix is singular if diagonal element is zero. \n Must alter this to pivot method so that subroutine reorder matrix if necessary and diagonals can be zero. */ GMatrix LUDecomp() const { if (row!=col) { printf("only implemented for square, returning zeros\n"); return GMatrix(row,col); } else { Double_t A[row*col]; Int_t i, j, k, p, p_k, p_row, p_col; for (j=0;j<row;j++) for (k=0;k<col;k++) A[j*col+k]=matrix[j*col+k]; for (k = 0, p_k = 0; k < row; p_k += row, k++) { for (i = k, p_row = p_k; i < row; p_row += row, i++) { for (p = 0, p_col = 0; p < k; p_col += row, p++) A[p_row + k] -= A[p_row + p] * A[p_col + k]; } if ( A[p_k + k] == 0.0 ) { printf("Singular matrix, returning zero matrix\n"); return GMatrix(row,col); } for (j = k+1; j < row; j++) { for (p = 0, p_col = 0; p < k; p_col += row, p++) A[p_k + j] -= A[p_k + p] * A[p_col + j]; A[p_k + j] /= A[p_k + k]; } } return GMatrix(row,col,A); } } /*! \brief Calculate the Inverse of the lower triangular matrix This routine calculates the inverse of the lower triangular matrix L. The superdiagonal part of the matrix is not addressed. The algorithm follows: \n Let M be the inverse of L, then \f$ L M = I \f$, \n \f$ M[i][i] = 1.0 / L[i][i] \f$ for i = 0, ..., row-1, and \n \f$ M[i][j] = -[(L[i][j] M[j][j] + ... + L[i][i-1] M[i-1][j])] / L[i][i], \f$ for i = 1, ..., row-1, j = 0, ..., i - 1. */ GMatrix Lower_Triangular_Inverse() { Double_t L[row*col]; int i, j, k, p_i, p_j, p_k; Double_t sum; for (j=0;j<row;j++) for (k=0;k<=j;k++) L[j*col+k]=matrix[j*col+k]; for (j=0;j<row;j++) for (k=j+1;k<col;k++) L[j*col+k]=0; //Invert the diagonal elements of the lower triangular matrix L. for (k = 0, p_k = 0; k < row; p_k += (row + 1), k++) { if (L[p_k] == 0.0) return GMatrix(row,row);//error, returning zero matrix else L[p_k] = 1.0 / L[p_k]; } //Invert the remaining lower triangular matrix L row by row. for (i = 1, p_i = 0 + row; i < row; i++, p_i += row) { for (j = 0, p_j = 0; j < i; p_j += row, j++) { sum = 0.0; for (k = j, p_k = p_j; k < i; k++, p_k += row) sum += L[p_i + k] * L[p_k + j]; L[p_i + j] = - L[p_i + i] * sum; } } return GMatrix(row,row,L); } /*! \brief Calculate the Inverse of the lower triangular matrix This routine calculates the inverse of the unit upper triangular matrix U. The subdiagonal part of the matrix is not addressed. The diagonal is assumed to consist of 1's and is not addressed. The algorithm follows: \n Let M be the inverse of U, then \f$ U M = I \f$, \n \f$ M[i][j] = -( U[i][i+1] M[i+1][j] + ... + U[i][j] M[j][j] ), \f$ for i = row-2, ... , 0, j = row-1, ..., i+1. */ GMatrix Unit_Upper_Triangular_Inverse() { Double_t U[row*col]; int i, j, k, p_i, p_k; for (j=0;j<row;j++) for (k=j+1;k<col;k++) U[j*col+k]=matrix[j*col+k]; for (j=0;j<row;j++) for (k=0;k<=j;k++) U[j*col+k]=(j==k); // Invert the superdiagonal part of the matrix U row by row where // the diagonal elements are assumed to be 1.0. for (i = row - 2, p_i = 0 + row * (row - 2); i >=0; p_i -= row, i-- ) { for (j = row - 1; j > i; j--) { U[p_i + j] = -U[p_i + j]; for (k = i + 1, p_k = p_i + row; k < j; p_k += row, k++ ) U[p_i + j] -= U[p_i + k] * U[p_k + j]; } } return GMatrix(row,row,U); } /// \brief Adjugate (classical adjoint) of matrix /// This is simply the transpose of the cofactor of the matrix GMatrix Adjugate() const { GMatrix cofactorT(row,col); for (int i=0;i<row;i++) for (int j=0;j<col;j++) cofactorT(j,i)=(ExtractMatrix(i,j)).Det()*pow(-1.,i+j); return cofactorT; } /// Inverse of matrix GMatrix Inverse() const { if (row!=col) { printf("only implemented for square, returning zeros\n"); return GMatrix(row,col); } GMatrix LU(LUDecomp()); Double_t d=1.0; for (int i=0;i<row;i++) d*=LU(i,i); if (d == 0.0) return GMatrix(row, col); else { GMatrix Uinv=LU.Unit_Upper_Triangular_Inverse(); GMatrix Linv=LU.Lower_Triangular_Inverse(); return Uinv*Linv; } } /// Inverse of matrix using a pivot (needed in case diagonals are zero) GMatrix InversewithPivot() const { if (row!=col) { printf("only implemented for square, returning zeros\n"); return GMatrix(row,col); } GMatrix A(*this); GMatrix Pivot(A.PivotInPlace()); GMatrix LU(A.LUDecomp()); Double_t d=1.0; for (int i=0;i<row;i++) d*=LU(i,i); if (d == 0.0) return GMatrix(row, col); else { GMatrix Uinv=LU.Unit_Upper_Triangular_Inverse(); GMatrix Linv=LU.Lower_Triangular_Inverse(); return Uinv*Linv*Pivot; } } /// helpful rotation definition used in \ref Math::GMatrix::Jacobi (see Numerical recipes) inline void ROTATE(GMatrix &m, int i, int j, int k, int l, Double_t sinrot, Double_t tanrot) const { Double_t tempa=m(i,j),tempb=m(k,l); m(i,j)=tempa-sinrot*(tempb+tempa*tanrot);m(k,l)=tempb+sinrot*(tempa-tempb*tanrot); } /// Applies jacobi transformations to a copy of a matrix and returns effectively the eigenvalues of the matrix GMatrix Jacobi(Double_t tol=1e-2) const { GMatrix m(*this); Double_t eigen[row], b[row], z[row]; GMatrix Prot(row);//identity int nrot=0; Double_t crot,srot,trot2,thres,t,theta,sm,temp1,temp2; //initialize vectors to diagonal elements of matrix for (int i=0;i<row;i++){ eigen[i]=b[i]=m(i,i);z[i]=0.;} do { //first check to see if off diagonal elements are zero // could check to within some precision relative to trace sm=0.; for (int ip=0;ip<row-1;ip++) for (int iq=ip+1;iq<col;iq++) sm+=sqrt(m(ip,iq)*m(ip,iq)); if (sm==0.) return GMatrix(row,1,eigen); //set the threshold to be 0 until several rotations have been applied nrot<4? thres=tol*sm/(Double_t)(row*row): thres=0.; //now start applying Jacobi rotations for (int ip=0;ip<row-1;ip++){ for (int iq=ip+1;iq<col;iq++){ //get absolute value of off diagonal element and check if it is small in comparison to //threshold factor of 1/5 is from numerical recipes temp1=sqrt(m(ip,iq)*m(ip,iq))*0.2; //if smaller than tolerance set to 0. after for sweeps and skip the rotation. if (nrot > 4 && (sqrt(eigen[ip]*eigen[ip])+temp1)==(sqrt(eigen[ip]*eigen[ip])+tol) && (sqrt(eigen[iq]*eigen[iq])+temp1)==(sqrt(eigen[iq]*eigen[iq])+tol)) m(ip,iq)=0.0; else if (thres<temp1*5.0) { temp2=eigen[iq]-eigen[ip]; //find the solution to t^2+2*t*theta-1=0 //where theta=(cos^2-sin^2)/(2*s*c)=(m(iq,iq)-m(ip,ip))/(2*m(ip,iq)) //note that nr has ad hoc check if theta^2 would overflow the computer /*if ((sqrt(temp2*temp2)+temp1) == sqrt(temp2*temp2)) t=(m(ip,iq))/temp2; else { theta=0.5*temp2/m(ip,iq); t=1.0/(sqrt(theta*theta)+sqrt(1.0+theta*theta)); if (theta < 0.0) t = -t; }*/ //instead I just determine the value of t theta=0.5*temp2/m(ip,iq); t=1.0/(sqrt(theta*theta)+sqrt(1.0+theta*theta)); if (theta < 0.0) t = -t; //calculate cos and sin of rotation angle and tan(rot/2) crot=1.0/sqrt(1.+t*t); srot=t*crot; trot2=srot/(1.0+crot); //not alter values in matrix temp2=t*m(ip,iq); z[ip]-= temp2; z[iq] += temp2; eigen[ip]-= temp2; eigen[iq] += temp2; m(ip,iq)=0.0; //now rotate the ipth values for 0<=j<ip for (int j=0;j<ip;j++) {ROTATE(m,j,ip,j,iq,srot,trot2);} //rotate the values for ip<j<iq for (int j=ip+1;j<iq;j++) {ROTATE(m,ip,j,j,iq,srot,trot2);} //rotate the values for iq<j<=row for (int j=iq+1;j<row;j++) {ROTATE(m,ip,j,iq,j,srot,trot2);} //store the rotations in Prot for (int j=0;j<row;j++) {ROTATE(Prot,j,ip,j,iq,srot,trot2);} } } } //now update vectors used in rotation and reinitialize b for (int ip=0;ip<row;ip++) { b[ip] += z[ip]; eigen[ip]=b[ip]; z[ip]=0.0; } }while (nrot++<10); printf("Too many iterations in routine jacobi, giving zeros\n"); for (int i=0;i<row;i++) eigen[i]=0.; return GMatrix(row,1,eigen); } /// same as \ref Math::GMatrix::Jacobi above with different arguments and also returns Prot void Jacobi(GMatrix &eigenval, GMatrix &Prot, Double_t tol=1e-2) const { GMatrix m((*this)); Double_t eigen[row], b[row], z[row]; for (int i=0;i<row;i++) Prot(i,i)=1.; int nrot=0; Double_t crot,srot,trot2,thres,t,theta,sm,temp1,temp2; //initialize vectors to diagonal elements of matrix for (int i=0;i<row;i++){eigen[i]=b[i]=m(i,i);z[i]=0.;} do { //first check to see if off diagonal elements are zero // could check to within some precision relative to trace sm=0.; for (int ip=0;ip<row-1;ip++) for (int iq=ip+1;iq<col;iq++) sm+=sqrt(m(ip,iq)*m(ip,iq)); if (sm==0.) break; //set the threshold to be 0 until several rotations have been applied nrot<4? thres=tol*sm/(Double_t)(row*row): thres=0.; //now start applying Jacobi rotations for (int ip=0;ip<row-1;ip++){ for (int iq=ip+1;iq<col;iq++){ //get absolute value of off diagonal element and check if it is small in comparison to //threshold factor of 1/5 is from numerical recipes temp1=sqrt(m(ip,iq)*m(ip,iq))*0.2; //if smaller than tolerance set to 0. after for sweeps and skip the rotation. if (nrot > 4 && (sqrt(eigen[ip]*eigen[ip])+temp1)==(sqrt(eigen[ip]*eigen[ip])+tol) && (sqrt(eigen[iq]*eigen[iq])+temp1)==(sqrt(eigen[iq]*eigen[iq])+tol)) m(ip,iq)=0.0; else if (thres<temp1*5.0) { temp2=eigen[iq]-eigen[ip]; //find the solution to t^2+2*t*theta-1=0 //where theta=(cos^2-sin^2)/(2*s*c)=(m(iq,iq)-m(ip,ip))/(2*m(ip,iq)) //note that nr has ad hoc check if theta^2 would overflow the computer /*if ((sqrt(temp2*temp2)+temp1) == sqrt(temp2*temp2)) t=(m(ip,iq))/temp2; else { theta=0.5*temp2/m(ip,iq); t=1.0/(sqrt(theta*theta)+sqrt(1.0+theta*theta)); if (theta < 0.0) t = -t; }*/ //instead I just determine the value of t theta=0.5*temp2/m(ip,iq); t=1.0/(sqrt(theta*theta)+sqrt(1.0+theta*theta)); if (theta < 0.0) t = -t; //calculate cos and sin of rotation angle and tan(rot/2) crot=1.0/sqrt(1.+t*t); srot=t*crot; trot2=srot/(1.0+crot); //not alter values in matrix temp2=t*m(ip,iq); z[ip]-= temp2; z[iq] += temp2; eigen[ip]-= temp2; eigen[iq] += temp2; m(ip,iq)=0.0; //now rotate the ipth values for 0<=j<ip for (int j=0;j<ip;j++) {ROTATE(m,j,ip,j,iq,srot,trot2);} //rotate the values for ip<j<iq for (int j=ip+1;j<iq;j++) {ROTATE(m,ip,j,j,iq,srot,trot2);} //rotate the values for iq<j<=row for (int j=iq+1;j<row;j++) {ROTATE(m,ip,j,iq,j,srot,trot2);} //store the rotations in Prot for (int j=0;j<row;j++) {ROTATE(Prot,j,ip,j,iq,srot,trot2);} } } } //now update vectors used in rotation and reinitialize b for (int ip=0;ip<row;ip++) { b[ip] += z[ip]; eigen[ip]=b[ip]; z[ip]=0.0; } }while (nrot++<10); if (nrot>=10) { printf("Too many iterations in routine jacobi, giving zeros\n"); for (int i=0;i<row;i++) { eigenval(i,0)=0.; for (int j=0;j<row;j++) Prot(i,j)=(i==j); } } for (int i=0;i<row;i++) eigenval(i,0)=eigen[i]; } /*! \brief Calculate eigenvalues of matrix of rank N. Stored as a GMatrix, e1, e2 ...eN. The user must know what to expect from this function, whether real eigenvalues or complex ones. Have to implement the Francis QR algorithm or use successive Jacobi transformations to get eigenvalues and eigenvectors (note Jacobi slower than QR) but to ensure real eigenvalues, check that the matrix is symmetric */ GMatrix Eigenvalues(Double_t tol=1e-2) const { if (isSymmetric()==0||isZero()==1) { printf("only implemented for nonzero symmetric matrices, returning null matrix\n"); return GMatrix(0,0); } else { //using Jacobi transformations //issue is then must order eigen values GMatrix eigen(Jacobi(tol)); //now order the eigen vaules e0>e1>e2..>eN //qsort(eigen.matrix,row,sizeof(Double_t),compare_Double); return eigen; } } // Computes the eigenvectors of the matrix, given the eigenvalues. Sadly, this function will only work // properly on symmetric matrices -- i.e., all real eigenvalues. //GMatrix Eigenvectors(const Coordinate& e) const; /// Calculate eigenvalues \e and eigenvector of matrix of rank N. Stored as a GMatrix, e1, e2 ...eN. void Eigenvalvec(GMatrix &eigenval, GMatrix &eigenvector, Double_t tol=1e-2) const { if (isSymmetric()==0||isZero()==1) { printf("only implemented for nonzero symmetric matrices, returning null matrix\n"); for (int i=0;i<row;i++) { eigenval(i,0)=0.; for (int j=0;j<row;j++) eigenvector(i,j)=0.; } } else { //using Jacobi transformations Jacobi(eigenval,eigenvector,tol); } } //@} }; } #endif
{ "alphanum_fraction": 0.4745899624, "avg_line_length": 37.2683246073, "ext": "h", "hexsha": "e24ad269093c305021f9a26e8e25043187e853fb", "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": "10de78dde32d724b7a5ce323ce8ab093b15c61a8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ICRAR/NBodylib", "max_forks_repo_path": "src/Math/GMatrix.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8", "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": "ICRAR/NBodylib", "max_issues_repo_path": "src/Math/GMatrix.h", "max_line_length": 114, "max_stars_count": null, "max_stars_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ICRAR/NBodylib", "max_stars_repo_path": "src/Math/GMatrix.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 8140, "size": 28473 }
/* * @file modulated.h * @brief Cosine modulated analysis and synthesis filter banks. * @author John McDonough and Kenichi Kumatani */ #ifndef MODULATED_H #define MODULATED_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 "btk.h" #ifdef HAVE_LIBFFTW3 #include <fftw3.h> #endif inline int powi(int x, int p) { if(p == 0) return 1; if(x == 0 && p > 0) return 0; if(p < 0) {assert(x == 1 || x == -1); return (-p % 2) ? x : 1;} int r = 1; for(;;) { if(p & 1) r *= x; if((p >>= 1) == 0) return r; x *= x; } } /** * \defgroup FilterBanks Filter Banks * This hierarchy of classes provides the capability to divide * signal into 'M' subbands and then resynthesize the original time-domain signal. */ /*@{*/ // ----- definition for class `BaseFilterBank' ----- // class BaseFilterBank { public: virtual ~BaseFilterBank(); virtual void reset() = 0; protected: class RealBuffer_ { public: /* @brief Construct a circular buffer to keep samples periodically. It keeps nsamp arrays which is completely updated with the period 'nsamp'. Each array holds actual values of the samples. @param unsigned len [in] The size of each array @param unsigned nsamp [in] The period of the circular buffer */ RealBuffer_(unsigned len, unsigned nsamp) : len_(len), nsamp_(nsamp), zero_(nsamp_ - 1), samples_(new gsl_vector*[nsamp_]) { for (unsigned i = 0; i < nsamp_; i++) samples_[i] = gsl_vector_calloc(len_); } ~RealBuffer_() { for (unsigned i = 0; i < nsamp_; i++) gsl_vector_free(samples_[i]); delete[] samples_; } const double sample(unsigned timeX, unsigned binX) const { unsigned idx = index_(timeX); const gsl_vector* vec = samples_[idx]; return gsl_vector_get(vec, binX); } void nextSample(const gsl_vector* s = NULL, bool reverse = false) { zero_ = (zero_ + 1) % nsamp_; gsl_vector* nextBlock = samples_[zero_]; if (s == NULL) { gsl_vector_set_zero(nextBlock); } else { if (s->size != len_) throw jdimension_error("'RealBuffer_': Sizes do not match (%d vs. %d)", s->size, len_); assert( s->size == len_ ); if (reverse) for (unsigned i = 0; i < len_; i++) gsl_vector_set(nextBlock, i, gsl_vector_get(s, len_ - i - 1)); else gsl_vector_memcpy(nextBlock, s); } } void nextSample(const gsl_vector_float* s) { zero_ = (zero_ + 1) % nsamp_; gsl_vector* nextBlock = samples_[zero_]; assert( s->size == len_ ); for (unsigned i = 0; i < len_; i++) gsl_vector_set(nextBlock, i, gsl_vector_float_get(s, i)); } void nextSample(const gsl_vector_short* s) { zero_ = (zero_ + 1) % nsamp_; gsl_vector* nextBlock = samples_[zero_]; assert( s->size == len_ ); for (unsigned i = 0; i < len_; i++) gsl_vector_set(nextBlock, i, gsl_vector_short_get(s, i)); } void zero() { for (unsigned i = 0; i < nsamp_; i++) gsl_vector_set_zero(samples_[i]); zero_ = nsamp_ - 1; } private: unsigned index_(unsigned idx) const { assert(idx < nsamp_); unsigned ret = (zero_ + nsamp_ - idx) % nsamp_; return ret; } const unsigned len_; const unsigned nsamp_; unsigned zero_; // index of most recent sample gsl_vector** samples_; }; BaseFilterBank(gsl_vector* prototype, unsigned M, unsigned m, unsigned r = 0, bool synthesis = false); const unsigned M_; const unsigned Mx2_; const unsigned m_; const unsigned mx2_; const unsigned r_; const unsigned R_; const unsigned Rx2_; const unsigned D_; }; // ----- definition for class `NormalFFTAnalysisBank' ----- // /** @class do FFT on time discrete samples multiplied with a window. */ class NormalFFTAnalysisBank : protected BaseFilterBank, public VectorComplexFeatureStream { public: NormalFFTAnalysisBank(VectorFloatFeatureStreamPtr& samp, unsigned fftLen, unsigned r = 1, unsigned windowType = 1, const String& nm = "NormalFFTAnalysisBank"); ~NormalFFTAnalysisBank(); virtual const gsl_vector_complex* next(int frame_no = -5); virtual void reset(); unsigned fftlen() const { return N_; } #ifdef ENABLE_LEGACY_BTK_API unsigned fftLen() const { return fftlen(); } #endif protected: void update_buf_(); virtual void update_buffer_(int frame_no); #ifdef HAVE_LIBFFTW3 fftw_plan fftwPlan_; #endif const VectorFloatFeatureStreamPtr samp_; int winType_; // 1 = hamming, 2 = hann window unsigned N_; // FFT length const unsigned processing_delay_; unsigned framesPadded_; RealBuffer_ buffer_; gsl_vector* convert_; RealBuffer_ gsi_; double* output_; const gsl_vector* prototype_; }; typedef Inherit<NormalFFTAnalysisBank, VectorComplexFeatureStreamPtr> NormalFFTAnalysisBankPtr; /** * \defgroup OversampledFilterBank Oversampled Filter Bank */ /*@{*/ // ----- definition for class `OverSampledDFTFilterBank' ----- // class OverSampledDFTFilterBank : public BaseFilterBank { public: ~OverSampledDFTFilterBank(); virtual void reset(); protected: OverSampledDFTFilterBank(gsl_vector* prototype, unsigned M, unsigned m, unsigned r = 0, bool synthesis = false, unsigned delayCompensationType=0, int gainFactor=1 ); double polyphase(unsigned m, unsigned n) const { return gsl_vector_get(prototype_, m + M_ * n); } unsigned laN_; /*>! the number of look-ahead */ const unsigned N_; unsigned processing_delay_; const gsl_vector* prototype_; RealBuffer_ buffer_; gsl_vector* convert_; RealBuffer_ gsi_; const int gain_factor_; }; /*@}*/ /** * \defgroup PerfectReconstructionFilterBank Perfect Reconstruction Filter Bank */ /*@{*/ // ----- definition for class `PerfectReconstructionFilterBank' ----- // class PerfectReconstructionFilterBank : public BaseFilterBank { public: ~PerfectReconstructionFilterBank(); virtual void reset(); protected: PerfectReconstructionFilterBank(gsl_vector* prototype, unsigned M, unsigned m, unsigned r = 0, bool synthesis = false); double polyphase(unsigned m, unsigned n) const { return gsl_vector_get(prototype_, m + Mx2_ * n); } const unsigned N_; const unsigned processing_delay_; const gsl_vector* prototype_; RealBuffer_ buffer_; gsl_vector* convert_; gsl_vector_complex* w_; RealBuffer_ gsi_; }; /*@}*/ /** * \addtogroup OversampledFilterBank */ /*@{*/ // ----- definition for class `OverSampledDFTAnalysisBank' ----- // class OverSampledDFTAnalysisBank : protected OverSampledDFTFilterBank, public VectorComplexFeatureStream { public: OverSampledDFTAnalysisBank(VectorFloatFeatureStreamPtr& samp, gsl_vector* prototype, unsigned M, unsigned m, unsigned r, unsigned delayCompensationType =0, const String& nm = "OverSampledDFTAnalysisBank"); ~OverSampledDFTAnalysisBank(); virtual const gsl_vector_complex* next(int frame_no = -5); virtual void reset(); unsigned fftlen() const { return M_; } unsigned shiftlen() const { return D_; } #ifdef ENABLE_LEGACY_BTK_API unsigned fftLen() const { return fftlen(); } unsigned nBlocks() const { return m_; } unsigned subSampRate() const { return r_; } #endif bool is_end(){return is_end_;} int frame_no() const { return frame_no_; } using OverSampledDFTFilterBank::polyphase; private: void update_buf_(); bool update_buffer_(int frame_no); #ifdef HAVE_LIBFFTW3 fftw_plan fftwPlan_; #endif const VectorFloatFeatureStreamPtr samp_; double* polyphase_output_; unsigned framesPadded_; }; typedef Inherit<OverSampledDFTAnalysisBank, VectorComplexFeatureStreamPtr> OverSampledDFTAnalysisBankPtr; // ----- definition for class `OverSampledDFTSynthesisBank' ----- // class OverSampledDFTSynthesisBank : private OverSampledDFTFilterBank, public VectorFloatFeatureStream { public: OverSampledDFTSynthesisBank(VectorComplexFeatureStreamPtr& samp, gsl_vector* prototype, unsigned M, unsigned m, unsigned r = 0, unsigned delayCompensationType = 0, int gainFactor=1, const String& nm = "OverSampledDFTSynthesisBank"); OverSampledDFTSynthesisBank(gsl_vector* prototype, unsigned M, unsigned m, unsigned r = 0, unsigned delayCompensationType = 0, int gainFactor=1, const String& nm = "OverSampledDFTSynthesisBank"); ~OverSampledDFTSynthesisBank(); virtual const gsl_vector_float* next(int frame_no = -5); virtual void reset(); using OverSampledDFTFilterBank::polyphase; void input_source_vector(const gsl_vector_complex* block){ update_buf_(block); } void no_stream_feature(bool flag=true){ no_stream_feature_ = flag; } #ifdef ENABLE_LEGACY_BTK_API void inputSourceVector(const gsl_vector_complex* block){ input_source_vector(block); } void doNotUseStreamFeature(bool flag=true){ no_stream_feature(flag); } #endif private: bool update_buffer_(int frame_no); void update_buf_(const gsl_vector_complex* block); const VectorComplexFeatureStreamPtr samp_; bool no_stream_feature_; #ifdef HAVE_LIBFFTW3 fftw_plan fftwPlan_; #endif double* polyphase_input_; }; typedef Inherit<OverSampledDFTSynthesisBank, VectorFloatFeatureStreamPtr> OverSampledDFTSynthesisBankPtr; /*@}*/ /** * \addtogroup PerfectReconstructionFilterBank */ /*@{*/ // ----- definition for class `PerfectReconstructionFFTAnalysisBank' ----- // class PerfectReconstructionFFTAnalysisBank : protected PerfectReconstructionFilterBank, public VectorComplexFeatureStream { public: PerfectReconstructionFFTAnalysisBank(VectorFloatFeatureStreamPtr& samp, gsl_vector* prototype, unsigned M, unsigned m, unsigned r, const String& nm = "PerfectReconstructionFFTAnalysisBank"); ~PerfectReconstructionFFTAnalysisBank(); virtual const gsl_vector_complex* next(int frame_no = -5); virtual void reset(); #ifdef ENABLE_LEGACY_BTK_API unsigned fftLen() const { return Mx2_; } unsigned nBlocks() const { return 4; } unsigned subSampRate() const { return 2; } #endif using PerfectReconstructionFilterBank::polyphase; protected: void update_buf_(); virtual void update_buffer_(int frame_no); #ifdef HAVE_LIBFFTW3 fftw_plan fftwPlan_; #endif double* polyphase_output_; unsigned framesPadded_; const VectorFloatFeatureStreamPtr samp_; }; typedef Inherit<PerfectReconstructionFFTAnalysisBank, VectorComplexFeatureStreamPtr> PerfectReconstructionFFTAnalysisBankPtr; // ----- definition for class `PerfectReconstructionFFTSynthesisBank' ----- // class PerfectReconstructionFFTSynthesisBank : private PerfectReconstructionFilterBank, public VectorFloatFeatureStream { public: PerfectReconstructionFFTSynthesisBank(VectorComplexFeatureStreamPtr& samp, gsl_vector* prototype, unsigned M, unsigned m, unsigned r = 0, const String& nm = "PerfectReconstructionFFTSynthesisBank"); PerfectReconstructionFFTSynthesisBank(gsl_vector* prototype, unsigned M, unsigned m, unsigned r = 0, const String& nm = "PerfectReconstructionFFTSynthesisBank"); ~PerfectReconstructionFFTSynthesisBank(); virtual const gsl_vector_float* next(int frame_no = -5); virtual void reset(); using PerfectReconstructionFilterBank::polyphase; private: void update_buffer_(int frame_no); void update_buffer_(const gsl_vector_complex* block); const VectorComplexFeatureStreamPtr samp_; #ifdef HAVE_LIBFFTW3 fftw_plan fftwPlan_; #endif double* polyphase_input_; }; typedef Inherit<PerfectReconstructionFFTSynthesisBank, VectorFloatFeatureStreamPtr> PerfectReconstructionFFTSynthesisBankPtr; // ----- definition for class `DelayFeature' ----- // class DelayFeature : public VectorComplexFeatureStream { public: DelayFeature( const VectorComplexFeatureStreamPtr& samp, float time_delay=0.0, const String& nm = "DelayFeature"); ~DelayFeature(); void set_time_delay(float time_delay){ time_delay_ = time_delay; } virtual const gsl_vector_complex* next(int frame_no = -5); virtual void reset(); private: const VectorComplexFeatureStreamPtr samp_; float time_delay_; }; typedef Inherit<DelayFeature, VectorComplexFeatureStreamPtr> DelayFeaturePtr; gsl_vector* get_window(unsigned winType, unsigned winLen); void write_gsl_format(const String& fileName, const gsl_vector* prototype); /*@}*/ /*@}*/ #endif
{ "alphanum_fraction": 0.6997362706, "avg_line_length": 28.0871459695, "ext": "h", "hexsha": "6ef1d8d1b08434d857cda35c2538957c585330ff", "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/modulated/modulated.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/modulated/modulated.h", "max_line_length": 167, "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/modulated/modulated.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": 3237, "size": 12892 }
/** @file * Based on the paper: * Quintana, F.A. (1998) ``Nonparametric Bayesian analysis for assessing homogeneity in $ k\times l$ * contingency tables with fixed right margin totals''. * Also as Technical Report PUC/FM-96/7. Journal of the American Statistical Association, 93(443), 1140-1149. * Available as compressed postscript. * http://www.mat.puc.cl/~quintana/hcttr.ps.gz */ #ifndef BIO_CONTINGENCY_HOMOGENEITY_H_ #define BIO_CONTINGENCY_HOMOGENEITY_H_ #include "bio/defs.h" #include "bio/partition.h" #include <boost/assign/list_of.hpp> #include <gsl/gsl_sf_log.h> #include <gsl/gsl_sf_exp.h> #include <gsl/gsl_machine.h> #include <gsl/gsl_sf_gamma.h> #include <numeric> #include <stdexcept> BIO_NS_START typedef std::vector<double> gamma_vec_t; extern gamma_vec_t contingency_gamma_exponential_prior; template <class LambdaIt> double calculate_ln_D( LambdaIt lambda_begin, LambdaIt lambda_end) { double result = gsl_sf_lngamma(std::accumulate(lambda_begin, lambda_end, double(0))); for (LambdaIt i = lambda_begin; lambda_end != i; ++i) { result -= gsl_sf_lngamma(*i); } return result; } /** Calculate natural logarithm of a term for one partition in Lm(n). */ template <class PartitionIt, class CountIt, class LambdaIt> double contingency_calculate_ln_L_term( PartitionIt part_it, unsigned m, CountIt n_begin, CountIt n_end, LambdaIt lambda_begin, LambdaIt lambda_end) { double ln_result = 1.0; #ifdef BIO_CONTINGENCY_PRINT_PARTITIONS //can only do this for smallish numbers if (26 >= part_it.M.size()) { std::vector<char> v; for (unsigned i = 0; i != part_it.M.size(); ++i) { v.push_back('a' + i); } std::cout << *part_it[v] << '\n'; } #endif //BIO_CONTINGENCY_PRINT_PARTITIONS //for each set in the partition for (unsigned i = 0; i < m; ++i) { //calculate lambda + n typedef std::vector<double> lambda_vec_t; lambda_vec_t lambda_plus_n; { std::copy(lambda_begin, lambda_end, std::inserter(lambda_plus_n, lambda_plus_n.begin())); unsigned e_i = 0; unsigned j = 0; //for each index for (CountIt n = n_begin; n_end != n; ++j, ++n) { //is this j in this partition? if (i == part_it.M[j]) { for (unsigned k = 0; k != (*n).size(); ++k) { lambda_plus_n[k] += (*n)[k]; } if (1 < e_i) { ln_result += gsl_sf_log(double(e_i)); //the factorial term } ++e_i; } } } ln_result += calculate_ln_D(lambda_begin, lambda_end); ln_result -= calculate_ln_D(lambda_plus_n.begin(), lambda_plus_n.end()); } return ln_result; } /** Calculate Lm(n). */ template <class CountIt, class LambdaIt> double contingency_calculate_L( unsigned m, CountIt n_begin, CountIt n_end, LambdaIt lambda_begin, LambdaIt lambda_end) { unsigned set_size = unsigned(n_end - n_begin); BOOST_ASSERT(unsigned(lambda_end - lambda_begin) == set_size); double result = 0; //iterate over all the partitions partition::iterator_k part_it(set_size, m); try { while (true) { const double ln_L_term = contingency_calculate_ln_L_term( part_it, m, n_begin, n_end, lambda_begin, lambda_end); //check for underflow - in which case it will be 0. if (ln_L_term > GSL_LOG_DBL_MIN) { result += gsl_sf_exp(ln_L_term); } ++part_it; } } catch (std::overflow_error&) //how the partition code determines there are no more partitions! { } return result; } template <class Value> Value factorial(Value value) { Value result = Value(1); while (value != 0) { result *= value; --value; } return result; } typedef double(* contingency_cluster_prior)(double c, void * void_params); struct ContingencyClusterPrior { virtual double operator()(double c) = 0; virtual double get_ln_prior(double c); }; struct ExponentialPrior : ContingencyClusterPrior { double mean; ExponentialPrior(double mean = 1.0); double operator()(double c); double get_ln_prior(double c); }; struct GammaParams { unsigned m; unsigned k; ContingencyClusterPrior * prior; }; double gamma_exponential_prior_integrand(double c, void * void_params); double contingency_calculate_gamma( unsigned m, unsigned k, ContingencyClusterPrior * prior); template <class GammaIt, class CountIt, class LambdaIt> double contingency_calculate_bayes_factor( GammaIt gamma_begin, GammaIt gamma_end, CountIt n_begin, CountIt n_end, LambdaIt lambda_begin, LambdaIt lambda_end) { const unsigned k = unsigned(n_end == n_begin ? 0 : n_begin->end() - n_begin->begin()); double result = contingency_calculate_L(1, n_begin, n_end, lambda_begin, lambda_end); result *= (1 - factorial(k-1) * (*gamma_begin)); result /= factorial(k-1); double sum = 0; for (unsigned i = 2; k + 1 != i; ++i) { sum += *(gamma_begin + i - 1) * contingency_calculate_L(i, n_begin, n_end, lambda_begin, lambda_end); } result /= sum; return result; } /** Contains the data for a contingency table and defines types. */ template <unsigned K, unsigned L> struct ContingencyTable { typedef boost::array<unsigned, K> row_t; typedef boost::array<row_t, L> table_t; typedef boost::array<double, L> lambda_vec_t; table_t data; static unsigned get_k() { return K; } static unsigned get_l() { return L; } }; template <unsigned K, unsigned L> std::ostream & operator<<(std::ostream & os, const ContingencyTable<K, L> & table) { for (unsigned l = 0; L != l; ++l) { for (unsigned k = 0; K != k; ++k) { os << table.data[l][k] << '\t'; } os << '\n'; } return os; } BIO_NS_END #endif //BIO_CONTINGENCY_HOMOGENEITY_H_
{ "alphanum_fraction": 0.693687231, "avg_line_length": 21.2015209125, "ext": "h", "hexsha": "99f1c77f03a8412f4cef7aa86e591c708c4e7bbc", "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": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "JohnReid/biopsy", "max_forks_repo_path": "C++/include/bio/contingency_homogeneity.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "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": "JohnReid/biopsy", "max_issues_repo_path": "C++/include/bio/contingency_homogeneity.h", "max_line_length": 109, "max_stars_count": null, "max_stars_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "JohnReid/biopsy", "max_stars_repo_path": "C++/include/bio/contingency_homogeneity.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1604, "size": 5576 }
/* * Copyright (c) 2011-2018 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * Copyright (c) 2013 Inria. All rights reserved. * * @precisions normal z -> c d s * */ #include <lapacke.h> #include "dplasma.h" #include "dplasmatypes.h" #include "parsec/data_dist/matrix/sym_two_dim_rectangle_cyclic.h" #include "parsec/data_dist/matrix/two_dim_rectangle_cyclic.h" /** ******************************************************************************* * * Generic case * ******************************************************************************* */ static int dplasma_zlatms_operator( parsec_execution_stream_t *es, const parsec_tiled_matrix_dc_t *descA, void *_A, PLASMA_enum uplo, int m, int n, void *args ) { int tempmm, tempnn, ldam, i; double *cond = (double*)args; parsec_complex64_t *A = (parsec_complex64_t*)_A; (void)es; tempmm = ((m)==((descA->mt)-1)) ? ((descA->m)-(m*(descA->mb))) : (descA->mb); tempnn = ((n)==((descA->nt)-1)) ? ((descA->n)-(n*(descA->nb))) : (descA->nb); ldam = BLKLDD( descA, m ); if (m == n) { LAPACKE_zlaset_work( LAPACK_COL_MAJOR, lapack_const( uplo ), tempmm, tempnn, 0., 0., A, ldam); /* D(i) = 1 - (i-1)/(N-1)*(1 - 1/COND) */ if ( m == 0 ) { A[0] = 1.; i = 1; } else { i = 0; } if ( descA->n > 1 ) { double tmp = 1. / (*cond); double alp = ( 1. - tmp ) / ((double)( descA->n - 1 )); int minmn = dplasma_imin( tempmm, tempnn ); for(; i < minmn; i++){ A[i+i*ldam] = (parsec_complex64_t)( (double)(descA->n-(descA->nb*n+i+1)) * alp + tmp ); } } } else { LAPACKE_zlaset_work( LAPACK_COL_MAJOR, 'A', tempmm, tempnn, 0., 0., A, ldam); } return 0; } /** ******************************************************************************* * * @ingroup dplasma_complex64 * * dplasma_zpltmg - Generates a special test matrix by tiles. * ******************************************************************************* * * @param[in,out] parsec * The parsec context of the application that will run the operation. * * @param[in] mtxtype * - PlasmaGeneral: Generate a general matrix * - PlasmaSymmetric: Generate a symmetric matrix * * @param[in,out] A * Descriptor of the distributed matrix A to generate. Any tiled matrix * descriptor can be used. * On exit, the matrix A generated. * * @param[in] seed * The seed used in the random generation. * ******************************************************************************* * * @return * \retval -i if the ith parameters is incorrect. * \retval 0 on success. * ******************************************************************************* * * @sa dplasma_cpltmg * @sa dplasma_dpltmg * @sa dplasma_spltmg * ******************************************************************************/ int dplasma_zlatms( parsec_context_t *parsec, PLASMA_enum mtxtype, double cond, parsec_tiled_matrix_dc_t *A, unsigned long long int seed) { two_dim_block_cyclic_t Q, T; int nodes, rank, mb, nb, m, n, mt, nt, P; int rc; /* Init the diagonal of A */ { parsec_taskpool_t *tp; double *condptr = malloc(sizeof( double )); *condptr = cond; tp = parsec_apply_New( PlasmaUpperLower, A, dplasma_zlatms_operator, condptr ); if ( tp != NULL ) { rc = parsec_context_add_taskpool(parsec, tp); rc = parsec_context_start( parsec ); rc = parsec_context_wait( parsec ); parsec_apply_Destruct(tp); } else { return -1; } } nodes = A->super.nodes; rank = A->super.myrank; mb = A->mb; nb = A->nb; m = A->m; n = A->n; mt = A->mt; nt = A->nt; if ( A->dtype & two_dim_block_cyclic_type ) { P = ((two_dim_block_cyclic_t*)A)->grid.rows; } else if ( A->dtype & sym_two_dim_block_cyclic_type ) { P = ((sym_two_dim_block_cyclic_t*)A)->grid.rows; } else { P = 1; } /* Init the random matrix R */ two_dim_block_cyclic_init( &Q, matrix_ComplexDouble, matrix_Tile, nodes, rank, mb, nb, m, n, 0, 0, m, n, 1, 1, P ); Q.mat = parsec_data_allocate((size_t)Q.super.nb_local_tiles * (size_t)Q.super.bsiz * (size_t)parsec_datadist_getsizeoftype(Q.super.mtype)); parsec_data_collection_set_key((parsec_data_collection_t*)&Q, "Q"); /* Init the T matrix */ two_dim_block_cyclic_init( &T, matrix_ComplexDouble, matrix_Tile, nodes, rank, 32, nb, mt*32, n, 0, 0, mt*32, n, 1, 1, P ); T.mat = parsec_data_allocate((size_t)T.super.nb_local_tiles * (size_t)T.super.bsiz * (size_t)parsec_datadist_getsizeoftype(T.super.mtype)); parsec_data_collection_set_key((parsec_data_collection_t*)&T, "T"); if ( mtxtype == PlasmaGeneral ) { if ( m >= n ) { parsec_tiled_matrix_dc_t *subA = tiled_matrix_submatrix( A, 0, 0, n, n ); parsec_tiled_matrix_dc_t *subQ = tiled_matrix_submatrix( (parsec_tiled_matrix_dc_t *)&Q, 0, 0, n, n ); parsec_tiled_matrix_dc_t *subT = tiled_matrix_submatrix( (parsec_tiled_matrix_dc_t *)&T, 0, 0, nt*32, n ); /* Multiply on the right by an unitary matrix */ dplasma_zplrnt( parsec, 0, subQ, seed + 1 ); dplasma_zgeqrf( parsec, subQ, subT ); dplasma_zunmqr( parsec, PlasmaRight, PlasmaNoTrans, subQ, subT, subA ); /* Multiply on the left by an unitary matrix */ dplasma_zplrnt( parsec, 0, (parsec_tiled_matrix_dc_t *)&Q, seed ); dplasma_zgeqrf( parsec, (parsec_tiled_matrix_dc_t*)&Q, (parsec_tiled_matrix_dc_t*)&T ); dplasma_zunmqr( parsec, PlasmaLeft, PlasmaNoTrans, (parsec_tiled_matrix_dc_t*)&Q, (parsec_tiled_matrix_dc_t*)&T, A ); free(subA); free(subQ); free(subT); } else { parsec_tiled_matrix_dc_t *subA = tiled_matrix_submatrix( A, 0, 0, m, m ); parsec_tiled_matrix_dc_t *subQ = tiled_matrix_submatrix( (parsec_tiled_matrix_dc_t *)&Q, 0, 0, m, m ); parsec_tiled_matrix_dc_t *subT = tiled_matrix_submatrix( (parsec_tiled_matrix_dc_t *)&T, 0, 0, mt*32, m ); /* Multiply on the left by an unitary matrix */ dplasma_zplrnt( parsec, 0, subQ, seed ); dplasma_zgeqrf( parsec, subQ, subT ); dplasma_zunmqr( parsec, PlasmaLeft, PlasmaNoTrans, subQ, subT, subA ); /* Multiply on the right by an unitary matrix */ dplasma_zplrnt( parsec, 0, (parsec_tiled_matrix_dc_t *)&Q, seed ); dplasma_zgeqrf( parsec, (parsec_tiled_matrix_dc_t*)&Q, (parsec_tiled_matrix_dc_t*)&T ); dplasma_zunmqr( parsec, PlasmaRight, PlasmaNoTrans, (parsec_tiled_matrix_dc_t*)&Q, (parsec_tiled_matrix_dc_t*)&T, A ); free(subA); free(subQ); free(subT); } } else { assert( mtxtype == PlasmaHermitian ); /* Init the unitary matrix */ dplasma_zplrnt( parsec, 0, (parsec_tiled_matrix_dc_t *)&Q, seed ); dplasma_zgeqrf( parsec, (parsec_tiled_matrix_dc_t*)&Q, (parsec_tiled_matrix_dc_t*)&T ); dplasma_zunmqr( parsec, PlasmaLeft, PlasmaNoTrans, (parsec_tiled_matrix_dc_t*)&Q, (parsec_tiled_matrix_dc_t*)&T, A ); dplasma_zunmqr( parsec, PlasmaRight, PlasmaConjTrans, (parsec_tiled_matrix_dc_t*)&Q, (parsec_tiled_matrix_dc_t*)&T, A ); } free(Q.mat); parsec_tiled_matrix_dc_destroy( (parsec_tiled_matrix_dc_t*)&Q ); free(T.mat); parsec_tiled_matrix_dc_destroy( (parsec_tiled_matrix_dc_t*)&T ); return 0; }
{ "alphanum_fraction": 0.4890510949, "avg_line_length": 36.4596774194, "ext": "c", "hexsha": "8a4286ada2062323c1b73c6aa2250a096d86585e", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "NLAFET/ABFT", "max_forks_repo_path": "dplasma/lib/zlatms_wrapper.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "NLAFET/ABFT", "max_issues_repo_path": "dplasma/lib/zlatms_wrapper.c", "max_line_length": 103, "max_stars_count": 1, "max_stars_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "NLAFET/ABFT", "max_stars_repo_path": "dplasma/lib/zlatms_wrapper.c", "max_stars_repo_stars_event_max_datetime": "2019-08-13T10:13:00.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-13T10:13:00.000Z", "num_tokens": 2335, "size": 9042 }
#ifndef ComplexMatrix_h #define ComplexMatrix_h #include <cmath> #include <complex> #include <iostream> #include <fstream> #include <iomanip> #ifndef NOBLAS extern "C" { #include <cblas.h> } // #ifdef SINGLEPRECISION // #define phi_hemm cblas_chemm // #define phi_symm cblas_csymm // #define phi_her cblas_cher // #define phi_gerc cblas_cgerc // #define phi_copy cblas_ccopy // #define phi_axpy cblas_caxpy // #define phi_dotc_sub cblas_cdotc_sub // #define phi_dotu_sub cblas_cdotu_sub // #define phi_scal cblas_zscal // #define phi_hemv cblas_chemv // #define phi_gemv cblas_cgemv // #else // #define phi_hemm cblas_zhemm // #define phi_symm cblas_zsymm // #define phi_her cblas_zher // #define phi_gerc cblas_zgerc // #define phi_copy cblas_zcopy // #define phi_axpy cblas_zaxpy // #define phi_dotc_sub cblas_zdotc_sub // #define phi_dotu_sub cblas_zdotu_sub // #define phi_scal cblas_zscal // #define phi_hemv cblas_zhemv // #define phi_gemv cblas_zgemv // #endif #else #ifndef CBLAS_ENUM_DEFINED_H #define CBLAS_ENUM_DEFINED_H enum CBLAS_ORDER {CblasRowMajor=101, CblasColMajor=102 }; enum CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113, AtlasConj=114}; enum CBLAS_UPLO {CblasUpper=121, CblasLower=122}; enum CBLAS_DIAG {CblasNonUnit=131, CblasUnit=132}; enum CBLAS_SIDE {CblasLeft=141, CblasRight=142}; #endif #endif using namespace std; #ifdef SINGLEPRECISION typedef float Float; typedef complex<float> Complex; #else typedef double Float; typedef complex<double> Complex; #endif struct Index2D { int i; int j; }; //#ifdef NOBLAS void phi_gemm(const int N, const Complex *alpha, const Complex *A, const Complex *B, const Complex *beta, Complex *C); void phi_hemm(const enum CBLAS_SIDE Side, const int N, const Complex *alpha, const Complex *A, const Complex *B, const Complex *beta, Complex *C); void phi_symm(const enum CBLAS_SIDE Side, const int N, const Complex *alpha, const Complex *A, const Complex *B, const Complex *beta, Complex *C); void phi_her(const int N, const Float alpha, const Complex *X, Complex *A); void phi_gerc(const int N, const Complex *alpha, const Complex *X, const Complex *Y, Complex *A); void phi_copy(const int N, const Complex *X, const int incX, Complex *Y, const int incY); void phi_axpy(const int N, const Complex *alpha, const Complex *X, const int incX, Complex *Y, const int incY); void phi_dotc_sub(const int N, const Complex *X, const int incX, const Complex *Y, const int incY, Complex *dotc); void phi_dotu_sub(const int N, const Complex *X, const int incX, const Complex *Y, const int incY, Complex *dotu); void phi_scal(const int N, const Complex *alpha, Complex *X, const int incX); void phi_hemv(const int N, const Complex *alpha, const Complex *A, const Complex *X, const Complex *beta, Complex *Y); void phi_gemv(const int N, const Complex *alpha, const Complex *A, const Complex *X, const Complex *beta, Complex *Y); //#endif //Equal size square matrices only Complex * outerProduct(const Complex *,const Complex *, const int); Complex * toLiouville(const Complex *,const int); void printMatrix(const Complex *, const int); void printMatrix(const Complex *, const Index2D *, const int); void writeMatrixToFile(const Complex *, const int, ofstream &); #endif
{ "alphanum_fraction": 0.6589456869, "avg_line_length": 31.041322314, "ext": "h", "hexsha": "6c8222ec43b3ad952620d4af3ee5dc1b20588b45", "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": "eeb609bdb59c71410aa1a7a5039492588600a8dd", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "dhold/Matlab_code", "max_forks_repo_path": "PHI code/phi-source/src/ComplexMatrix.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "eeb609bdb59c71410aa1a7a5039492588600a8dd", "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": "dhold/Matlab_code", "max_issues_repo_path": "PHI code/phi-source/src/ComplexMatrix.h", "max_line_length": 94, "max_stars_count": null, "max_stars_repo_head_hexsha": "eeb609bdb59c71410aa1a7a5039492588600a8dd", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "dhold/Matlab_code", "max_stars_repo_path": "PHI code/phi-source/src/ComplexMatrix.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1035, "size": 3756 }
#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_hpr (void) { const double flteps = 1e-4, dbleps = 1e-6; { int order = 101; int uplo = 121; int N = 2; float alpha = 0.1f; float Ap[] = { -0.273f, -0.499f, -0.305f, -0.277f, 0.238f, -0.369f }; float X[] = { 0.638f, -0.905f, 0.224f, 0.182f }; int incX = -1; float Ap_expected[] = { -0.26467f, 0.0f, -0.30718f, -0.245116f, 0.360607f, 0.0f }; cblas_chpr(order, uplo, N, alpha, X, incX, Ap); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Ap[2*i], Ap_expected[2*i], flteps, "chpr(case 1418) real"); gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], flteps, "chpr(case 1418) imag"); }; }; }; { int order = 101; int uplo = 122; int N = 2; float alpha = 0.1f; float Ap[] = { -0.273f, -0.499f, -0.305f, -0.277f, 0.238f, -0.369f }; float X[] = { 0.638f, -0.905f, 0.224f, 0.182f }; int incX = -1; float Ap_expected[] = { -0.26467f, 0.0f, -0.30718f, -0.308884f, 0.360607f, 0.0f }; cblas_chpr(order, uplo, N, alpha, X, incX, Ap); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Ap[2*i], Ap_expected[2*i], flteps, "chpr(case 1419) real"); gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], flteps, "chpr(case 1419) imag"); }; }; }; { int order = 102; int uplo = 121; int N = 2; float alpha = 0.1f; float Ap[] = { -0.273f, -0.499f, -0.305f, -0.277f, 0.238f, -0.369f }; float X[] = { 0.638f, -0.905f, 0.224f, 0.182f }; int incX = -1; float Ap_expected[] = { -0.26467f, 0.0f, -0.30718f, -0.245116f, 0.360607f, 0.0f }; cblas_chpr(order, uplo, N, alpha, X, incX, Ap); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Ap[2*i], Ap_expected[2*i], flteps, "chpr(case 1420) real"); gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], flteps, "chpr(case 1420) imag"); }; }; }; { int order = 102; int uplo = 122; int N = 2; float alpha = 0.1f; float Ap[] = { -0.273f, -0.499f, -0.305f, -0.277f, 0.238f, -0.369f }; float X[] = { 0.638f, -0.905f, 0.224f, 0.182f }; int incX = -1; float Ap_expected[] = { -0.26467f, 0.0f, -0.30718f, -0.308884f, 0.360607f, 0.0f }; cblas_chpr(order, uplo, N, alpha, X, incX, Ap); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Ap[2*i], Ap_expected[2*i], flteps, "chpr(case 1421) real"); gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], flteps, "chpr(case 1421) imag"); }; }; }; { int order = 101; int uplo = 121; int N = 2; double alpha = 1; double Ap[] = { 0.265, 0.362, -0.855, 0.035, 0.136, 0.133 }; double X[] = { -0.278, -0.686, -0.736, -0.918 }; int incX = -1; double Ap_expected[] = { 1.64942, 0.0, -0.020644, -0.214692, 0.68388, 0.0 }; cblas_zhpr(order, uplo, N, alpha, X, incX, Ap); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Ap[2*i], Ap_expected[2*i], dbleps, "zhpr(case 1422) real"); gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], dbleps, "zhpr(case 1422) imag"); }; }; }; { int order = 101; int uplo = 122; int N = 2; double alpha = 1; double Ap[] = { 0.265, 0.362, -0.855, 0.035, 0.136, 0.133 }; double X[] = { -0.278, -0.686, -0.736, -0.918 }; int incX = -1; double Ap_expected[] = { 1.64942, 0.0, -0.020644, 0.284692, 0.68388, 0.0 }; cblas_zhpr(order, uplo, N, alpha, X, incX, Ap); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Ap[2*i], Ap_expected[2*i], dbleps, "zhpr(case 1423) real"); gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], dbleps, "zhpr(case 1423) imag"); }; }; }; { int order = 102; int uplo = 121; int N = 2; double alpha = 1; double Ap[] = { 0.265, 0.362, -0.855, 0.035, 0.136, 0.133 }; double X[] = { -0.278, -0.686, -0.736, -0.918 }; int incX = -1; double Ap_expected[] = { 1.64942, 0.0, -0.020644, -0.214692, 0.68388, 0.0 }; cblas_zhpr(order, uplo, N, alpha, X, incX, Ap); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Ap[2*i], Ap_expected[2*i], dbleps, "zhpr(case 1424) real"); gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], dbleps, "zhpr(case 1424) imag"); }; }; }; { int order = 102; int uplo = 122; int N = 2; double alpha = 1; double Ap[] = { 0.265, 0.362, -0.855, 0.035, 0.136, 0.133 }; double X[] = { -0.278, -0.686, -0.736, -0.918 }; int incX = -1; double Ap_expected[] = { 1.64942, 0.0, -0.020644, 0.284692, 0.68388, 0.0 }; cblas_zhpr(order, uplo, N, alpha, X, incX, Ap); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Ap[2*i], Ap_expected[2*i], dbleps, "zhpr(case 1425) real"); gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], dbleps, "zhpr(case 1425) imag"); }; }; }; }
{ "alphanum_fraction": 0.5260780287, "avg_line_length": 28.3139534884, "ext": "c", "hexsha": "385f8d8ac6b2a5c68e6be058a8996918a6e7f978", "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_hpr.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_hpr.c", "max_line_length": 85, "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_hpr.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": 2194, "size": 4870 }
/** * @file videofeature.h * @brief Audio-visual speech recognition front end. * @author Munir Georges, John McDonough, Friedrich Faubel */ #include "btk.h" #ifdef AVFORMAT #ifdef OPENCV #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_sort_vector.h> #ifdef HAVE_LIBFFTW3 #include <fftw3.h> #endif #undef HAVE_CONFIG_H #include <opencv/cv.h> #include <opencv/highgui.h> #define HAVE_CONFIG_H #include "stream/stream.h" #include "common/mlist.h" #ifndef VIDEOFEATURE_H #define VIDEOFEATURE_H // ----- definition for class VideoFeature ----- // class VideoFeature : public VectorFloatFeatureStream { public: // sz := number of elements in _vector VideoFeature(int mode, unsigned width, unsigned height, const String& nm = "VideoFeature"); ~VideoFeature(); virtual const gsl_vector_float* next(int frameX = -5); virtual void reset(); void read(const String& fileName, int from, int _to); int width() const { return _width; } int height() const { return _height; } int frameNumber() const { return _frameNumber;} int Frames(); private: CvCapture* _capture; IplImage* _frame; IplImage* _gray; IplImage* _hsv; unsigned _width; unsigned _height; gsl_vector_float* _R; gsl_vector_float* _G; gsl_vector_float* _B; String _filename; unsigned _from; unsigned _to; int _mode; bool _endOfSamples; string _fileName; int _frameNumber; }; typedef Inherit<VideoFeature, VectorFloatFeatureStreamPtr> VideoFeaturePtr; // ----- definition for class 'ImageROI' ----- // class ImageROI : public VectorFloatFeatureStream { public: // sz := number of elements in _vector ImageROI(const VectorFloatFeatureStreamPtr& src, unsigned width, unsigned height, unsigned x=0, unsigned y=0, unsigned w=2, unsigned h=3, const String& nm = "ImageROI"); ~ImageROI(); void setROI(int x,int y); gsl_vector_float* data(); virtual const gsl_vector_float* next(int frameX = -5); virtual void reset(); unsigned width() const { return _width; } unsigned height() const { return _height; } unsigned x_pos() const { return _x_pos; } unsigned y_pos() const { return _y_pos; } unsigned w() const { return _w; } unsigned h() const { return _h; } private: VectorFloatFeatureStreamPtr _src; bool _endOfSamples; const unsigned _width; const unsigned _height; gsl_vector_float* _srcVec; const unsigned _w; const unsigned _h; unsigned _x_pos; unsigned _y_pos; }; typedef Inherit<ImageROI, VectorFloatFeatureStreamPtr> ImageROIPtr; // ----- definition for class ImageSmooth ----- // class ImageSmooth : public VectorFloatFeatureStream { public: // sz := number of elements in _vector ImageSmooth(const VectorFloatFeatureStreamPtr& src,unsigned width,unsigned height, int smoothtype, int param1, int param2, const String& nm = "ImageSmooth"); ~ImageSmooth(); gsl_vector_float* data(); virtual const gsl_vector_float* next(int frameX = -5); virtual void reset(); private: VectorFloatFeatureStreamPtr _src; bool _endOfSamples; unsigned _width; unsigned _height; gsl_vector_float* _srcVec; IplImage* _img; IplImage* _imgf; int _smoothtype; int _param1; int _param2; }; typedef Inherit<ImageSmooth, VectorFloatFeatureStreamPtr> ImageSmoothPtr; // ----- definition for class ImageMorphology ----- // class ImageMorphology : public VectorFloatFeatureStream { public: // sz := number of elements in _vector ImageMorphology(const VectorFloatFeatureStreamPtr& src,unsigned width,unsigned height, int type, int param, const String& nm = "ImageMorphology"); ~ImageMorphology(); gsl_vector_float* data(); virtual const gsl_vector_float* next(int frameX = -5); virtual void reset(); private: VectorFloatFeatureStreamPtr _src; bool _endOfSamples; unsigned _width; unsigned _height; gsl_vector_float* _srcVec; IplImage* _img; IplImage* _imgf; int _type; int _param; }; typedef Inherit<ImageMorphology, VectorFloatFeatureStreamPtr> ImageMorphologyPtr; // ----- definition for class ImageMorphologyEx ----- // class ImageMorphologyEx : public VectorFloatFeatureStream { public: // sz := number of elements in _vector ImageMorphologyEx(const VectorFloatFeatureStreamPtr& src,unsigned width,unsigned height, int type, int param, const String& nm = "ImageMorphologyEx"); ~ImageMorphologyEx(); gsl_vector_float* data(); virtual const gsl_vector_float* next(int frameX = -5); virtual void reset(); private: VectorFloatFeatureStreamPtr _src; bool _endOfSamples; unsigned _width; unsigned _height; gsl_vector_float* _srcVec; IplImage* _img; IplImage* _imgf; IplImage* _temp; int _type; int _param; }; typedef Inherit<ImageMorphologyEx, VectorFloatFeatureStreamPtr> ImageMorphologyExPtr; // ----- definition for class Canny ----- // class Canny : public VectorFloatFeatureStream { public: // sz := number of elements in _vector Canny(const VectorFloatFeatureStreamPtr& src,unsigned width,unsigned height, int param0, int param1, int param2, const String& nm = "Canny"); ~Canny(); gsl_vector_float* data(); virtual const gsl_vector_float* next(int frameX = -5); virtual void reset(); private: VectorFloatFeatureStreamPtr _src; bool _endOfSamples; unsigned _width; unsigned _height; gsl_vector_float* _srcVec; IplImage* _img; IplImage* _imgf; int _param0; int _param1; int _param2; }; typedef Inherit<Canny, VectorFloatFeatureStreamPtr> CannyPtr; // ----- definition for class ImageThreshold ----- // class ImageThreshold : public VectorFloatFeatureStream { public: // sz := number of elements in _vector ImageThreshold(const VectorFloatFeatureStreamPtr& src,unsigned width,unsigned height, float param0, int param1, int param2, const String& nm = "Canny"); ~ImageThreshold(); gsl_vector_float* data(); virtual const gsl_vector_float* next(int frameX = -5); virtual void reset(); private: VectorFloatFeatureStreamPtr _src; bool _endOfSamples; unsigned _width; unsigned _height; gsl_vector_float* _srcVec; IplImage* _img; IplImage* _imgf; int _param0; int _param1; int _param2; }; typedef Inherit<ImageThreshold, VectorFloatFeatureStreamPtr> ImageThresholdPtr; /*Do not use this funktion within python - there is a problem with the window-handle or threading....*/ // ----- definition for class imageshow ----- // class ImageShow : public VectorFloatFeatureStream { public: // sz := number of elements in _vector ImageShow(const VectorFloatFeatureStreamPtr& src,unsigned width,unsigned height, const String& nm = "ImageShow"); ~ImageShow(); virtual const gsl_vector_float* next(int frameX = -5); virtual void reset(); private: VectorFloatFeatureStreamPtr _src; unsigned _width; unsigned _height; IplImage* _img; gsl_vector_float* _srcVec; bool _endOfSamples; }; typedef Inherit<ImageShow, VectorFloatFeatureStreamPtr> ImageShowPtr; // ----- definition for class 'SaveImage' ----- // class SaveImage { public: // sz := number of elements in _vector SaveImage(unsigned width, unsigned height); ~SaveImage(); void save(const gsl_vector_float* V, const String& filename); void savedouble(const gsl_vector* V, const String& filename); private: unsigned _width; unsigned _height; IplImage* _img; const String _filename; }; typedef refcount_ptr<SaveImage> SaveImagePtr; // ----- definition for class 'ImageDetection' ----- // class ImageDetection : public VectorFloatFeatureStream { public: // sz := number of elements in _vector ImageDetection(VectorFloatFeatureStreamPtr& src, unsigned width, unsigned height, unsigned w, unsigned h, const String& filename, double scale_factor, int min_neighbors, int flags, int min_sizeX, int min_sizeY, const String& nm = "ImageDetection"); ~ImageDetection(); gsl_vector_float* data(); virtual const gsl_vector_float* next(int frameX = -5); virtual void reset(); private: double _linearnext(gsl_vector * v); VectorFloatFeatureStreamPtr _src; const unsigned _width; const unsigned _height; unsigned _w; unsigned _h; gsl_vector_float* _srcVec; IplImage* _img; const String _filename; CvHaarClassifierCascade* _pCascade; CvMemStorage* _pStorage; CvSeq* _pRectSeq; double _scale_factor; int _min_neighbors; int _flags; CvSize _min_size; int _x_pos; int _y_pos; const int _his; gsl_vector* _x_his; gsl_vector* _y_his; int _tmp_x; int _tmp_y; bool _endOfSamples; }; typedef Inherit<ImageDetection, VectorFloatFeatureStreamPtr> ImageDetectionPtr; // ----- definition for class FaceDetection ----- // class FaceDetection : public VectorFloatFeatureStream { public: // sz := number of elements in _vector FaceDetection(VectorFloatFeatureStreamPtr& src, unsigned width, unsigned height, int region, const String& filename_eye, double scale_factor_eye, int min_neighbors_eye, int flags_eye, int min_sizeX_eye, int min_sizeY_eye, const String& filename_nose, double scale_factor_nose, int min_neighbors_nose, int flags_nose, int min_sizeX_nose, int min_sizeY_nose, const String& filename_mouth, double scale_factor_mouth, int min_neighbors_mouth, int flags_mouth, int min_sizeX_mouth, int min_sizeY_mouth, const String& nm = "FaceDetection"); ~FaceDetection(); virtual const gsl_vector_float* next(int frameX = -5); virtual void reset(); private: bool _endOfSamples; VectorFloatFeatureStreamPtr _src; gsl_vector_float* _srcVec; unsigned _width; unsigned _height; }; typedef Inherit<FaceDetection, VectorFloatFeatureStreamPtr> FaceDetectionPtr; // ----- definition for class ImageCentering ----- // class ImageCentering : public VectorFloatFeatureStream { public: // sz := number of elements in _vector ImageCentering(const VectorFloatFeatureStreamPtr& src,unsigned width,unsigned height, const String& nm = "ImageCentering"); ~ImageCentering(); gsl_vector_float* data(); virtual const gsl_vector_float* next(int frameX = -5); virtual void reset(); private: bool _endOfSamples; VectorFloatFeatureStreamPtr _src; gsl_vector_float* _srcVec; IplImage* _img; IplImage* _gmi; IplImage* _out; unsigned _width; unsigned _height; }; typedef Inherit<ImageCentering, VectorFloatFeatureStreamPtr> ImageCenteringPtr; // ----- definition for class LinearInterpolation ----- // class LinearInterpolation : public VectorFloatFeatureStream { public: // sz := number of elements in _vector LinearInterpolation(const VectorFloatFeatureStreamPtr& src, double fps_src, double fps_dest, const String& nm = "LinearInterpolation"); ~LinearInterpolation(); virtual const gsl_vector_float* next(int frameX = -5); virtual void reset(); private: VectorFloatFeatureStreamPtr _src; const double _DeltaTs; const double _DeltaTd; int _sourceFrameX; gsl_vector_float* _x_n; bool _endOfSamples; }; typedef Inherit<LinearInterpolation, VectorFloatFeatureStreamPtr> LinearInterpolationPtr; // ----- definition for class OpticalFlowFeature ----- // class OpticalFlowFeature : public VectorFloatFeatureStream { public: OpticalFlowFeature(const VectorFloatFeatureStreamPtr& src,unsigned width,unsigned height, const char* filename, const String& nm = "OpticalFlowFeature"); ~OpticalFlowFeature(); gsl_vector_float* data(); virtual const gsl_vector_float* next(int frameX = -5); virtual void reset(); private: float StringToFloat(const std::string& str_input); int StringToInt(const std::string& str_input); void disalloc_matrix(float **matrix, long nx, long ny); void alloc_matrix(float ***matrix, long nx, long ny); float ** _gray; float ** _ux; float ** _uy; typedef float fptype; typedef int itype; fptype **f1_c1; /* in : 1st image, channel 1*/ fptype **f2_c1; /* in : 2nd image, channel 1*/ fptype **f1_c2; /* in : 1st image, channel 2*/ fptype **f2_c2; /* in : 2nd image, channel 2*/ fptype **f1_c3; /* in : 1st image, channel 3*/ fptype **f2_c3; /* in : 2nd image, channel 3*/ fptype **u; /* in+out : u component of flow field */ fptype **v; /* in+out : v component of flow field */ itype _nx; /* in : size in x-direction on current grid */ itype _ny; /* in : size in y-direction on current grid */ itype _bx; /* in : boundary size in x-direction */ itype _by; /* in : boundary size in y-direction */ fptype hx; /* in : grid size in x-dir. on current grid */ fptype hy; /* in : grid size in y-dir. on current grid */ itype m_type_d; /* in : type of data term */ itype m_type_s; /* in : type of smoothness term */ fptype m_gamma_ofc1; /* in : weight of grey value constancy */ fptype m_gamma_ofc2; /* in : weight of gradient constancy */ fptype m_gamma_ofc3; /* in : weight of Hessian constancy */ fptype m_gamma_gradnorm;/* in : weight of gradient norm constancy */ fptype m_gamma_laplace; /* in : weight of Laplacian constancy */ fptype m_gamma_hessdet; /* in : weight of Hessian det. constancy */ itype m_function_d; /* in : type of robust function in data term */ itype m_function_s; /* in : type of robust function in smoothness term */ fptype m_epsilon_d; /* in : parameter data term */ fptype m_epsilon_s; /* in : parameter smoothness term */ fptype m_power_d; /* in : exponent data term */ fptype m_power_s; /* in : exponent smoothness term */ fptype m_rhox; /* in : integration scale in x-direction*/ fptype m_rhoy; /* in : integration scale in y-direction*/ fptype m_rhox_F; /* in : FLOW integration scale in x-direction*/ fptype m_rhoy_F; /* in : FLOW integration scale in y-direction*/ fptype m_sigma_F; /* in : FLOW presmoothing scale */ fptype m_alpha; /* in : smoothness weight */ itype m_color; /* in : color flag */ itype n_solver; /* in : general solver */ itype n_max_rec_depth; /* in : max rec depth */ itype n_mg_res_prob; /* in : resample problem */ itype n_theta; /* in : discretisation parameter */ itype n_mg_cycles; /* in : number of cycles */ itype n_mg_solver; /* in : type of multigrid solver */ itype n_mg_pre_relax; /* in : number of pre relaxation steps */ itype n_mg_post_relax; /* in : number of post relaxation steps */ itype n_mg_rec_calls; /* in : number of recursive calls */ itype n_mg_centered; /* in : intergrid transfer: 0-cell/1-vertex */ itype n_mg_mat_order_r;/* in : matrix multigrid restriction order */ itype n_mg_cas_order_r;/* in : cascadic multigrid restriction order */ itype n_mg_cas_order_p;/* in : cascadic multigrid prolongation order */ itype n_mg_cor_order_r;/* in : correcting multigrid restriction order */ itype n_mg_cor_order_p;/* in : correcting multigrid prolongation order */ itype n_iter_out; /* in : outer iterations */ itype n_iter_in; /* in : inner iterations */ fptype n_omega; /* in : overrelaxation parameter */ fptype n_tau; /* in : time step size */ fptype n_warp_eta; /* in : reduction factor */ itype n_warp_steps; /* in : warping steps per level */ itype n_warp_max_rec_depth; /*in : max warp rect depth */ itype n_warp_scaling; /* in : flag for scaling */ itype n_warp_rem; /* in : flag for removing out of bounds estimates */ itype n_warp_centered; /* in : warping intergrid transfer: 0-cell/1-vertex */ itype n_warp_order_r; /* in : correcting warping restriction order */ itype n_warp_order_p; /* in : correcting warping prolongation order */ fptype n_tensor_eps; /* in : motion tensor normalisation factor */ fptype **utruth; /* in : x-component of numerical ground truth */ fptype **vtruth; /* in : y-component of numerical ground truth */ fptype **uref; /* in : x-component of problem ground truth */ fptype **vref; /* in : y-component of problem ground truth */ fptype **error_mag; /* in : error magnitude map */ itype i_rel_res_flag; /* in : flag for relative residual computation */ fptype *i_rel_res; /* out : relative residual */ itype i_rel_err_flag; /* in : flag for relative error computation */ fptype *i_rel_err; /* out : relative error */ itype i_time_flag; /* in : flag for runtime computation */ itype *i_time_sec; /* out : consumed seconds */ itype *i_time_usec; /* out : consumed microseconds */ itype info_flag; /* in : flag for information */ itype info_step; /* in : stepsize for information */ itype write_flag; /* in : flag for writing out */ itype write_step; /* in : stepsize for writing out */ itype frame_nr; /* in : current frame number */ bool _endOfSamples; VectorFloatFeatureStreamPtr _src; gsl_vector_float* _srcVec; unsigned _width; unsigned _height; }; typedef Inherit<OpticalFlowFeature, VectorFloatFeatureStreamPtr> OpticalFlowFeaturePtr; // ----- definition for class SnakeImage ----- // class SnakeImage : public VectorFloatFeatureStream { public: SnakeImage(const VectorFloatFeatureStreamPtr& src,unsigned width,unsigned height, float alpha, float beta, float gamma, const String& nm = "SnakeImage"); ~SnakeImage(); gsl_vector_float* data(); virtual const gsl_vector_float* next(int frameX = -5); virtual void reset(); private: bool _endOfSamples; VectorFloatFeatureStreamPtr _src; gsl_vector_float* _srcVec; IplImage* _img; unsigned _width; unsigned _height; float _alpha; float _beta ; float _gamma; }; typedef Inherit<SnakeImage, VectorFloatFeatureStreamPtr> SnakeImagePtr; // ----- definition for class PCAFeature ----- // class PCAFeature : public VectorFloatFeatureStream { public: // sz := number of elements in _vector PCAFeature(const VectorFloatFeatureStreamPtr& src,unsigned width,unsigned height, const char *filename, const char *filename_mean, int n, int k, const String& nm = "PCAFeature"); ~PCAFeature(); virtual const gsl_vector_float* next(int frameX = -5); virtual void reset(); private: void _floatToDouble(gsl_vector_float *src, gsl_vector * dest); void _doubleToFloat(gsl_vector *src, gsl_vector_float * dest); void _normalizeRows(); VectorFloatFeatureStreamPtr _src; const unsigned _width; const unsigned _height; const unsigned _N; const unsigned _M; gsl_matrix* _evec; gsl_vector* _mean; gsl_vector_float* _srcVec; bool _endOfSamples; }; typedef Inherit<PCAFeature, VectorFloatFeatureStreamPtr> PCAFeaturePtr; // ----- definition for class IPCAFeature ----- // class IPCAFeature : public VectorFloatFeatureStream { public: // sz := number of elements in _vector IPCAFeature(const VectorFloatFeatureStreamPtr& src, unsigned width, unsigned height, const String& filename, const String& filename_mean, int n, int k, const String& nm = "IPCAFeature"); ~IPCAFeature(); virtual const gsl_vector_float* next(int frameX = -5); const gsl_vector* get_mean() const { return _mean; } const gsl_matrix* get_vec(int i) const { return _evec; } virtual void reset(); private: void _floatToDouble(gsl_vector_float* src, gsl_vector* dest); void _doubleToFloat(gsl_vector* src, gsl_vector_float* dest); void _normalizeRows(); VectorFloatFeatureStreamPtr _src; const unsigned _width; const unsigned _height; const unsigned _N; const unsigned _M; gsl_matrix* _evec; gsl_vector* _mean; gsl_vector_float* _srcVec; bool _endOfSamples; }; typedef Inherit<IPCAFeature, VectorFloatFeatureStreamPtr> IPCAFeaturePtr; // ----- definition for class PCAEstimator ----- // class PCAEstimator{ public: // sz := number of elements in _vector PCAEstimator(unsigned n,unsigned m); ~PCAEstimator(); void clearaccu(); void accumulate(gsl_vector_float *V); void estimate(); void save(const String& filename); const gsl_vector* get_mean() const { return _mean; } const gsl_matrix* get_vec() const { return _evec; } const gsl_vector* get_eigval() const { return _eval; } private: void _floatToDouble(gsl_vector_float* src, gsl_vector* dest); void _doubleToFloat(gsl_vector* src, gsl_vector_float* dest); unsigned _N; unsigned _M; unsigned _in_data; gsl_vector* _sum; //sum per row gsl_vector* _mean; gsl_matrix* _data; // original data, one image in each row gsl_matrix* _mdata; // data without row mean gsl_matrix* _mdatat; // data' gsl_matrix* _cov; // cov = 1/M * (mdata' * data) gsl_vector* _eval; //eigen values gsl_matrix* _evec; //eigen vector }; typedef refcount_ptr<PCAEstimator> PCAEstimatorPtr; // ----- definition for class PCAModEstimator ----- // class PCAModEstimator { public: // sz := number of elements in _vector PCAModEstimator(unsigned n, unsigned m); ~PCAModEstimator(); const gsl_vector* get_mean() const { return _mean; } const gsl_matrix* get_data() const { return _data; } const gsl_matrix* get_mdata() const { return _mdata; } const gsl_vector* get_eigval() const { return _eval; } const gsl_matrix* get_eigface() const { return _eigface; } const gsl_matrix* get_evecc() const { return _evecc; } const gsl_matrix* get_evec() const { return _evec; } const gsl_matrix* get_cov() const { return _cov; } void clearaccu(); void accumulate(gsl_vector_float* V); void estimate(); void save(const char* filename1, const char* filename2); private: void _floatToDouble(gsl_vector_float* src, gsl_vector* dest); void _doubleToFloat(gsl_vector* src, gsl_vector_float* dest); void _normalizeRows(); void _normalizeColumn(); const unsigned _N; const unsigned _M; unsigned _indata; gsl_matrix* _data; // original data, one image in each row gsl_matrix* _mdata; // data without row mean gsl_vector* _sum; // sum per row gsl_vector* _mean; // sum per row gsl_matrix* _mdatat; // data' gsl_matrix* _cov; // cov = 1/M * (mdata' * data) gsl_vector* _eval; // eigen values gsl_matrix* _evec; // eigen vector gsl_matrix* _evecc; // eigen vector gsl_matrix* _evecct; // eigen vector gsl_matrix* _eigface;// eigen vector }; typedef refcount_ptr<PCAModEstimator> PCAModEstimatorPtr; #endif #endif #endif
{ "alphanum_fraction": 0.6704421512, "avg_line_length": 31.2424639581, "ext": "h", "hexsha": "1b4c71804b99c55c96feb8445deca66f01a5b785", "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/feature/videofeature.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/feature/videofeature.h", "max_line_length": 189, "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/feature/videofeature.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": 6304, "size": 23838 }
#ifndef wf_H_INCLUDED #define wf_H_INCLUDED //#define DEBUG #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_integration.h> #include "alphas.h" //* // Global variables for UGD for nucleus 1 and 2 //* //run at fixed x //#define fixedx (0.001) //number of tabulated points in Y and kT for wavefunction #define NY 151 #define Nkt 101 #define kT_min (0.02) // phi=0 below this min kt #define kT_max (18.) // phi has a power lower extrapolation // beyond this max kt #define x0 (0.01) // separates small/large x #define XMIN (x0*exp(-15.)) //smallest x tabulated // Global variables for UGD for nucleus 1 and 2 int wfTAG; double uGD1[NY][Nkt]; double uGD2[NY][Nkt]; double Y[NY]; double kT[NY][Nkt]; gsl_interp_accel *accWF1[NY]; gsl_spline *WF1[NY]; gsl_interp_accel *accWF2[NY]; gsl_spline *WF2[NY]; gsl_interp_accel *accLargeX; gsl_spline *LargeX; //global variable for wfTAG=2 #define QS02 (0.1) double QS21, QS22; void ReadInWF(int A1, int A2, int TAG); double wf(int nucleus, double x, double kT) ; double wfsimple(int nucleus, double x, double kT) ; void PrintWF(double x, const char *out) ; #endif
{ "alphanum_fraction": 0.6983606557, "avg_line_length": 23.0188679245, "ext": "h", "hexsha": "608456801e801320c1fc5fc6549e167001af26d3", "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": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kdusling/mpc", "max_forks_repo_path": "src/wf.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "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": "kdusling/mpc", "max_issues_repo_path": "src/wf.h", "max_line_length": 63, "max_stars_count": null, "max_stars_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kdusling/mpc", "max_stars_repo_path": "src/wf.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 388, "size": 1220 }
/* * Copyright (c) 2011-2018 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * * @precisions normal z -> s d c * */ #include "dplasma_cores.h" #include "dplasma_zcores.h" #if defined(PARSEC_HAVE_STRING_H) #include <string.h> #endif /* defined(PARSEC_HAVE_STRING_H) */ #if defined(PARSEC_HAVE_STDARG_H) #include <stdarg.h> #endif /* defined(PARSEC_HAVE_STDARG_H) */ #include <stdio.h> #ifdef PARSEC_HAVE_LIMITS_H #include <limits.h> #endif #include <stdlib.h> #include <cblas.h> #include <core_blas.h> #define max(a, b) ((a) > (b) ? (a) : (b)) #define min(a, b) ((a) < (b) ? (a) : (b)) #if defined(ADD_) #define DLARFG zlarfg_ #else #define DLARFG zlarfg #endif extern void DLARFG(int *N, parsec_complex64_t *ALPHA, parsec_complex64_t *X, int *INCX, parsec_complex64_t *TAU); //static void band_to_trd_vmpi1(int N, int NB, parsec_complex64_t *A, int LDA); //static void band_to_trd_vmpi2(int N, int NB, parsec_complex64_t *A, int LDA); //static void band_to_trd_v8seq(int N, int NB, parsec_complex64_t *A, int LDA, int INgrsiz, int INthgrsiz); //static int TRD_seqgralgtype(int N, int NB, parsec_complex64_t *A, int LDA, parsec_complex64_t *C, parsec_complex64_t *S, int i, int j, int m, int grsiz, int BAND); int blgchase_ztrdv1(int NT, int N, int NB, parsec_complex64_t *A, parsec_complex64_t *V, parsec_complex64_t *TAU, int sweep, int id, int blktile); int blgchase_ztrdv2(int NT, int N, int NB, parsec_complex64_t *A1, parsec_complex64_t *A2, parsec_complex64_t *V1, parsec_complex64_t *TAU1, parsec_complex64_t *V2, parsec_complex64_t *TAU2, int sweep, int id, int blktile); int CORE_zlarfx2(int side, int N, parsec_complex64_t V, parsec_complex64_t TAU, parsec_complex64_t *C1, int LDC1, parsec_complex64_t *C2, int LDC2); int CORE_zlarfx2c(int uplo, parsec_complex64_t V, parsec_complex64_t TAU, parsec_complex64_t *C1, parsec_complex64_t *C2, parsec_complex64_t *C3); static void CORE_zhbtelr(int N, int NB, parsec_complex64_t *A1, int LDA1, parsec_complex64_t *A2, int LDA2, parsec_complex64_t *V1, parsec_complex64_t *TAU1, int st, int ed); static void CORE_zhbtrce(int N, int NB, parsec_complex64_t *A1, int LDA1, parsec_complex64_t *A2, int LDA2, parsec_complex64_t *V1, parsec_complex64_t *TAU1, parsec_complex64_t *V2, parsec_complex64_t *TAU2, int st, int ed, int edglob); static void CORE_zhbtlrx(int N, int NB, parsec_complex64_t *A1, int LDA1, parsec_complex64_t *A2, int LDA2, parsec_complex64_t *V1, parsec_complex64_t *TAU1, int st, int ed); static void DLARFX_C(char side, int N, parsec_complex64_t V, parsec_complex64_t TAU, parsec_complex64_t *C, int LDC); static void TRD_type1bHL(int N, int NB, parsec_complex64_t *A, int LDA, parsec_complex64_t *V, parsec_complex64_t *TAU, int st, int ed); static void TRD_type2bHL(int N, int NB, parsec_complex64_t *A, int LDA, parsec_complex64_t *V, parsec_complex64_t *TAU, int st, int ed); static void TRD_type3bHL(int N, int NB, parsec_complex64_t *A, int LDA, parsec_complex64_t *V, parsec_complex64_t *TAU, int st, int ed); int CORE_zlarfx2(int side, int N, parsec_complex64_t V, parsec_complex64_t TAU, parsec_complex64_t *C1, int LDC1, parsec_complex64_t *C2, int LDC2) { static parsec_complex64_t zzero = 0.0; int J; parsec_complex64_t V2, T2, SUM; /* Quick return */ /* if (N == 0) return PLASMA_SUCCESS; */ if (TAU == zzero) return 0; /* * Special code for 2 x 2 Householder where V1 = I */ if(side==PlasmaLeft){ V2 = conj(V); T2 = TAU*conj(V2); for (J = 0; J < N ; J++){ SUM = C1[J*LDC1] + V2*C2[J*LDC2]; C1[J*LDC1] = C1[J*LDC1] - SUM*TAU; C2[J*LDC2] = C2[J*LDC2] - SUM*T2; } }else if(side==PlasmaRight){ V2 = V; T2 = TAU*conj(V2); for (J = 0; J < N ; J++){ SUM = C1[J] + V2*C2[J]; C1[J] = C1[J] - SUM*TAU; C2[J] = C2[J] - SUM*T2; } } return 0; } /***************************************************************************//** * **/ int CORE_zlarfx2c(int uplo, parsec_complex64_t V, parsec_complex64_t TAU, parsec_complex64_t *C1, parsec_complex64_t *C2, parsec_complex64_t *C3) { static parsec_complex64_t zzero = 0.0; parsec_complex64_t T2, SUM, TEMP; /* Quick return */ if (TAU == zzero) return 0; /* * Special code for a diagonal block C1 * C2 C3 */ if(uplo==PlasmaLower){ //do the corner Left then Right (used for the lower case tridiag) // L and R for the 2x2 corner // C(N-1, N-1) C(N-1,N) C1 TEMP // C(N , N-1) C(N ,N) C2 C3 // For Left : use conj(TAU) and V. // For Right: nothing, keep TAU and V. // Left 1 ==> C1 // C2 TEMP = conj(C2[0]); // copy C2 here before modifying it. T2 = conj(TAU)*V; SUM = C1[0] + conj(V)*C2[0]; C1[0] = C1[0] - SUM*conj(TAU); C2[0] = C2[0] - SUM*T2; // Left 2 ==> TEMP // C3 SUM = TEMP + conj(V)*C3[0]; TEMP = TEMP - SUM*conj(TAU); C3[0] = C3[0] - SUM*T2; // Right 1 ==> C1 TEMP. NB: no need to compute corner (2,2)=TEMP T2 = TAU*conj(V); SUM = C1[0] + V*TEMP; C1[0] = C1[0] - SUM*TAU; // Right 2 ==> C2 C3 SUM = C2[0] + V*C3[0]; C2[0] = C2[0] - SUM*TAU; C3[0] = C3[0] - SUM*T2; }else if(uplo==PlasmaUpper){ // do the corner Right then Left (used for the upper case tridiag) // C(N-1, N-1) C(N-1,N) C1 C2 // C(N , N-1) C(N ,N) TEMP C3 // For Left : use TAU and conj(V). // For Right: use conj(TAU) and conj(V). // Right 1 ==> C1 C2 V = conj(V); TEMP = conj(C2[0]); // copy C2 here before modifying it. T2 = conj(TAU)*conj(V); SUM = C1[0] + V*C2[0]; C1[0] = C1[0] - SUM*conj(TAU); C2[0] = C2[0] - SUM*T2; // Right 2 ==> TEMP C3 SUM = TEMP + V*C3[0]; TEMP = TEMP - SUM*conj(TAU); C3[0] = C3[0] - SUM*T2; // Left 1 ==> C1 // TEMP. NB: no need to compute corner (2,1)=TEMP T2 = TAU*V; SUM = C1[0] + conj(V)*TEMP; C1[0] = C1[0] - SUM*TAU; // Left 2 ==> C2 // C3 SUM = C2[0] + conj(V)*C3[0]; C2[0] = C2[0] - SUM*TAU; C3[0] = C3[0] - SUM*T2; } return 0; } /////////////////////////////////////////////////////////// // DLARFX en C /////////////////////////////////////////////////////////// static void DLARFX_C(char side, int N, parsec_complex64_t V, parsec_complex64_t TAU, parsec_complex64_t *C, int LDC) { parsec_complex64_t T2, SUM, TEMP; int J, pt; /* * Special code for 2 x 2 Householder */ T2 = TAU*V; if(side=='L'){ for (J = 0; J < N ; J++){ pt = LDC*J; SUM = C[pt] + V*C[pt+1]; C[pt] = C[pt] - SUM*TAU; C[pt+1] = C[pt+1] - SUM*T2; } }else if(side=='R'){ for (J = 0; J < N ; J++){ pt = J+LDC; SUM = C[J] + V*C[pt]; C[J] = C[J] - SUM*TAU; C[pt] = C[pt] - SUM*T2; } }else if(side=='B'){ TEMP = C[ LDC * (N-2) +1]; for (J = 0; J < N-1 ; J++){ pt = LDC*J; SUM = C[pt] + V*C[pt+1]; C[pt] = C[pt] - SUM*TAU; C[pt+1] = C[pt+1] - SUM*T2; } // L and R for the 2x2 corner // C(1, N-1) C(1,N) C(1, N-1) TEMP // C(2, N-1) C(2,N) C(2, N-1) C(2,N) // Left 1 ==> C(1,N-1) C(2,N-1) deja fait dans la boucle //pt = LDC * (N-2); //TEMP = C[pt+1]; //SUM = C[pt] + V*C[pt+1]; //C[pt] = C[pt] - SUM*TAU; //C[pt+1] = C[pt+1] - SUM*T2; // Left 2 ==> TEMP C(2,N) pt = LDC * (N-1) +1; SUM = TEMP + V*C[pt]; TEMP = TEMP - SUM*TAU; C[pt] = C[pt] - SUM*T2; // Right 1 ==> C(1,N-1) TEMP. NB: no need to compute corner (2,2) J = LDC * (N-2); SUM = C[J] + V*TEMP; C[J] = C[J] - SUM*TAU; // Right 2 ==> C(2,N-1) C(2,N) J = LDC * (N-2) + 1; pt = LDC * (N-1) + 1; SUM = C[J] + V*C[pt]; C[J] = C[J] - SUM*TAU; C[pt] = C[pt] - SUM*T2; } } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// #define A1(m,n) &(A1[((m)-(n)) + LDA1*(n)]) #define A2(m,n) &(A2[((m)-(n)) + LDA2*((n)-NB)]) #define V1(m) &(V1[m-st]) #define TAU1(m) &(TAU1[m-st]) #define V2(m) &(V2[m-st]) #define TAU2(m) &(TAU2[m-st]) /////////////////////////////////////////////////////////// // TYPE 1-BAND Householder /////////////////////////////////////////////////////////// static void CORE_zhbtelr(int N, int NB, parsec_complex64_t *A1, int LDA1, parsec_complex64_t *A2, int LDA2, parsec_complex64_t *V1, parsec_complex64_t *TAU1, int st, int ed) { int J1, J2, KDM1, LDX; int len, len1, len2, t1ed, t2st; int i, IONE, ITWO; IONE=1; ITWO=2; (void)N; KDM1 = NB-1; LDX = LDA2-1; /* ********************************************************************************************** * Annihiliate, then LEFT: * ***********************************************************************************************/ for (i = ed; i >= st+1 ; i--){ /* generate Householder to annihilate a(i+k-1,i) within the band */ *V1(i) = *A1(i, (st-1)); *A1(i, (st-1)) = 0.0; DLARFG( &ITWO, A1((i-1),(st-1)), V1(i), &IONE, TAU1(i) ); J1 = st; J2 = i-2; t1ed = min(J2,KDM1); t2st = max(J1, NB); len1 = t1ed - J1 +1; len2 = J2 - t2st +1; // printf("Type 1L st %d ed %d i %d J1 %d J2 %d t1ed %d t2st %d len1 %d len2 %d \n", st, ed, i, J1,J2,t1ed,t2st,len1,len2); /* apply reflector from the left (horizontal row) and from the right for only the diagonal 2x2.*/ if(len2>=0){ /* part of the left(if len2>0) and the corner are on tile T2 */ if(len2>0) CORE_zlarfx2(PlasmaLeft, len2 , *V1(i), conj(*TAU1(i)), A2((i-1), t2st), LDX, A2(i, t2st), LDX); CORE_zlarfx2c(PlasmaLower, *V1(i), *TAU1(i), A2(i-1,i-1), A2(i,i-1), A2(i,i)); if(len1>0) CORE_zlarfx2(PlasmaLeft, len1 , *V1(i), conj(*TAU1(i)), A1(i-1, J1), LDX, A1(i, J1), LDX); }else if(len2==-1){ /* the left is on tile T1, and only A(i,i) of the corner is on tile T2 */ CORE_zlarfx2c(PlasmaLower, *V1(i), *TAU1(i), A1(i-1,i-1), A1(i,i-1), A2(i,i)); if(len1>0) CORE_zlarfx2(PlasmaLeft, len1 , *V1(i), conj(*TAU1(i)), A1(i-1, J1), LDX, A1(i, J1), LDX); }else{ /* the left and the corner are on tile T1, nothing on tile T2 */ CORE_zlarfx2c(PlasmaLower, *V1(i), *TAU1(i), A1(i-1,i-1), A1(i,i-1), A1(i,i)) ; if(len1>0) CORE_zlarfx2(PlasmaLeft, len1 , *V1(i), conj(*TAU1(i)), A1((i-1), J1), LDX, A1(i, J1), LDX); } } /* ********************************************************************************************** * APPLY RIGHT ON THE REMAINING ELEMENT OF KERNEL 1 * ***********************************************************************************************/ for (i = ed; i >= st+1 ; i--){ J1 = i+1; J2 = ed; len = J2-J1+1; if(len>0){ if(i>NB) /* both column (i-1) and i are on tile T2 */ CORE_zlarfx2(PlasmaRight, len, *V1(i), *TAU1(i), A2(J1, i-1), LDX, A2(J1, i), LDX); else if(i==NB) /* column (i-1) is on tile T1 while column i is on tile T2 */ CORE_zlarfx2(PlasmaRight, len, *V1(i), *TAU1(i), A1(J1, i-1), LDX, A2(J1, i), LDX); else /* both column (i-1) and i are on tile T1 */ CORE_zlarfx2(PlasmaRight, len, *V1(i), *TAU1(i), A1(J1, i-1), LDX, A1(J1, i), LDX); } } } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // TYPE 2-BAND Householder /////////////////////////////////////////////////////////// static void CORE_zhbtrce(int N, int NB, parsec_complex64_t *A1, int LDA1, parsec_complex64_t *A2, int LDA2, parsec_complex64_t *V1, parsec_complex64_t *TAU1, parsec_complex64_t *V2, parsec_complex64_t *TAU2, int st, int ed, int edglob) { int J1, J2, J3, KDM1, LDX, pt; int len, len1, len2, t1ed, t2st, iglob; int i, IONE, ITWO; parsec_complex64_t V,T,SUM; IONE=1; ITWO=2; iglob = edglob+1; LDX = LDA1-1; KDM1 = NB-1; /* ********************************************************************************************** * Right: * ***********************************************************************************************/ for (i = ed; i >= st+1 ; i--){ /* apply Householder from the right. and create newnnz outside the band if J3 < N */ iglob = iglob -1; J1 = ed+1; if((iglob+NB)>= N){ J2 = i +(N-iglob-1); J3 = J2; }else{ J2 = i + KDM1; J3 = J2+1; } len = J2-J1+1; /* printf("Type 2R st %d ed %d i %d J1 %d J2 %d len %d iglob %d \n",st,ed,i,J1,J2,len,iglob);*/ if(len>0){ if(i>NB){ /* both column (i-1) and i are on tile T2 */ CORE_zlarfx2(PlasmaRight, len, *V1(i), *TAU1(i), A2(J1, i-1), LDX, A2(J1, i), LDX); /* if nonzero element need to be created outside the band (if index < N) then create and eliminate it. */ if(J3>J2){ /* new nnz at TEMP=V2(i) */ V = *V1(i); T = *TAU1(i) * conj(V); SUM = V * (*A2(J3, i)); *V2(i) = -SUM * (*TAU1(i)); *A2(J3, i) = *A2(J3, i) - SUM * T; /* generate Householder to annihilate a(j+kd,j-1) within the band */ DLARFG( &ITWO, A2(J2,i-1), V2(i), &IONE, TAU2(i) ); } }else if(i==NB){ /* column (i-1) is on tile T1 while column i is on tile T2 */ CORE_zlarfx2(PlasmaRight, len, *V1(i), *TAU1(i), A1(J1, i-1), LDX, A2(J1, i), LDX); /* if nonzero element need to be created outside the band (if index < N) then create and eliminate it. */ if(J3>J2){ /* new nnz at TEMP=V2(i) */ V = *V1(i); T = *TAU1(i) * conj(V); SUM = V * (*A2(J3, i)); *V2(i) = -SUM * (*TAU1(i)); *A2(J3, i) = *A2(J3, i) - SUM * T; /* generate Householder to annihilate a(j+kd,j-1) within the band */ DLARFG( &ITWO, A1(J2, i-1), V2(i), &IONE, TAU2(i) ); } }else{ /* both column (i-1) and i are on tile T1 */ CORE_zlarfx2(PlasmaRight, len, *V1(i), *TAU1(i), A1(J1, i-1), LDX, A1(J1, i), LDX); /* if nonzero element need to be created outside the band (if index < N) then create and eliminate it. */ if(J3>J2){ /* new nnz at TEMP=V2(i) */ V = *V1(i); T = *TAU1(i) * conj(V); SUM = V * (*A1(J3, i)); *V2(i) = -SUM * (*TAU1(i)); *A1(J3, i) = *A1(J3, i) - SUM * T; /* generate Householder to annihilate a(j+kd,j-1) within the band */ DLARFG( &ITWO, A1(J2, i-1), V2(i), &IONE, TAU2(i) ); } } } } // if(id==1) return; /* ********************************************************************************************** * APPLY LEFT ON THE REMAINING ELEMENT OF KERNEL 1 * ***********************************************************************************************/ iglob = edglob+1; for (i = ed; i >= st+1 ; i--){ iglob = iglob -1; if((iglob+NB)< N){ /* mean that J3>J2 and so a nnz has been created and so a left is required. */ J1 = i; J2 = ed; t1ed = min(J2,KDM1); t2st = max(J1, NB); len1 = t1ed - J1 +1; len2 = J2 - t2st +1; pt = i + KDM1; /* pt correspond to the J2 position of the corresponding right done above */ //printf("Type 2L st %d ed %d i %d J1 %d J2 %d t1ed %d t2st %d len1 %d len2 %d \n", st, ed, i, J1,J2,t1ed,t2st,len1,len2); /* apply reflector from the left (horizontal row) and from the right for only the diagonal 2x2.*/ if(len2>0){ /* part of the left(if len2>0) and the corner are on tile T2 */ CORE_zlarfx2(PlasmaLeft, len2 , *V2(i), conj(*TAU2(i)), A2(pt, t2st), LDX, A2(pt+1, t2st), LDX); if(len1>0) CORE_zlarfx2(PlasmaLeft, len1 , *V2(i), conj(*TAU2(i)), A1(pt, J1), LDX, A1(pt+1, J1), LDX); }else if(len1>0){ /* the left and the corner are on tile T1, nothing on tile T2 */ CORE_zlarfx2(PlasmaLeft, len1 , *V2(i), conj(*TAU2(i)), A1(pt, J1), LDX, A1(pt+1, J1), LDX); } } } } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // TYPE 1-BAND Householder /////////////////////////////////////////////////////////// static void CORE_zhbtlrx(int N, int NB, parsec_complex64_t *A1, int LDA1, parsec_complex64_t *A2, int LDA2, parsec_complex64_t *V1, parsec_complex64_t *TAU1, int st, int ed) { int J1, J2, KDM1, LDX; int len, len1, len2, t1ed, t2st; int i; (void)N; KDM1 = NB-1; LDX = LDA2-1; /* ********************************************************************************************** * Annihiliate, then LEFT: * ***********************************************************************************************/ for (i = ed; i >= st+1 ; i--){ J1 = st; J2 = i-2; t1ed = min(J2,KDM1); t2st = max(J1, NB); len1 = t1ed - J1 +1; len2 = J2 - t2st +1; //printf("Type 3L st %d ed %d i %d J1 %d J2 %d t1ed %d t2st %d len1 %d len2 %d \n", st, ed, i, J1,J2,t1ed,t2st,len1,len2); /* apply reflector from the left (horizontal row) and from the right for only the diagonal 2x2.*/ if(len2>=0){ /* part of the left(if len2>0) and the corner are on tile T2 */ if(len2>0) CORE_zlarfx2(PlasmaLeft, len2 , *V1(i), conj(*TAU1(i)), A2((i-1), t2st), LDX, A2(i, t2st), LDX); CORE_zlarfx2c(PlasmaLower, *V1(i), *TAU1(i), A2(i-1,i-1), A2(i,i-1), A2(i,i)); if(len1>0) CORE_zlarfx2(PlasmaLeft, len1 , *V1(i), conj(*TAU1(i)), A1(i-1, J1), LDX, A1(i, J1), LDX); }else if(len2==-1){ /* the left is on tile T1, and only A(i,i) of the corner is on tile T2 */ CORE_zlarfx2c(PlasmaLower, *V1(i), *TAU1(i), A1(i-1,i-1), A1(i,i-1), A2(i,i)); if(len1>0) CORE_zlarfx2(PlasmaLeft, len1 , *V1(i), conj(*TAU1(i)), A1(i-1, J1), LDX, A1(i, J1), LDX); }else{ /* the left and the corner are on tile T1, nothing on tile T2 */ CORE_zlarfx2c(PlasmaLower, *V1(i), *TAU1(i), A1(i-1,i-1), A1(i,i-1), A1(i,i)) ; if(len1>0) CORE_zlarfx2(PlasmaLeft, len1 , *V1(i), conj(*TAU1(i)), A1((i-1), J1), LDX, A1(i, J1), LDX); } } /* ********************************************************************************************** * APPLY RIGHT ON THE REMAINING ELEMENT OF KERNEL 1 * ***********************************************************************************************/ for (i = ed; i >= st+1 ; i--){ J1 = i+1; J2 = ed; len = J2-J1+1; if(len>0){ if(i>NB) /* both column (i-1) and i are on tile T2 */ CORE_zlarfx2(PlasmaRight, len, *V1(i), *TAU1(i), A2(J1, i-1), LDX, A2(J1, i), LDX); else if(i==NB) /* column (i-1) is on tile T1 while column i is on tile T2 */ CORE_zlarfx2(PlasmaRight, len, *V1(i), *TAU1(i), A1(J1, i-1), LDX, A2(J1, i), LDX); else /* both column (i-1) and i are on tile T1 */ CORE_zlarfx2(PlasmaRight, len, *V1(i), *TAU1(i), A1(J1, i-1), LDX, A1(J1, i), LDX); } } } /////////////////////////////////////////////////////////// #undef A1 #undef A2 #undef V1 #undef TAU1 #undef V2 #undef TAU2 /////////////////////////////////////////////////////////// // TYPE 1-BAND Householder /////////////////////////////////////////////////////////// //// add -1 because of C #define A(m,n) &(A[((m)-(n)) + LDA*((n)-1)]) #define V(m) &(V[m-1]) #define TAU(m) &(TAU[m-1]) static void TRD_type1bHL(int N, int NB, parsec_complex64_t *A, int LDA, parsec_complex64_t *V, parsec_complex64_t *TAU, int st, int ed) { int J1, J2, len, LDX; int i, IONE, ITWO; IONE=1; ITWO=2; (void)NB; if(ed <= st){ printf("TRD_type 1bH: ERROR st and ed %d %d \n",st,ed); exit(-10); } LDX = LDA-1; for (i = ed; i >= st+1 ; i--){ // generate Householder to annihilate a(i+k-1,i) within the band *V(i) = *A(i, (st-1)); *A(i, (st-1)) = 0.0; DLARFG( &ITWO, A((i-1),(st-1)), V(i), &IONE, TAU(i) ); // apply reflector from the left (horizontal row) and from the right for only the diagonal 2x2. J1 = st; J2 = i; len = J2-J1+1; printf("voici J1 %d J2 %d len %d \n",J1,J2,len); DLARFX_C('B', len , *V(i), *TAU(i), A((i-1),J1 ), LDX); } for (i = ed; i >= st+1 ; i--){ len = min(ed,N)-i; if(len>0)DLARFX_C('R', len, *V(i), *TAU(i), A((i+1),(i-1)), LDX); } } #undef A #undef V #undef TAU /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // TYPE 2-BAND Householder /////////////////////////////////////////////////////////// //// add -1 because of C #define A(m,n) &(A[((m)-(n)) + LDA*((n)-1)]) #define V(m) &(V[m-1]) #define TAU(m) &(TAU[m-1]) static void TRD_type2bHL(int N, int NB, parsec_complex64_t *A, int LDA, parsec_complex64_t *V, parsec_complex64_t *TAU, int st, int ed) { int J1, J2, J3, KDM2, len, LDX; int i, IONE, ITWO; IONE=1; ITWO=2; if(ed <= st){ printf("TRD_type 2H: ERROR st and ed %d %d \n",st,ed); exit(-10);; } LDX = LDA -1; KDM2 = NB-2; for (i = ed; i >= st+1 ; i--){ // apply Householder from the right. and create newnnz outside the band if J3 < N J1 = ed+1; J2 = min((i+1+KDM2), N); J3 = min((J2+1), N); len = J2-J1+1; DLARFX_C('R', len, *V(i), *TAU(i), A(J1,(i-1)), LDX); // if nonzero element a(j+kd,j-1) has been created outside the band (if index < N) then eliminate it. len = J3-J2; // soit 1 soit 0 if(len>0){ // new nnz at TEMP=V(J3) *V(J3) = - *A(J3,(i)) * (*TAU(i)) * (*V(i)); *A(J3,(i)) = *A(J3,(i)) + *V(J3) * (*V(i)); //ATTENTION THIS replacement IS VALID IN FLOAT CASE NOT IN COMPLEX // generate Householder to annihilate a(j+kd,j-1) within the band DLARFG( &ITWO, A(J2,(i-1)), V(J3), &IONE, TAU(J3) ); } } //if(id==1) return; for (i = ed; i >= st+1 ; i--){ J2 = min((i+1+KDM2), N); J3 = min((J2+1), N); len = J3-J2; if(len>0){ len = min(ed,N)-i+1; DLARFX_C('L', len , *V(J3), *TAU(J3), A(J2, i), LDX); } } } #undef A #undef V #undef TAU /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // TYPE 3-BAND Householder /////////////////////////////////////////////////////////// //// add -1 because of C #define A(m,n) &(A[((m)-(n)) + LDA*((n)-1)]) #define V(m) &(V[m-1]) #define TAU(m) &(TAU[m-1]) static void TRD_type3bHL(int N, int NB, parsec_complex64_t *A, int LDA, parsec_complex64_t *V, parsec_complex64_t *TAU, int st, int ed) { int J1, J2, len, LDX; int i; (void)NB; if(ed <= st){ printf("TRD_type 3H: ERROR st and ed %d %d \n",st,ed); exit(-10); } LDX = LDA-1; for (i = ed; i >= st+1 ; i--){ // apply rotation from the left. faire le DROT horizontal J1 = st; J2 = i; len = J2-J1+1; //len = NB+1; DLARFX_C('B', len , *V(i), *TAU(i), A((i-1),J1 ), LDX); } for (i = ed; i >= st+1 ; i--){ len = min(ed,N)-i; if(len>0)DLARFX_C('R', len, *V(i), *TAU(i), A((i+1),(i-1)), LDX); } } #undef A #undef V #undef TAU /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // grouping sched wrapper call /////////////////////////////////////////////////////////// #if 0 int TRD_seqgralgtype(int N, int NB, parsec_complex64_t *A, int LDA, parsec_complex64_t *C, parsec_complex64_t *S, int i, int j, int m, int grsiz, int BAND) { int k,shift=3; int myid,colpt,stind,edind,blklastind,stepercol; (void) BAND; k = shift/grsiz; stepercol = k*grsiz == shift ? k:k+1; for (k = 1; k <=grsiz; k++){ myid = (i-j)*(stepercol*grsiz) +(m-1)*grsiz + k; if(myid%2 ==0){ colpt = (myid/2)*NB+1+j-1; stind = colpt-NB+1; edind = min(colpt,N); blklastind = colpt; if(stind>=edind){ printf("TRD_seqalg ERROR---------> st>=ed %d %d \n\n",stind, edind); return -10; } }else{ colpt = ((myid+1)/2)*NB + 1 +j -1 ; stind = colpt-NB+1; edind = min(colpt,N); if( (stind>=edind-1) && (edind==N) ) blklastind=N; else blklastind=0; if(stind>=edind){ printf("TRD_seqalg ERROR---------> st>=ed %d %d \n\n",stind, edind); return -10; } } if(myid == 1) TRD_type1bHL(N, NB, A, LDA, C, S, stind, edind); else if(myid%2 == 0) TRD_type2bHL(N, NB, A, LDA, C, S, stind, edind); else if(myid%2 == 1) TRD_type3bHL(N, NB, A, LDA, C, S, stind, edind); else{ printf("COUCOU ERROR myid/2 %d\n",myid); return -10; } if(blklastind >= (N-1)) break; //if(myid==2)return; } // END for k=1:grsiz return 0; } /////////////////////////////////////////////////////////// #endif /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // REDUCTION BAND TO TRIDIAG /////////////////////////////////////////////////////////////////////////////////////////////////////////////// #if 0 static void band_to_trd_v8seq(int N, int NB, parsec_complex64_t *A, int LDA, int INgrsiz, int INthgrsiz) { int myid, grsiz, shift, stt, st, ed, stind, edind, BAND; int blklastind, colpt; int stepercol,mylastid; parsec_complex64_t *C, *S; int i,j,m; int thgrsiz, thgrnb, thgrid, thed; int INFO; INFO=-1; BAND = 0; C = malloc(N*sizeof(parsec_complex64_t)); S = malloc(N*sizeof(parsec_complex64_t)); memset(C,0,N*sizeof(parsec_complex64_t)); memset(S,0,N*sizeof(parsec_complex64_t)); grsiz = INgrsiz; thgrsiz = INthgrsiz; shift = 3; if(grsiz==0)grsiz = 6; if(thgrsiz==0)thgrsiz = N; if(LDA != (NB+1)) { printf(" ERROR LDA not equal NB+1 and this code is special for LDA=NB+1. LDA=%d NB+1=%d \n",LDA,NB+1); return; } printf(" Version -8seq- grsiz %4d thgrsiz %4d N %5d NB %5d BAND %5d\n",grsiz,thgrsiz, N, NB, BAND); i = shift/grsiz; stepercol = i*grsiz == shift ? i:i+1; i = (N-2)/thgrsiz; thgrnb = i*thgrsiz == (N-2) ? i:i+1; for (thgrid = 1; thgrid<=thgrnb; thgrid++){ stt = (thgrid-1)*thgrsiz+1; thed = min( (stt + thgrsiz -1), (N-2)); for (i = stt; i <= N-2; i++){ ed=min(i,thed); if(stt>ed)break; for (m = 1; m <=stepercol; m++){ st=stt; for (j = st; j <=ed; j++){ myid = (i-j)*(stepercol*grsiz) +(m-1)*grsiz + 1; mylastid = myid+grsiz-1; INFO = TRD_seqgralgtype(N, NB, A, LDA, C, S, i, j, m, grsiz, BAND); if(INFO!=0){ printf("ERROR band_to_trd_v8seq INFO=%d\n",INFO); return; } if(mylastid%2 ==0){ blklastind = (mylastid/2)*NB+1+j-1; }else{ colpt = ((mylastid+1)/2)*NB + 1 +j -1 ; stind = colpt-NB+1; edind = min(colpt,N); if( (stind>=edind-1) && (edind==N) ) blklastind=N; else blklastind=0; } if(blklastind >= (N-1)) stt=stt+1; } // END for j=st:ed } // END for m=1:stepercol } // END for i=1:N-2 } // END for thgrid=1:thgrnb } // END FUNCTION /////////////////////////////////////////////////////////////////////////////////////////////////////////////// #endif /////////////////////////////////////////////////////////////////////////////////////////////////////////////// int blgchase_ztrdv1(int NT, int N, int NB, parsec_complex64_t *A, parsec_complex64_t *V, parsec_complex64_t *TAU, int sweep, int id, int blktile) { int /*edloc,*/ stloc, st, ed, KDM1, LDA; (void)NT; KDM1 = NB-1; LDA = NB+1; /* generate the indiceslocal and global*/ stloc = (sweep+1)%NB; if(stloc==0) stloc=NB; /*if(id==NT-1) edloc = NB-1; else edloc = stloc + KDM1; */ st = min(id*NB+stloc, N-1); ed = min(st+KDM1, N-1); /* * i = (N-1)%ed; * edloc = i%NB+NB; */ /* quick return in case of last tile */ if(st==ed) return 0; /* because the kernel have been writted for fortran, add 1 */ st = st +1; ed = ed +1; /* code for all tiles */ if(id==blktile){ TRD_type1bHL(N, NB, A, LDA, V, TAU, st, ed); TRD_type2bHL(N, NB, A, LDA, V, TAU, st, ed); }else{ TRD_type3bHL(N, NB, A, LDA, V, TAU, st, ed); //if(id==6) return; TRD_type2bHL(N, NB, A, LDA, V, TAU, st, ed); } return 0; } #if 0 /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void band_to_trd_vmpi1(int N, int NB, parsec_complex64_t *A, int LDA) { int NT; parsec_complex64_t *V, *TAU; int blktile, S, id, sweep; V = malloc(N*sizeof(parsec_complex64_t)); TAU = malloc(N*sizeof(parsec_complex64_t)); memset(V,0,N*sizeof(parsec_complex64_t)); memset(TAU,0,N*sizeof(parsec_complex64_t)); NT = N/NB; if(NT*NB != N){ printf("ERROR NT*NB not equal N \n"); return; } //printf("voici NT, N NB %d %d %d\n",NT,N,NB); for (blktile = 0; blktile<NT; blktile++){ for (S = 0; S<NB; S++){ sweep = blktile*NB + S ; for (id = blktile; id<NT; id++){ blgchase_ztrdv1 (NT, N, NB, A, V, TAU, sweep , id, blktile); } } } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// #endif /////////////////////////////////////////////////////////////////////////////////////////////////////////////// int blgchase_ztrdv2(int NT, int N, int NB, parsec_complex64_t *A1, parsec_complex64_t *A2, parsec_complex64_t *V1, parsec_complex64_t *TAU1, parsec_complex64_t *V2, parsec_complex64_t *TAU2, int sweep, int id, int blktile) { int edloc, stloc, st, ed, KDM1, LDA; KDM1 = NB-1; LDA = NB+1; /* generate the indiceslocal and global*/ stloc = (sweep+1)%NB; if(stloc==0) stloc=NB; if(id==NT-1) edloc = NB-1; else edloc = stloc + KDM1; st = min(id*NB+stloc, N-1); ed = min(st+KDM1, N-1); /* * i = (N-1)%ed; * edloc = i%NB+NB; */ /* quick return in case of last tile */ if(st==ed) return 0; /* code for all tiles */ if(id==blktile){ CORE_zhbtelr(N, NB, A1, LDA, A2, LDA, V1, TAU1, stloc, edloc); CORE_zhbtrce(N, NB, A1, LDA, A2, LDA, V1, TAU1, V2, TAU2, stloc, edloc, ed); }else{ CORE_zhbtlrx(N, NB, A1, LDA, A2, LDA, V1, TAU1, stloc, edloc); CORE_zhbtrce(N, NB, A1, LDA, A2, LDA, V1, TAU1, V2, TAU2, stloc, edloc, ed); } return 0; } #if 0 /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void band_to_trd_vmpi2(int N, int NB, parsec_complex64_t *A, int LDA) { int NT; parsec_complex64_t *V, *TAU; int blktile, S, id, sweep; V = malloc(N*sizeof(parsec_complex64_t)); TAU = malloc(N*sizeof(parsec_complex64_t)); memset(V,0,N*sizeof(parsec_complex64_t)); memset(TAU,0,N*sizeof(parsec_complex64_t)); NT = N/NB; if(NT*NB != N){ printf("ERROR NT*NB not equal N \n"); return; } //printf("voici NT, N NB %d %d %d\n",NT,N,NB); for (blktile = 0; blktile<NT; blktile++){ for (S = 0; S<NB; S++){ sweep = blktile*NB + S ; for (id = blktile; id<NT; id++){ //printf("voici blktile %d S %d id %d sweep %d \n",blktile, S, id, sweep); blgchase_ztrdv2 (NT, N, NB, A+(id*NB*LDA), A+((id+1)*NB*LDA), V+(id*NB), TAU+(id*NB), V+((id+1)*NB), TAU+((id+1)*NB), sweep, id, blktile); } //if(sweep==0) return; } } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// #endif
{ "alphanum_fraction": 0.4496422675, "avg_line_length": 35.5540679712, "ext": "c", "hexsha": "8d54f6307f2d8a35c90f00f37127aefb294040bc", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "NLAFET/ABFT", "max_forks_repo_path": "dplasma/cores/core_ztrdv.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "NLAFET/ABFT", "max_issues_repo_path": "dplasma/cores/core_ztrdv.c", "max_line_length": 237, "max_stars_count": 1, "max_stars_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "NLAFET/ABFT", "max_stars_repo_path": "dplasma/cores/core_ztrdv.c", "max_stars_repo_stars_event_max_datetime": "2019-08-13T10:13:00.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-13T10:13:00.000Z", "num_tokens": 11798, "size": 34523 }
/* ** Various utilities for LISA algorithm ** ** G.Lohmann, Jan 2017 */ #include <viaio/VImage.h> #include <viaio/Vlib.h> #include <viaio/mu.h> #include <viaio/option.h> #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_histogram.h> #define SQR(x) ((x)*(x)) #define ABS(x) ((x) > 0 ? (x) : -(x)) extern float kth_smallest(float *a, size_t n, size_t k); #define Median(a,n) kth_smallest(a,n,(((n)&1)?((n)/2):(((n)/2)-1))) /* update histogram */ void HistoUpdate(VImage src1,gsl_histogram *hist) { float u,tiny = 1.0e-6; size_t i; float xmin = gsl_histogram_min (hist); float xmax = gsl_histogram_max (hist); float *pp1 = VImageData(src1); for (i=0; i<VImageNPixels(src1); i++) { u = *pp1++; if (ABS(u) < tiny) continue; if (u > xmax) u = xmax-tiny; if (u < xmin) u = xmin+tiny; gsl_histogram_increment (hist,u); } } /* In moderately skewed or asymmetrical distribution (Pearson) */ float VGetMode(VImage src) { size_t i,n=0; float u,tiny=1.0e-8; VFloat *pp = VImageData(src); for (i=0; i<VImageNPixels(src); i++) { u = (*pp++); if (fabs(u) > tiny) n++; } float *data = (float *) VCalloc(n,sizeof(float)); double sum=0,nx=0; n=0; pp = VImageData(src); for (i=0; i<VImageNPixels(src); i++) { u = (*pp++); if (fabs(u) > tiny) { data[n] = u; sum += u; n++; } } nx = (double)n; float median = Median(data,n); float mean = (float)(sum/nx); float mode = 3.0*median - 2.0*mean; /* fprintf(stderr," mean: %f, median: %f, mode: %f\n",mean,median,mode); */ VFree(data); return mode; } /* scale z-values */ void VZScale(VImage src,float mode,float stddev) { size_t i=0; float u=0,tiny=1.0e-8; VFloat *pp=VImageData(src); for (i=0; i<VImageNPixels(src); i++) { u = (*pp); if (fabs(u) > tiny) (*pp) = (u-mode)/stddev; pp++; } } /* get max z-value */ float VZMax(VImage src) { size_t i=0; float u=0,umax=0; VFloat *pp=VImageData(src); for (i=0; i<VImageNPixels(src); i++) { u = (*pp++); if (u > umax) umax = u; } return umax; } /* get image variance */ double VImageVar(VImage src) { size_t i=0; double u=0,s1=0,s2=0,nx=0,tiny=1.0e-8; VFloat *pp=VImageData(src); for (i=0; i<VImageNPixels(src); i++) { u = (double)(*pp++); if (ABS(u) < tiny) continue; s1 += u; s2 += u*u; nx++; } if (nx < 3.0) VError(" number of nonzero voxels: %g\n",nx); double mean = s1/nx; double var = (s2 - nx * mean * mean) / (nx - 1.0); return var; } /* count nonzero voxels */ void VImageCount(VImage src) { float u=0; size_t i=0,npos=0; VFloat *pp=VImageData(src); for (i=0; i<VImageNPixels(src); i++) { u = (float)(*pp++); if (u > 0) npos++; } } /* check histogram range, image is normalized so [-10,10] should be okay */ void VGetHistRange(VImage src,double *hmin,double *hmax) { size_t i=0; double u=0,x=0,y=0; double zmin = -10.0; double zmax = 10.0; VFloat *pp=VImageData(src); size_t npix=0,npos=0,nneg=0; for (i=0; i<VImageNPixels(src); i++) { u = (*pp++); if (u < zmin) nneg++; if (u > zmax) npos++; if (fabs(u) > 0) npix++; } if (npix < 1) VError(" image has no non-zero pixels"); if (npos > 0 || nneg > 0) { x = (double)npos/(double)npix; y = (double)nneg/(double)npix; if (x > 0.01 || y > 0.01) { zmin = -20.0; zmax = 20.0; } } /* output */ *hmin = zmin; *hmax = zmax; } /* remove isolated voxels */ void VIsolatedVoxels(VImage src,float threshold) { int b,r,c,bb,rr,cc; float u=0; size_t i; VImage tmp = VCreateImage(VImageNBands(src),VImageNRows(src),VImageNColumns(src),VBitRepn); VFillImage(tmp,VAllBands,0); VFloat *pp=VImageData(src); VBit *pa=VImageData(tmp); for (i=0; i<VImageNPixels(src); i++) { u = (*pp++); if (u > threshold) *pa = 1; pa++; } for (b=1; b<VImageNBands(src)-1; b++) { for (r=1; r<VImageNRows(src)-1; r++) { for (c=1; c<VImageNColumns(src)-1; c++) { int n=0; for (bb=b-1; bb<=b+1; bb++) { for (rr=r-1; rr<=r+1; rr++) { for (cc=c-1; cc<=c+1; cc++) { if (VPixel(tmp,bb,rr,cc,VBit) > 0) n++; if (n >= 2) goto skip; } } } if (n < 2) VPixel(src,b,r,c,VFloat) = 0; skip: ; } } } VDestroyImage(tmp); }
{ "alphanum_fraction": 0.5610312571, "avg_line_length": 20.198156682, "ext": "c", "hexsha": "eeaa7beeecf34feed9386aaaf7a00d81287c1c9d", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_path": "src/stats/utils/Hotspot.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_path": "src/stats/utils/Hotspot.c", "max_line_length": 93, "max_stars_count": 17, "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_path": "src/stats/utils/Hotspot.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "num_tokens": 1635, "size": 4383 }
#include <gsl/gsl_sf_airy.h> #include <gsl/gsl_errno.h> /* function names generated by removing "gsl_sf" from the beginning of the name. Thus gsl_sf_airy_Ai goes to airy_Ai. */ static int sf_mode[] = { GSL_PREC_DOUBLE, GSL_PREC_SINGLE, GSL_PREC_APPROX } ; void airy_Ai_e(double *x, int *len, int *mode, double *val, double *err, int *status) { int i; gsl_sf_result result; gsl_set_error_handler_off(); for(i = 0; i< *len ; i++){ status[i] = gsl_sf_airy_Ai_e(x[i], sf_mode[*mode], &result) ; val[i] = result.val; err[i] = result.err; } } void airy_Bi_e(double *x, int *len, int *mode, double *val, double *err, int *status) { int i; gsl_sf_result result; for(i = 0; i< *len ; i++){ status[i] = gsl_sf_airy_Bi_e(x[i], sf_mode[*mode], &result) ; val[i] = result.val; err[i] = result.err; } } void airy_Ai_scaled_e(double *x, int *len, int *mode, double *val, double *err, int *status) { int i; gsl_sf_result result; for(i = 0; i< *len ; i++){ status[i] = gsl_sf_airy_Ai_scaled_e(x[i], sf_mode[*mode], &result) ; val[i] = result.val; err[i] = result.err; } } void airy_Bi_scaled_e(double *x, int *len, int *mode, double *val, double *err, int *status) { int i; gsl_sf_result result; for(i = 0; i< *len ; i++){ status[i] = gsl_sf_airy_Bi_scaled_e(x[i], sf_mode[*mode], &result) ; val[i] = result.val; err[i] = result.err; } } void airy_Ai_deriv_e(double *x, int *len, int *mode, double *val, double *err, int *status) { int i; gsl_sf_result result; for(i = 0; i< *len ; i++){ status[i] = gsl_sf_airy_Ai_deriv_e(x[i], sf_mode[*mode], &result) ; val[i] = result.val; err[i] = result.err; } } void airy_Bi_deriv_e(double *x, int *len, int *mode, double *val, double *err, int *status) { int i; gsl_sf_result result; for(i = 0; i< *len ; i++){ status[i] = gsl_sf_airy_Bi_deriv_e(x[i], sf_mode[*mode], &result) ; val[i] = result.val; err[i] = result.err; } } void airy_Ai_deriv_scaled_e(double *x, int *len, int *mode, double *val, double *err, int *status) { int i; gsl_sf_result result; for(i = 0; i< *len ; i++){ status[i] = gsl_sf_airy_Ai_deriv_scaled_e(x[i], sf_mode[*mode], &result) ; val[i] = result.val; err[i] = result.err; } } void airy_Bi_deriv_scaled_e(double *x, int *len, int *mode, double *val, double *err, int *status) { int i; gsl_sf_result result; for(i = 0; i< *len ; i++){ status[i] = gsl_sf_airy_Bi_deriv_scaled_e(x[i], sf_mode[*mode], &result) ; val[i] = result.val; err[i] = result.err; } } void airy_zero_Ai_e(int *n, int *len, double *val, double *err, int *status) { int i; gsl_sf_result result; for(i = 0; i< *len ; i++){ if(n[i]>0){ status[i] = gsl_sf_airy_zero_Ai_e(n[i], &result) ; } else { result.val=0.0; result.err=GSL_EDOM; } val[i] = result.val; err[i] = result.err; } } void airy_zero_Bi_e(int *n, int *len, double *val, double *err, int *status) { int i; gsl_sf_result result; for(i = 0; i< *len ; i++){ if(n[i]>0){ status[i] = gsl_sf_airy_zero_Bi_e(n[i], &result) ; } else { result.val=0.0; result.err=GSL_EDOM; } val[i] = result.val; err[i] = result.err; } } void airy_zero_Ai_deriv_e(int *n, int *len, double *val, double *err, int *status) { int i; gsl_sf_result result; for(i = 0; i< *len ; i++){ if(n[i]>0){ status[i] = gsl_sf_airy_zero_Ai_deriv_e(n[i], &result) ; } else { result.val=0.0; result.err=GSL_EDOM; } val[i] = result.val; err[i] = result.err; } } void airy_zero_Bi_deriv_e(int *n, int *len, double *val, double *err, int *status) { int i; gsl_sf_result result; for(i = 0; i< *len ; i++){ if(n[i]>0){ status[i] = gsl_sf_airy_zero_Bi_deriv_e(n[i], &result) ; } else { result.val=0.0; result.err=GSL_EDOM; } val[i] = result.val; err[i] = result.err; } }
{ "alphanum_fraction": 0.6221642764, "avg_line_length": 22.6923076923, "ext": "c", "hexsha": "b154d1fae4d04861ece167361ddc6c262843b7ef", "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": "d646a22b258d92199845446d914c1d3866e7b43f", "max_forks_repo_licenses": [ "CC0-1.0" ], "max_forks_repo_name": "kbroman/fluctuationDomains", "max_forks_repo_path": "src/airy.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "d646a22b258d92199845446d914c1d3866e7b43f", "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": "kbroman/fluctuationDomains", "max_issues_repo_path": "src/airy.c", "max_line_length": 98, "max_stars_count": null, "max_stars_repo_head_hexsha": "d646a22b258d92199845446d914c1d3866e7b43f", "max_stars_repo_licenses": [ "CC0-1.0" ], "max_stars_repo_name": "kbroman/fluctuationDomains", "max_stars_repo_path": "src/airy.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1359, "size": 3835 }
#ifndef __calcAinvb__ #define __calcAinvb__ #include <gsl/gsl_linalg.h> #include <gsl/gsl_matrix_double.h> //#include <gsl/gsl_multimin.h> #include <gsl/gsl_multiroots.h> //#include "my_misc.c" //#define GSL 1 #define GSL 1 int GSLtag; void least_gsl_error_handler( const char * reason, const char * file, int line, int gsl_errno) { // printf("%s:%d: %s (gsl_error: %s)\n", // file, line, reason, gsl_strerror(gsl_errno)); printf("%s:%d: %s (gsl_error %d)\n", file, line, reason,gsl_errno); GSLtag=1; } double VarY; void calc_Ainvb(double *M, double *A_data, double *b_data, int nx, int ndata,int nxmarume) { /* b= A M --> M= Ainv b b in R^{ndata x 1} A in R^{ndata x nx} (ndata>nx) M in R^{nx x 1} */ int i; gsl_vector *S; gsl_vector *work; gsl_vector *x; gsl_vector *b; gsl_matrix *V; gsl_matrix *A; if(ndata<=0){ M[0]=1; for(i=1;i<nx;i++) M[i]=1./nx; } else{ A =gsl_matrix_alloc(ndata,nx); b =gsl_vector_alloc(ndata);b->data=b_data; A->data=A_data; // for(i=0;i<ndata;i++){printf("%e %e %d #bi,Ai\n",A->data[i],b->data[i],i); } V = gsl_matrix_alloc (nx,nx); S = gsl_vector_alloc (nx); work = gsl_vector_alloc(nx); x = gsl_vector_alloc(nx); gsl_set_error_handler( &least_gsl_error_handler );GSLtag=0; #if GSL == 1 gsl_linalg_SV_decomp_jacobi (A, V, S); //higer accuracy than Golub-Reinsh #elif GSL == 2 gsl_linalg_SV_decomp (A, V, S, work); //Golub-Reinsh #elif GSL == 3 {//faster gsl_matrix *X; X = gsl_matrix_alloc (nx,nx); gsl_linalg_SV_decomp_mod (A, X, V, S, work); gsl_matrix_free(X); } #endif // for(i=nxmarume;i<nx;i++){ fprintf(stdout,"Lambda"); for(i=0;i<nx;i++){ // if(nx>40) break; // fprintf(stdout,"S->data[%d]=%e;",i,S->data[i]); fprintf(stdout,"(%d)%e",i,S->data[i]); } fprintf(stdout,"\n"); VarY=0; if(GSLtag==1){ fprintf(stderr,"\nEigenValue=");for(i=0;i<nx;i++) fprintf(stderr,"%e ",S->data[i]); fprintf(stderr,"\n"); for(i=0;i<nx;i++) M[i]=1./nx; } else{ if(nxmarume>=0){//Principal Component Analysis for(i=nxmarume;i<nx;i++) S->data[i]=0; for(i=0;i<nxmarume;i++) VarY+=S->data[i]; gsl_linalg_SV_solve(A,V,S,b,x); for(i=0;i<nx;i++) M[i]=gsl_vector_get(x,i); // {//check // double err=0,yhat; // int j; // for(i=0;i<ndata;i++){ // if(i>10) break; // yhat=b_data[i]; // for(j=0;j<nx;j++){ // yhat-= M[j]*A_data[i*nx+j]; // } // err+=square(yhat); // fprintf(stderr,"err=%e=%e/%d. yhat=%e=(%e",err/(i+1.),err,i,yhat,b_data[i]); // for(j=0;j<nx;j++) fprintf(stderr,"-(%e)*(%e)",M[j],A_data[i*nx+j]); // fprintf(stderr,")^2\n"); // } // } } else{//Minor Component Analysis int ii=0; int im=-nxmarume; for(i=nx-1;i>=0;i--){ if(S->data[i]>1e-20){ ii++; VarY+=S->data[i]; if(ii>=im) break; } } int j; double M0=-V->data[i]; for(j=1;j<nx;j++){ M[j-1]=V->data[j*nx+i]/M0; } // double M0=-V->data[i*nx]; // for(j=1;j<nx;j++){ // M[j-1]=V->data[i*nx+j]/M0; // } } } gsl_vector_free(S); gsl_vector_free(work); gsl_vector_free(x); gsl_matrix_free(V); gsl_matrix_free(A); gsl_vector_free(b); } } void calc_AtinvbMCA(double *M, double *At_data, double *b_data, int nx, int ndata,int nxmarume) { /* b= A M --> M= Ainv b b in R^{ndata x 1} A=At in R^{ndata x nx} M in R^{nx x 1} */ int nx1=nx+1,i,j,jnx1; gsl_matrix *A =gsl_matrix_alloc(ndata,nx1); for(j=0;j<ndata;j++){ jnx1=j*nx1; A->data[jnx1]=b_data[j]; for(i=0;i<nx;i++){ A->data[jnx1+i+1]=At_data[i*ndata+j]; } } calc_Ainvb(M, (double *)(A->data), b_data, nx1, ndata, -nxmarume); gsl_matrix_free(A); } void calc_Atinvb(double *M, double *At_data, double *b_data, int nx, int ndata,int nxmarume) { /* b= A M --> M= Ainv b b in R^{ndata x 1} A=At in R^{ndata x nx} M in R^{nx x 1} */ gsl_matrix *At =gsl_matrix_alloc(nx,ndata); gsl_matrix *A =gsl_matrix_alloc(ndata,nx); At->data=At_data; gsl_matrix_transpose_memcpy(A, At); calc_Ainvb(M, (double *)(A->data), b_data, nx, ndata, nxmarume); gsl_matrix_free(A); gsl_matrix_free(At); } #endif // __calcAinvb__
{ "alphanum_fraction": 0.5660073597, "avg_line_length": 25.4269005848, "ext": "c", "hexsha": "e718351a52a0930fcfc639379ea37e0ccc3760fa", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-12-01T00:54:18.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-01T00:54:18.000Z", "max_forks_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_forks_repo_licenses": [ "CECILL-B" ], "max_forks_repo_name": "Kurogi-Lab/CAN2", "max_forks_repo_path": "0522/tsp/calcAinvb.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CECILL-B" ], "max_issues_repo_name": "Kurogi-Lab/CAN2", "max_issues_repo_path": "0522/tsp/calcAinvb.c", "max_line_length": 111, "max_stars_count": null, "max_stars_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_stars_repo_licenses": [ "CECILL-B" ], "max_stars_repo_name": "Kurogi-Lab/CAN2", "max_stars_repo_path": "0522/tsp/calcAinvb.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1604, "size": 4348 }
/** @file */ #ifndef __CCL_F3D_H_INCLUDED__ #define __CCL_F3D_H_INCLUDED__ #include <gsl/gsl_spline.h> #include <gsl/gsl_interp2d.h> #include <gsl/gsl_spline2d.h> CCL_BEGIN_DECLS /** * Struct for accelerated linear interpolation. */ typedef struct { int ia_last; /**< Last index found */ double amin; /**< Minimum a-value within range */ double amax; /**< Maximum a-value within range */ int na; /**< Number of a-values held */ double *a_arr; /**< Array of a-values */ } ccl_a_finder; /** * Creates a new ccl_a_finder structure from an array * of scale factors. * @param na Number of elements held by a_arr * @param a_arr array of scale factors over which linear interpolation will be carried out. */ ccl_a_finder *ccl_a_finder_new(int na, double *a_arr); /** * ccl_a_finder destructor. */ void ccl_a_finder_free(ccl_a_finder *finda); /** * Find index corresponding to scale factor value a * such that finda->a_arr[index]<a<finda->a_arr[index+1]. * @param finda ccl_a_finder. * @param a scale factor value. */ int ccl_find_a_index(ccl_a_finder *finda, double a); /** * Struct containing a 3D trispectrum */ typedef struct { double lkmin,lkmax; /**< Edges in log(k)*/ int na; /**< Number of a values */ double *a_arr; /**< Array of a values at which this is sampled */ int is_product; /**< Is this factorizable as f(k1,a)*g(k2,a)? */ int extrap_order_lok; /**< Order of extrapolating polynomial in log(k) for low k (0, 1 or 2)*/ int extrap_order_hik; /**< Order of extrapolating polynomial in log(k) for high k (0, 1 or 2)*/ ccl_f2d_extrap_growth_t extrap_linear_growth; /**< Extrapolation type at high redshifts*/ int is_log; /**< Do I hold the values of log(f(k,a))?*/ double growth_factor_0; /**< Constant extrapolating growth factor*/ int growth_exponent; /**< Power to which growth should be exponentiated*/ ccl_f2d_t *fka_1; /**< If is_product=True, then this holds the first factor f(k,a) */ ccl_f2d_t *fka_2; /**< If is_product=True, then this holds the second factor g(k,a) */ gsl_spline2d **tkka; /**< Array of 2D (k1,k2) splines (one for each value of a). */ } ccl_f3d_t; /** * Create a ccl_f3d_t structure. * @param na number of elements in a_arr. * @param a_arr array of scale factor values at which the function is defined. The array should be ordered. * @param nk number of elements of lk_arr. * @param lk_arr array of logarithmic wavenumbers at which the function is defined (i.e. this array contains ln(k), NOT k). The array should be ordered. * @param tkka_arr array of size na * nk * nk containing the 3D function. The 3D ordering is such that fka_arr[ik1+nk*(ik2+nk*ia)] = f(k1=exp(lk_arr[ik1]),k2=exp(lk_arr[ik2],a=a_arr[ia]). * @param fka1_arr array of size nk * na containing the first factor f1 making up the total function if it's factorizable such that f(k1,k2,a) = f1(k1,a)*f2(k2,a). The 2D ordering of this array should be such that fka1_arr[ik+nk*ia] = f1(k=exp(lk_arr[ik]),a=a_arr[ia]). Only relevant if is_product is true. * @param fka2_arr same as fka1_arr for the second factor. * @param is_product if not 0, fka1_arr and fka2_arr will be used as 2-D arrays to construct a factorizable 3D function f(k1,k1,a) = f1(k1,a)*f2(k2,a). * @param extrap_order_lok Order of the polynomial that extrapolates on wavenumbers smaller than the minimum of lk_arr. Allowed values: 0 (constant) and 1 (linear extrapolation). Extrapolation happens in ln(k). * @param extrap_order_hik Order of the polynomial that extrapolates on wavenumbers larger than the maximum of lk_arr. Allowed values: 0 (constant) and 1 (linear extrapolation). Extrapolation happens in ln(k). * @param extrap_linear_growth: ccl_f2d_extrap_growth_t value defining how the function with scale factors below the interpolation range. Allowed values: ccl_f2d_cclgrowth (scale with the CCL linear growth factor), ccl_f2d_constantgrowth (scale by multiplying the function at the earliest available scale factor by a constant number, defined by `growth_factor_0`), ccl_f2d_no_extrapol (throw an error if the function is ever evaluated outside the interpolation range in a). Note that, above the interpolation range (i.e. for low redshifts), the function will be assumed constant. * @param is_tkka_log: if not zero, `tkka_arr` contains ln(f(k1,k2,a)) instead of f(k1,k2,a) (and likewise for fka1_arr and fka2_arr). * @param growth_factor_0: growth factor outside the range of scale factors held by a_arr. Irrelevant if extrap_linear_growth!=ccl_f2d_constantgrowth. * @param growth_exponent: power to which the extrapolating growth factor should be exponentiated when extrapolating (e.g. usually 4 for trispectra). * @param interp_type: 2D interpolation method in k1,k2 space. Currently only ccl_f2d_3 is implemented (bicubic interpolation). Note that linear interpolation is used between values of the scale factor. * @param status Status flag. 0 if there are no errors, nonzero otherwise. */ ccl_f3d_t *ccl_f3d_t_new(int na,double *a_arr, int nk,double *lk_arr, double *tkka_arr, double *fka1_arr, double *fka2_arr, int is_product, int extrap_order_lok, int extrap_order_hik, ccl_f2d_extrap_growth_t extrap_linear_growth, int is_tkka_log, double growth_factor_0, int growth_exponent, ccl_f2d_interp_t interp_type, int *status); /** * Evaluate 3D function of k1, k2 and a defined by ccl_f3d_t structure. * @param f3d ccl_f3d_t structure defining f(k1,k2,a). * @param lk1 Natural logarithm of the wavenumber. * @param lk2 Natural logarithm of the wavenumber. * @param a Scale factor. * @param finda Helper structure used to accelerate the scale factor interpolation. * @param cosmo ccl_cosmology structure, only needed if evaluating f(k1,k2,a) at small scale factors outside the interpolation range, and if fka was initialized with extrap_linear_growth = ccl_f2d_cclgrowth. * @param status Status flag. 0 if there are no errors, nonzero otherwise. */ double ccl_f3d_t_eval(ccl_f3d_t *f3d,double lk1,double lk2,double a,ccl_a_finder *finda, void *cosmo, int *status); /** * F3D structure destructor. * Frees up all memory associated with a f3d structure. * @param f3d Structure to be freed. */ void ccl_f3d_t_free(ccl_f3d_t *f3d); /** * Make a copy of a ccl_f3d_t structure. * @param f3d_o old ccl_f3d_t structure. * @param status Status flag. 0 if there are no errors, nonzero otherwise. */ ccl_f3d_t *ccl_f3d_t_copy(ccl_f3d_t *f3d_o, int *status); /** * Create a ccl_a_finder from the array of scale factors held * by a ccl_f3d_t structure. * @param f3d ccl_f3d_t structure. */ ccl_a_finder *ccl_a_finder_new_from_f3d(ccl_f3d_t *f3d); CCL_END_DECLS #endif
{ "alphanum_fraction": 0.7387948946, "avg_line_length": 49.9111111111, "ext": "h", "hexsha": "17d5457ec26955a63fc1f9c5b3eebbf0fd723f35", "lang": "C", "max_forks_count": 54, "max_forks_repo_forks_event_max_datetime": "2022-02-06T13:12:10.000Z", "max_forks_repo_forks_event_min_datetime": "2017-07-12T13:08:25.000Z", "max_forks_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "Jappenn/CCL", "max_forks_repo_path": "include/ccl_f3d.h", "max_issues_count": 703, "max_issues_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:40:10.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-07T16:27:17.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "Jappenn/CCL", "max_issues_repo_path": "include/ccl_f3d.h", "max_line_length": 579, "max_stars_count": 91, "max_stars_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Jappenn/CCL", "max_stars_repo_path": "include/ccl_f3d.h", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:55:54.000Z", "max_stars_repo_stars_event_min_datetime": "2017-07-14T02:45:59.000Z", "num_tokens": 1926, "size": 6738 }
#include <errno.h> #include <getopt.h> #include <gsl/gsl_spmatrix.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> static int verbose = 0; static int help = 0; int test (size_t m, size_t n, size_t r, size_t c, size_t nnz, const size_t *ind, const size_t *ptr, const double *data, int trials, int verbose); static void usage () { fprintf(stderr,"usage: spmv [options] <input>\n" " <input> MatrixMarket file (multiply this matrix)\n" " -r, --block_r <arg> Row block size\n" " -c, --block_c <arg> Column block size\n" " -t, --trials <arg> Number of trials to run\n" " -v, --verbose Verbose mode\n" " -q, --quiet Quiet mode\n" " -h, --help Display help message\n"); } int main (int argc, char **argv) { size_t b_r = 1; size_t b_c = 1; int trials = 1; /* Beware. Option parsing below. */ long longarg; double doublearg; while (1) { static char *options = "r:c:t:vqh"; static struct option long_options[] = { {"block_r", required_argument, 0, 'r'}, {"block_c", required_argument, 0, 'c'}, {"trials", required_argument, 0, 't'}, {"verbose", no_argument, &verbose, 1}, {"quiet", no_argument, &verbose, 0}, {"help", no_argument, &help, 1}, {0, 0, 0, 0} }; /* getopt_long stores the option index here. */ int option_index = 0; int c = getopt_long (argc, argv, options, long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; if (c == 0 && long_options[option_index].flag == 0) c = long_options[option_index].val; switch (c) { case 0: /* If this option set a flag, do nothing else now. */ break; case 'r': errno = 0; longarg = strtol(optarg, 0, 10); if (errno != 0 || longarg < 1) { printf("option -r takes an integer column block size >= 1\n"); usage(); return 1; } b_r = longarg; break; case 'c': errno = 0; longarg = strtol(optarg, 0, 10); if (errno != 0 || longarg < 1) { printf("option -c takes an integer column block size >= 1\n"); usage(); return 1; } b_c = longarg; break; case 't': errno = 0; longarg = strtol(optarg, 0, 10); if (errno != 0 || longarg < 1) { printf("option -t takes an integer number of trials >= 1\n"); usage(); return 1; } trials = longarg; break; case 'v': verbose = 1; break; case 'q': verbose = 0; break; case 'h': help = 1; break; case '?': usage(); return 1; default: abort(); } } if (help) { printf("Run a fill estimation algorithm!\n"); usage(); return 0; } if (argc - optind > 1) { printf("<input> cannot be more than one file\n"); usage(); return 1; } if (argc - optind < 1) { printf("<input> not specified\n"); usage(); return 1; } struct stat statthing; if (stat(argv[optind], &statthing) < 0 || !S_ISREG(statthing.st_mode)){ printf("<input> must be filename of MatrixMarket matrix\n"); usage(); return 1; } FILE *f = fopen(argv[optind], "r"); gsl_spmatrix *triples = gsl_spmatrix_fscanf(f); fclose(f); if (triples == 0) { printf("<input> must be filename of MatrixMarket matrix\n"); usage(); return 1; } int ret = test(triples->size1, triples->size2, b_r, b_c, triples->nz, triples->i, triples->p, triples->data, trials, verbose); gsl_spmatrix_free(triples); return ret; }
{ "alphanum_fraction": 0.5197930142, "avg_line_length": 23.1437125749, "ext": "c", "hexsha": "7ec682ea41217f7f86855e68a50b53c68235c3a5", "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": "src/run_spmv.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": "src/run_spmv.c", "max_line_length": 128, "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": "src/run_spmv.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1114, "size": 3865 }
#include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <dc1394/dc1394.h> #include <math.h> #include <fitsio.h> #include <gsl/gsl_statistics.h> #include <xpa.h> #include <sys/time.h> #include <string.h> #include <inttypes.h> #define NXPA 10 typedef struct _Box { double x; double y; double fwhm; double cenx; double ceny; double counts; double background; double noise; double sigmaxythresh; double sigmaxy; double sigmafwhmthresh; double sigmafwhm; int r; } Box; typedef struct _Back { double x; double y; double background; double sigma; int r; int width; } Back; Box box[3]; Back back; long nelements, naxes[2], fpixel; int boxsize = 30; double pixel_scale = 1.22; double stardist(int i, int j) { return( sqrt( (box[i].cenx-box[j].cenx)*(box[i].cenx-box[j].cenx) + (box[i].ceny-box[j].ceny)*(box[i].ceny-box[j].ceny) ) ); } /* this routine uses a. tokovinin's modified equation given in 2002, PASP, 114, 1156 */ double seeing(double var, double d, double r) { double lambda; double b, K, seeing; lambda = 0.65e-6; b = r/d; /* pixel scale in "/pixel, convert to rad */ var = var*pow(pixel_scale/206265.0,2); K = 0.364*(1.0 - 0.532*pow(b, -1/3) - 0.024*pow(b, -7/3)); seeing = 206265.0*0.98*pow(d/lambda, 0.2)*pow(var/K, 0.6); return seeing; } /* this routine uses the classic DIMM equation */ double old_seeing(double var, double d, double r) { double lambda; double r0; lambda = 0.65e-6; /* pixel scale in "/pixel, convert to rad */ var = var*pow(pixel_scale/206265.0,2); r0 = pow(2.0*(lambda*lambda)*( ( 0.1790*pow(d, (-1.0/3.0)) - 0.0968*pow(r, (-1.0/3.0)) )/var ), 0.6); return 206265.0*0.98*lambda/r0; } /* measure the background in an annulus around the spot pattern */ int background(char *image, int imwidth, int imheight) { int i, j, backpix; int low_y, up_y, low_x, up_x; double dist, sum, sumsq; backpix = 0; sum = 0.0; sumsq = 0.0; low_y = back.y - back.r - back.width; up_y = back.y + back.r + back.width; low_x = back.x - back.r - back.width; up_x = back.x + back.r + back.width; if (low_y < 0) { low_y = 0; } if (up_y >= imheight) { up_y = imheight; } if (low_x < 0) { low_x = 0; } if (up_x >= imwidth) { up_x = imwidth; } for (i=low_y; i<up_y; i++) { for (j=low_x; j<up_x; j++) { dist = sqrt(pow(back.x-j, 2) + pow(back.y-i, 2)); if (dist >= back.r && dist <= back.r+back.width) { sum += image[i*naxes[0]+j]; backpix++; } } } back.background = sum/backpix; //back.background = 0.0; for (i=low_y; i<up_y; i++) { for (j=low_x; j<up_x; j++) { dist = sqrt(pow(back.x-j, 2) + pow(back.y-i, 2)); if (dist >= back.r && dist <= back.r+back.width) { sumsq += (image[i*naxes[0]+j]-back.background)* (image[i*naxes[0]+j]-back.background); } } } back.sigma = sqrt(sumsq/backpix); //back.sigma = 1.0; return 1; } /* measure centroid using center-of-mass algorithm */ int centroid(char *image, int imwidth, int imheight, int num) { int i, j; double sum = 0.0; double sumx = 0.0; double sumxx = 0.0; double sumy = 0.0; double sumyy = 0.0; double val = 0.0; double gain = 0.5; double rmom; double dist; double nsigma = 5.0; int low_y, up_y, low_x, up_x; int sourcepix = 0; low_y = box[num].y - box[num].r; up_y = box[num].y + box[num].r; low_x = box[num].x - box[num].r; up_x = box[num].x + box[num].r; if (low_y < 0) { low_y = 0; } if (up_y >= imheight) { up_y = imheight; } if (low_x < 0) { low_x = 0; } if (up_x >= imwidth) { up_x = imwidth; } for (i=low_y; i<up_y; i++) { for (j=low_x; j<up_x; j++) { dist = sqrt(pow(box[num].x-j, 2) + pow(box[num].y-i, 2)); if (dist <= box[num].r) { val = image[i*naxes[0]+j] - back.background; if (val >= nsigma*back.sigma) { sum += val; sumx += val*j; sumxx += val*j*j; sumy += val*i; sumyy += val*i*i; sourcepix++; } } } } if ( sum <= 0.0 ) { box[num].sigmaxy = -1.0; box[num].sigmafwhm = -1.0; //box[num].x = imwidth/2.0; //box[num].y = imheight/2.0; box[num].fwhm = -1.0; } else { rmom = ( sumxx - sumx * sumx / sum + sumyy - sumy * sumy / sum ) / sum; if ( rmom <= 0 ) { box[num].fwhm = -1.0; } else { box[num].fwhm = sqrt(rmom) * 2.354 / sqrt(2.0); } box[num].counts = sum; box[num].cenx = sumx / sum; box[num].ceny = sumy / sum; box[num].x += gain*(box[num].cenx - box[num].x); box[num].y += gain*(box[num].ceny - box[num].y); box[num].sigmaxy= box[num].noise * sourcepix / box[num].counts / sqrt(6.0); box[num].sigmafwhm = box[num].noise * pow(sourcepix,1.5) / 10. / box[num].fwhm / box[num].counts * 2.354 * 2.354 / 2.0; } return 1; } int grab_frame(dc1394camera_t *cam, char *buf, int nbytes) { dc1394video_frame_t *frame=NULL; dc1394error_t err; err = dc1394_capture_dequeue(cam, DC1394_CAPTURE_POLICY_WAIT, &frame); if (err != DC1394_SUCCESS) { dc1394_log_error("Unable to capture."); dc1394_capture_stop(cam); dc1394_camera_free(cam); exit(1); } memcpy(buf, frame->image, nbytes); dc1394_capture_enqueue(cam, frame); return 1; } int add_gaussian(char *buffer, float cenx, float ceny, float a, float sigma) { float gauss, rsq; int i, j, low_x, up_x, low_y, up_y, size; size = 30; low_x = (int)(cenx-size); up_x = (int)(cenx+size); low_y = (int)(ceny-size); up_y = (int)(ceny+size); for (i=low_y; i<up_y; i++) { for (j=low_x; j<up_x; j++) { rsq = (cenx - j)*(cenx - j) + (ceny - i)*(ceny - i); gauss = a*expf(-1.0*rsq/(sigma*sigma)); if (gauss > 255) gauss = 255; buffer[i*naxes[0]+j] += (char)gauss; } } return 1; } int main() { dc1394camera_t *camera; char *buffer, *buffer2, *average; fitsfile *fptr; int i, j, f, status, nimages, anynul, nboxes, test; char fitsfile[256], xpastr[256]; char *froot, *timestr; FILE *init, *out; float xx = 0.0, yy = 0.0, xsum = 0.0, ysum = 0.0; double dist[2000], sig[2000], dist_l[2000], sig_l[2000]; double mean, var, var_l, avesig; double seeing_short, seeing_long, seeing_ave; struct timeval start_time, end_time; time_t start_sec, end_sec; suseconds_t start_usec, end_usec; float elapsed_time, fps; dc1394_t * dc; dc1394camera_list_t * list; dc1394error_t err; unsigned int min_bytes, max_bytes, max_height, max_width; unsigned int actual_bytes, winleft, wintop; uint64_t total_bytes = 0; char *names[NXPA]; char *messages[NXPA]; double d = 0.060; double r = 0.130; XPA xpa; xpa = XPAOpen(NULL); stderr = freopen("measure_seeing.log", "w", stderr); status = 0; anynul = 0; naxes[0] = 320; naxes[1] = 240; fpixel = 1; nelements = naxes[0]*naxes[1]; dc = dc1394_new(); if (!dc) return 1; err = dc1394_camera_enumerate(dc, &list); DC1394_ERR_RTN(err, "Failed to enumerate cameras."); if (list->num == 0) { dc1394_log_error("No cameras found."); return 1; } camera = dc1394_camera_new(dc, list->ids[0].guid); if (!camera) { dc1394_log_error("Failed to initialize camera with guid %"PRIx64".", list->ids[0].guid); return 1; } dc1394_camera_free_list(list); printf("Using camera with GUID %"PRIx64"\n", camera->guid); // need to use legacy firewire400 mode for now. 800 not quite reliable. dc1394_video_set_iso_speed(camera, DC1394_ISO_SPEED_400); // configure camera for format7 err = dc1394_video_set_mode(camera, DC1394_VIDEO_MODE_FORMAT7_1); DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), "Can't choose format7_0"); printf("I: video mode is format7_0\n"); err = dc1394_format7_get_max_image_size(camera, DC1394_VIDEO_MODE_FORMAT7_1, &max_width, &max_height); DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),"cannot get max image size for format7_0"); printf ("I: max image size is: height = %d, width = %d\n", max_height, max_width); printf ("I: current image size is: height = %ld, width = %ld\n", naxes[1], naxes[0]); //winleft = (max_width - naxes[0])/2; //wintop = (max_height - naxes[1])/2; winleft = 0; wintop = 0; err = dc1394_format7_set_roi(camera, DC1394_VIDEO_MODE_FORMAT7_1, DC1394_COLOR_CODING_MONO8, DC1394_USE_MAX_AVAIL, winleft, wintop, // left, top naxes[0], naxes[1]); DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), "Can't set ROI."); printf("I: ROI is (%d, %d) - (%ld, %ld)\n", winleft, wintop, winleft+naxes[0], wintop+naxes[1]); err = dc1394_format7_get_total_bytes(camera, DC1394_VIDEO_MODE_FORMAT7_1, &total_bytes); DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), "Can't get total bytes."); printf("I: total bytes per frame are %"PRIu64"\n", total_bytes); err = dc1394_capture_setup(camera, 16, DC1394_CAPTURE_FLAGS_DEFAULT); DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), "Error capturing."); // start the camera up err = dc1394_video_set_transmission(camera, DC1394_ON); if (err != DC1394_SUCCESS) { dc1394_log_error("Unable to start camera iso transmission."); dc1394_capture_stop(camera); dc1394_camera_free(camera); exit(1); } out = fopen("seeing.dat", "a"); init = fopen("init_cen_all", "r"); i = 0; while (fscanf(init, "%f %f\n", &xx, &yy) != EOF) { box[i].x = xx; box[i].cenx = xx; box[i].y = yy; box[i].ceny = yy; box[i].r = boxsize/2.0; i++; } nboxes = i; fclose(init); back.r = 80; back.width = 10; /* allocate the buffers */ if (!(buffer = malloc(nelements*sizeof(char)))) { printf("Couldn't Allocate Image Buffer\n"); exit(-1); } if (!(buffer2 = malloc(nelements*sizeof(char)))) { printf("Couldn't Allocate 2nd Image Buffer\n"); exit(-1); } if (!(average = malloc(nelements*sizeof(char)))) { printf("Couldn't Allocate Average Image Buffer\n"); exit(-1); } nimages = 2000; froot = "seeing.fits"; gettimeofday(&start_time, NULL); for (f=0; f<nimages; f++) { /* first do a single exposure */ grab_frame(camera, buffer, nelements*sizeof(char)); // add_gaussian(buffer, 175.0, 130.0, 50.0, 3.0); // add_gaussian(buffer, 155.0, 115.0, 50.0, 3.0); // find center of star images and calculate background xsum = 0.0; ysum = 0.0; for (i=0; i<nboxes; i++) { xsum += box[i].cenx; ysum += box[i].ceny; } back.x = xsum/nboxes; back.y = ysum/nboxes; background(buffer, naxes[0], naxes[1]); for (i=0; i<nboxes; i++) { box[i].noise = back.sigma; box[i].r = boxsize/2.0; //centroid(buffer, i); //box[i].r = boxsize/3.0; //centroid(buffer, i); //box[i].r = boxsize/4.0; centroid(buffer, naxes[0], naxes[1], i); } dist[f] = stardist(0, 1); sig[f] = box[0].sigmaxy*box[0].sigmaxy + box[1].sigmaxy*box[1].sigmaxy; /* now average two exposures */ grab_frame(camera, buffer, nelements*sizeof(char)); grab_frame(camera, buffer2, nelements*sizeof(char)); for (j=0; j<nelements; j++) { test = buffer[j]+buffer2[j]; if (test <= 254) { average[j] = buffer[j]+buffer2[j]; } else { average[j] = 254; } } // add_gaussian(average, 175.0, 130.0, 50.0, 3.0); // add_gaussian(average, 155.0, 115.0, 50.0, 3.0); xsum = 0.0; ysum = 0.0; for (i=0; i<nboxes; i++) { xsum += box[i].cenx; ysum += box[i].ceny; } back.x = xsum/nboxes; back.y = ysum/nboxes; background(average, naxes[0], naxes[1]); for (i=0; i<nboxes; i++) { box[i].noise = back.sigma; box[i].r = boxsize/2.0; //centroid(average, i); //box[i].r = boxsize/3.0; //centroid(average, i); //box[i].r = boxsize/4.0; centroid(average, naxes[0], naxes[1], i); } dist_l[f] = stardist(0, 1); sig_l[f] = box[0].sigmaxy*box[0].sigmaxy + box[1].sigmaxy*box[1].sigmaxy; if (f % 40 == 0) { status = XPASet(xpa, "ds9", "array [xdim=320,ydim=240,bitpix=8]", "ack=false", average, nelements, names, messages, NXPA); sprintf(xpastr, "image; box %f %f %d %d 0.0", box[0].x, box[0].y, boxsize, boxsize); status = XPASet(xpa, "ds9", "regions", "ack=false", xpastr, strlen(xpastr), names, messages, NXPA); sprintf(xpastr, "image; box %f %f %d %d 0.0", box[1].x, box[1].y, boxsize, boxsize); status = XPASet(xpa, "ds9", "regions", "ack=false", xpastr, strlen(xpastr), names, messages, NXPA); } } gettimeofday(&end_time, NULL); printf("End capture.\n"); /*----------------------------------------------------------------------- * stop data transmission *-----------------------------------------------------------------------*/ start_sec = start_time.tv_sec; start_usec = start_time.tv_usec; end_sec = end_time.tv_sec; end_usec = end_time.tv_usec; elapsed_time = (float)((end_sec + 1.0e-6*end_usec) - (start_sec + 1.0e-6*start_usec)); fps = 3*nimages/elapsed_time; printf("Elapsed time = %g seconds.\n", elapsed_time); printf("Framerate = %g fps.\n", fps); err=dc1394_video_set_transmission(camera,DC1394_OFF); DC1394_ERR_RTN(err,"couldn't stop the camera?"); /* sprintf(fitsfile, "!%s", froot); fits_create_file(&fptr, fitsfile, &status); fits_create_img(fptr, BYTE_IMG, 2, naxes, &status); fits_write_img(fptr, TBYTE, fpixel, nelements, buffer, &status); fits_close_file(fptr, &status); fits_report_error(stderr, status); */ /* analyze short exposure */ printf("\t SHORT EXPOSURE\n"); mean = gsl_stats_mean(dist, 1, nimages); avesig = gsl_stats_mean(sig, 1, nimages); printf("mean = %f, avesig = %f\n", mean, avesig); printf("\n"); var = gsl_stats_variance_m(dist, 1, nimages, mean); var = var - avesig; seeing_short = seeing(var, d, r); printf("sigma = %f, seeing = %f\n", sqrt(var), seeing_short); /* analyze long exposure */ printf("\t LONG EXPOSURE\n"); mean = gsl_stats_mean(dist_l, 1, nimages); avesig = gsl_stats_mean(sig_l, 1, nimages); printf("mean_l = %f, avesig_l = %f\n", mean, avesig); printf("\n"); var_l = gsl_stats_variance_m(dist_l, 1, nimages, mean); var_l = var_l - avesig; seeing_long = seeing(var_l, d, r); printf("sigma_l = %f, seeing_l = %f\n", sqrt(var_l), seeing_long); seeing_ave = pow(seeing_short, 1.75)*pow(seeing_long,-0.75); printf("Exposure corrected seeing = %4.2f\"\n\n", seeing_ave); timestr = ctime(&end_sec); fprintf(out, "%s %f %f %f %f %f\n", timestr, var, var_l, seeing_short, seeing_long, seeing_ave); init = fopen("init_cen_all", "w"); for (i=0; i<nboxes; i++) { fprintf(init, "%f %f\n", box[i].cenx, box[i].ceny); } fclose(init); fclose(out); return (status); }
{ "alphanum_fraction": 0.5892892431, "avg_line_length": 26.6801405975, "ext": "c", "hexsha": "28638d9912e9714201c79a140ba0f31603bba87e", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2017-12-01T13:02:36.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-29T15:16:35.000Z", "max_forks_repo_head_hexsha": "dde00a3bb6ca7c3d9b71e24f9363350a0e2a323f", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "marissakotze/timDIMM", "max_forks_repo_path": "src/measure_seeing_16bpp.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "dde00a3bb6ca7c3d9b71e24f9363350a0e2a323f", "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": "marissakotze/timDIMM", "max_issues_repo_path": "src/measure_seeing_16bpp.c", "max_line_length": 100, "max_stars_count": 1, "max_stars_repo_head_hexsha": "dde00a3bb6ca7c3d9b71e24f9363350a0e2a323f", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "marissakotze/timDIMM", "max_stars_repo_path": "src/measure_seeing_16bpp.c", "max_stars_repo_stars_event_max_datetime": "2021-06-06T15:26:36.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-06T15:26:36.000Z", "num_tokens": 5206, "size": 15181 }
#ifndef QUAC_P_H_ #define QUAC_P_H_ #include <petsc.h> extern int petsc_initialized; PetscLogEvent add_lin_event,add_to_ham_event,add_lin_recovery_event,add_encoded_gate_to_circuit_event; PetscLogEvent _qc_event_function_event,_qc_postevent_function_event,_apply_gate_event; PetscClassId quac_class_id; PetscLogStage pre_solve_stage,solve_stage,post_solve_stage; #endif
{ "alphanum_fraction": 0.897574124, "avg_line_length": 37.1, "ext": "h", "hexsha": "a678252d48f1656044a75d86ac7cba3c0ab5fd83", "lang": "C", "max_forks_count": 13, "max_forks_repo_forks_event_max_datetime": "2022-02-24T20:07:22.000Z", "max_forks_repo_forks_event_min_datetime": "2017-03-13T15:03:11.000Z", "max_forks_repo_head_hexsha": "2b47b378c6b5b823a094e9af79f7cb8eb39dd337", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sgulania/QuaC", "max_forks_repo_path": "src/quac_p.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "2b47b378c6b5b823a094e9af79f7cb8eb39dd337", "max_issues_repo_issues_event_max_datetime": "2020-09-03T14:21:56.000Z", "max_issues_repo_issues_event_min_datetime": "2020-07-17T15:16:22.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "sgulania/QuaC", "max_issues_repo_path": "src/quac_p.h", "max_line_length": 102, "max_stars_count": 23, "max_stars_repo_head_hexsha": "2b47b378c6b5b823a094e9af79f7cb8eb39dd337", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sgulania/QuaC", "max_stars_repo_path": "src/quac_p.h", "max_stars_repo_stars_event_max_datetime": "2022-01-28T10:27:57.000Z", "max_stars_repo_stars_event_min_datetime": "2017-06-18T02:11:04.000Z", "num_tokens": 98, "size": 371 }
//**************************************************************************\ //* This file is property of and copyright by the ALICE Project *\ //* ALICE Experiment at CERN, All rights reserved. *\ //* *\ //* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> *\ //* for The ALICE HLT Project. *\ //* *\ //* Permission to use, copy, modify and distribute this software and its *\ //* documentation strictly for non-commercial purposes is hereby granted *\ //* without fee, provided that the above copyright notice appears in all *\ //* copies and that both the copyright notice and this permission notice *\ //* appear in the supporting documentation. The authors make no claims *\ //* about the suitability of this software for any purpose. It is *\ //* provided "as is" without express or implied warranty. *\ //************************************************************************** /// \file GPUO2InterfaceRefit.h /// \author David Rohr #ifndef GPUO2INTERFACEREFIT_H #define GPUO2INTERFACEREFIT_H // Some defines denoting that we are compiling for O2 #ifndef HAVE_O2HEADERS #define HAVE_O2HEADERS #endif #ifndef GPUCA_TPC_GEOMETRY_O2 #define GPUCA_TPC_GEOMETRY_O2 #endif #ifndef GPUCA_O2_INTERFACE #define GPUCA_O2_INTERFACE #endif #include <memory> #include <vector> #include <gsl/span> namespace o2::base { template <typename value_T> class PropagatorImpl; using Propagator = PropagatorImpl<float>; } // namespace o2::base namespace o2::dataformats { template <typename FirstEntry, typename NElem> class RangeReference; } namespace o2::tpc { using TPCClRefElem = uint32_t; using TrackTPCClusRef = o2::dataformats::RangeReference<uint32_t, uint16_t>; class TrackTPC; struct ClusterNativeAccess; } // namespace o2::tpc namespace o2::track { template <typename value_T> class TrackParametrizationWithError; using TrackParCovF = TrackParametrizationWithError<float>; using TrackParCov = TrackParCovF; } // namespace o2::track namespace o2::gpu { class GPUParam; class GPUTrackingRefit; class TPCFastTransform; class GPUO2InterfaceRefit { public: // Must initialize with: // - In any case: Cluster Native access structure (cl), TPC Fast Transformation instance (trans), solenoid field (bz), TPC Track hit references (trackRef) // - Either the shared cluster map (sharedmap) or the vector of tpc tracks (trks) to build the shared cluster map internally // - o2::base::Propagator (p) in case RefitTrackAsTrackParCov is to be used GPUO2InterfaceRefit(const o2::tpc::ClusterNativeAccess* cl, const TPCFastTransform* trans, float bz, const o2::tpc::TPCClRefElem* trackRef, const unsigned char* sharedmap = nullptr, const std::vector<o2::tpc::TrackTPC>* trks = nullptr, o2::base::Propagator* p = nullptr); ~GPUO2InterfaceRefit(); int RefitTrackAsGPU(o2::tpc::TrackTPC& trk, bool outward = false, bool resetCov = false); int RefitTrackAsTrackParCov(o2::tpc::TrackTPC& trk, bool outward = false, bool resetCov = false); int RefitTrackAsGPU(o2::track::TrackParCov& trk, const o2::tpc::TrackTPCClusRef& clusRef, float time0, float* chi2 = nullptr, bool outward = false, bool resetCov = false); int RefitTrackAsTrackParCov(o2::track::TrackParCov& trk, const o2::tpc::TrackTPCClusRef& clusRef, float time0, float* chi2 = nullptr, bool outward = false, bool resetCov = false); void setGPUTrackFitInProjections(bool v = true); void setTrackReferenceX(float v); void setIgnoreErrorsAtTrackEnds(bool v); static void fillSharedClustersMap(const o2::tpc::ClusterNativeAccess* cl, const gsl::span<const o2::tpc::TrackTPC> trks, const o2::tpc::TPCClRefElem* trackRef, unsigned char* shmap); private: std::unique_ptr<GPUTrackingRefit> mRefit; std::unique_ptr<GPUParam> mParam; std::vector<unsigned char> mSharedMap; }; } // namespace o2::gpu #endif
{ "alphanum_fraction": 0.6819413649, "avg_line_length": 41.4183673469, "ext": "h", "hexsha": "98efb4f714ed29c6b3acc25d99be58ab26cad327", "lang": "C", "max_forks_count": 275, "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:06:19.000Z", "max_forks_repo_forks_event_min_datetime": "2016-06-21T20:24:05.000Z", "max_forks_repo_head_hexsha": "c1d89b133b433f608b2373112d3608d8cec26095", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "chengtt0406/AliRoot", "max_forks_repo_path": "GPU/GPUTracking/Interface/GPUO2InterfaceRefit.h", "max_issues_count": 1388, "max_issues_repo_head_hexsha": "c1d89b133b433f608b2373112d3608d8cec26095", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:26:09.000Z", "max_issues_repo_issues_event_min_datetime": "2016-11-01T10:27:36.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "chengtt0406/AliRoot", "max_issues_repo_path": "GPU/GPUTracking/Interface/GPUO2InterfaceRefit.h", "max_line_length": 273, "max_stars_count": 52, "max_stars_repo_head_hexsha": "c1d89b133b433f608b2373112d3608d8cec26095", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "chengtt0406/AliRoot", "max_stars_repo_path": "GPU/GPUTracking/Interface/GPUO2InterfaceRefit.h", "max_stars_repo_stars_event_max_datetime": "2022-03-11T11:49:35.000Z", "max_stars_repo_stars_event_min_datetime": "2016-12-11T13:04:01.000Z", "num_tokens": 1058, "size": 4059 }
// // smctc.h // // The principle header file for the SMC template class. // // Copyright Adam Johansen, 2008 // // // This file is part of SMCTC. // // SMCTC 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. // // SMCTC 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 SMCTC. If not, see <http://www.gnu.org/licenses/>. // /// \mainpage smctc -- A Template Class Library for SMC Simulation /// /// \version 1.0 /// \author Adam M. Johansen /// /// \section intro_sec Summary /// /// The SMC template class library (SMCTC) is intended to be used to implement SMC /// algorithms ranging from simple particle filter to complicated SMC algorithms /// from simple particle filters to the SMC samplers of Del Moral, Doucet and Jasra (2006) /// within a generic framework. /// /// \section license License /// /// SMCTC 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. /// /// SMCTC 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 SMCTC. If not, see <http://www.gnu.org/licenses/>. /// /// The software is still in development but is thought to be sufficiently fully-featured and /// stable for use. /// /// \section using_sec Using the Template Library /// /// In order to use the template libary it is necessary to place the set of header files in /// a suitable include directory and then to instantiate the various classes with the /// appropriate type for your sampler. /// /// For implementation details, please see the accompanying user guide. /// /// /// \section example_sec Examples /// /// \subsection A Simple Particle Filter /// /// This example provides a simple particle filter for the approximate filtering of /// nonlinear, nongaussian state space models. /// /// \subsection SMC Samplers for Rare Event Simulation /// /// The main.cc file provides an example of a use of the template library to estimate /// Gaussian tail probabilities within an SMC samplers framework by making use of a sequence /// of intermediate distributions defined by introducing a potential function which /// varies from flat to being very close to an indicator function on the tail event. /// /// This example is taken from from Johansen, Del Moral and Doucet (2006). /// /// \subsection Acknowledgements /// /// Thanks are due to Edmund Jackson and Mark Briers for testing SMCTC on a variety of platforms. /// The Visual C++ project and solution files are kindly provided by Mark Briers. /// //! \file //! \brief The main header file for SMCTC. //! //! This file serves as an interface between user-space programs and the SMCTC library. //! This is the only header file which applications need to include to make use of the library (it includes //! such additional files as are necessary). #ifndef __SMC_TDSMC_HH #define __SMC_TDSMC_HH 1.0 #include <cmath> #include <cstdlib> #include <iostream> #include <gsl/gsl_rng.h> #include "smc-exception.h" #include "sampler.h" /// The Sequential Monte Carlo namespace /// /// The classes and functions within this namespace are intended to be used for producing /// implemenetations of SMC samplers and related simulation techniques. namespace smc {} /// The standard namespace /// The classes provided within the standard libraries reside within this namespace and /// the TDSMC class library adds a number of additional operator overloads to some of /// the standard classes to allow them to deal with our structures. namespace std {} #endif
{ "alphanum_fraction": 0.7285616282, "avg_line_length": 35.8442622951, "ext": "h", "hexsha": "ce04c873d81f1bc15df8c662831b05ca3654eebe", "lang": "C", "max_forks_count": 15, "max_forks_repo_forks_event_max_datetime": "2021-10-08T13:20:35.000Z", "max_forks_repo_forks_event_min_datetime": "2018-05-26T22:34:24.000Z", "max_forks_repo_head_hexsha": "58cb79d35e35786ecea1bf8023a639fd8bb148c0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "williamg42/IMU-GPS-Fusion", "max_forks_repo_path": "include/smctc.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "58cb79d35e35786ecea1bf8023a639fd8bb148c0", "max_issues_repo_issues_event_max_datetime": "2019-04-02T17:45:59.000Z", "max_issues_repo_issues_event_min_datetime": "2018-03-22T09:21:20.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "williamg42/IMU-GPS-Fusion", "max_issues_repo_path": "include/smctc.h", "max_line_length": 107, "max_stars_count": 27, "max_stars_repo_head_hexsha": "58cb79d35e35786ecea1bf8023a639fd8bb148c0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "williamg42/IMU-GPS-Fusion", "max_stars_repo_path": "include/smctc.h", "max_stars_repo_stars_event_max_datetime": "2022-03-10T15:16:46.000Z", "max_stars_repo_stars_event_min_datetime": "2018-03-22T09:11:16.000Z", "num_tokens": 981, "size": 4373 }
/** * * @file qwrapper_slantr.c * * PLASMA core_blas quark wrapper * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Mathieu Faverge * @date 2010-11-15 * @generated s Tue Jan 7 11:44:57 2014 * **/ #include <lapacke.h> #include "common.h" void CORE_slantr_quark(Quark *quark); void CORE_slantr_f1_quark(Quark *quark); /***************************************************************************//** * **/ void QUARK_CORE_slantr(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum norm, PLASMA_enum uplo, PLASMA_enum diag, int M, int N, const float *A, int LDA, int szeA, int szeW, float *result) { szeW = max(1, szeW); DAG_CORE_LANGE; QUARK_Insert_Task(quark, CORE_slantr_quark, task_flags, sizeof(PLASMA_enum), &norm, VALUE, sizeof(PLASMA_enum), &uplo, VALUE, sizeof(PLASMA_enum), &diag, VALUE, sizeof(int), &M, VALUE, sizeof(int), &N, VALUE, sizeof(float)*szeA, A, INPUT, sizeof(int), &LDA, VALUE, sizeof(float)*szeW, NULL, SCRATCH, sizeof(float), result, OUTPUT, 0); } /***************************************************************************//** * **/ void QUARK_CORE_slantr_f1(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum norm, PLASMA_enum uplo, PLASMA_enum diag, int M, int N, const float *A, int LDA, int szeA, int szeW, float *result, float *fake, int szeF) { szeW = max(1, szeW); DAG_CORE_LANGE; if ( result == fake ) { QUARK_Insert_Task(quark, CORE_slantr_quark, task_flags, sizeof(PLASMA_enum), &norm, VALUE, sizeof(PLASMA_enum), &uplo, VALUE, sizeof(PLASMA_enum), &diag, VALUE, sizeof(int), &M, VALUE, sizeof(int), &N, VALUE, sizeof(float)*szeA, A, INPUT, sizeof(int), &LDA, VALUE, sizeof(float)*szeW, NULL, SCRATCH, sizeof(float), result, OUTPUT | GATHERV, 0); } else { QUARK_Insert_Task(quark, CORE_slantr_f1_quark, task_flags, sizeof(PLASMA_enum), &norm, VALUE, sizeof(PLASMA_enum), &uplo, VALUE, sizeof(PLASMA_enum), &diag, VALUE, sizeof(int), &M, VALUE, sizeof(int), &N, VALUE, sizeof(float)*szeA, A, INPUT, sizeof(int), &LDA, VALUE, sizeof(float)*szeW, NULL, SCRATCH, sizeof(float), result, OUTPUT, sizeof(float)*szeF, fake, OUTPUT | GATHERV, 0); } } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_slantr_quark = PCORE_slantr_quark #define CORE_slantr_quark PCORE_slantr_quark #endif void CORE_slantr_quark(Quark *quark) { float *normA; PLASMA_enum norm, uplo, diag; int M; int N; float *A; int LDA; float *work; quark_unpack_args_9(quark, norm, uplo, diag, M, N, A, LDA, work, normA); *normA = LAPACKE_slantr_work( LAPACK_COL_MAJOR, lapack_const(norm), lapack_const(uplo), lapack_const(diag), M, N, A, LDA, work); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_slantr_f1_quark = PCORE_slantr_f1_quark #define CORE_slantr_f1_quark PCORE_slantr_f1_quark #endif void CORE_slantr_f1_quark(Quark *quark) { float *normA; PLASMA_enum norm, uplo, diag; int M; int N; float *A; int LDA; float *work; float *fake; quark_unpack_args_10(quark, norm, uplo, diag, M, N, A, LDA, work, normA, fake); *normA = LAPACKE_slantr_work( LAPACK_COL_MAJOR, lapack_const(norm), lapack_const(uplo), lapack_const(diag), M, N, A, LDA, work); }
{ "alphanum_fraction": 0.4734371666, "avg_line_length": 33.7194244604, "ext": "c", "hexsha": "a19c684291aee8457dcdc9fd062ef24b0caa8f85", "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-qwrapper/qwrapper_slantr.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-qwrapper/qwrapper_slantr.c", "max_line_length": 93, "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-qwrapper/qwrapper_slantr.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1217, "size": 4687 }
/* gsl_spmatrix.h * * Copyright (C) 2012-2014 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_SPMATRIX_H__ #define __GSL_SPMATRIX_H__ #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 /* * Binary tree data structure for storing sparse matrix elements * in triplet format. This is used for efficiently detecting * duplicates and element retrieval via gsl_spmatrix_get */ typedef struct { void *tree; /* tree structure */ void *node_array; /* preallocated array of tree nodes */ size_t n; /* number of tree nodes in use (<= nzmax) */ } gsl_spmatrix_tree; /* * Triplet format: * * If data[n] = A_{ij}, then: * i = A->i[n] * j = A->p[n] * * Compressed column format (CCS): * * If data[n] = A_{ij}, then: * i = A->i[n] * A->p[j] <= n < A->p[j+1] * so that column j is stored in * [ data[p[j]], data[p[j] + 1], ..., data[p[j+1] - 1] ] * * Compressed row format (CRS): * * If data[n] = A_{ij}, then: * j = A->i[n] * A->p[i] <= n < A->p[i+1] * so that row i is stored in * [ data[p[i]], data[p[i] + 1], ..., data[p[i+1] - 1] ] */ typedef struct { size_t size1; /* number of rows */ size_t size2; /* number of columns */ /* i (size nzmax) contains: * * Triplet/CCS: row indices * CRS: column indices */ size_t *i; double *data; /* matrix elements of size nzmax */ /* * p contains the column indices (triplet) or column pointers (compcol) * * triplet: p[n] = column number of element data[n] * CCS: p[j] = index in data of first non-zero element in column j * CRS: p[i] = index in data of first non-zero element in row i */ size_t *p; size_t nzmax; /* maximum number of matrix elements */ size_t nz; /* number of non-zero values in matrix */ gsl_spmatrix_tree *tree_data; /* binary tree for sorting triplet data */ /* * workspace of size MAX(size1,size2)*MAX(sizeof(double),sizeof(size_t)) * used in various routines */ void *work; size_t sptype; /* sparse storage type */ } gsl_spmatrix; #define GSL_SPMATRIX_TRIPLET (0) #define GSL_SPMATRIX_CCS (1) #define GSL_SPMATRIX_CRS (2) #define GSL_SPMATRIX_ISTRIPLET(m) ((m)->sptype == GSL_SPMATRIX_TRIPLET) #define GSL_SPMATRIX_ISCCS(m) ((m)->sptype == GSL_SPMATRIX_CCS) #define GSL_SPMATRIX_ISCRS(m) ((m)->sptype == GSL_SPMATRIX_CRS) /* * Prototypes */ gsl_spmatrix *gsl_spmatrix_alloc(const size_t n1, const size_t n2); gsl_spmatrix *gsl_spmatrix_alloc_nzmax(const size_t n1, const size_t n2, const size_t nzmax, const size_t flags); void gsl_spmatrix_free(gsl_spmatrix *m); int gsl_spmatrix_realloc(const size_t nzmax, gsl_spmatrix *m); int gsl_spmatrix_set_zero(gsl_spmatrix *m); size_t gsl_spmatrix_nnz(const gsl_spmatrix *m); int gsl_spmatrix_compare_idx(const size_t ia, const size_t ja, const size_t ib, const size_t jb); int gsl_spmatrix_tree_rebuild(gsl_spmatrix * m); /* spcopy.c */ int gsl_spmatrix_memcpy(gsl_spmatrix *dest, const gsl_spmatrix *src); /* spgetset.c */ double gsl_spmatrix_get(const gsl_spmatrix *m, const size_t i, const size_t j); int gsl_spmatrix_set(gsl_spmatrix *m, const size_t i, const size_t j, const double x); double *gsl_spmatrix_ptr(gsl_spmatrix *m, const size_t i, const size_t j); /* spcompress.c */ gsl_spmatrix *gsl_spmatrix_compcol(const gsl_spmatrix *T); gsl_spmatrix *gsl_spmatrix_ccs(const gsl_spmatrix *T); gsl_spmatrix *gsl_spmatrix_crs(const gsl_spmatrix *T); void gsl_spmatrix_cumsum(const size_t n, size_t *c); /* spio.c */ int gsl_spmatrix_fprintf(FILE *stream, const gsl_spmatrix *m, const char *format); gsl_spmatrix * gsl_spmatrix_fscanf(FILE *stream); int gsl_spmatrix_fwrite(FILE *stream, const gsl_spmatrix *m); int gsl_spmatrix_fread(FILE *stream, gsl_spmatrix *m); /* spoper.c */ int gsl_spmatrix_scale(gsl_spmatrix *m, const double x); int gsl_spmatrix_minmax(const gsl_spmatrix *m, double *min_out, double *max_out); int gsl_spmatrix_add(gsl_spmatrix *c, const gsl_spmatrix *a, const gsl_spmatrix *b); int gsl_spmatrix_d2sp(gsl_spmatrix *S, const gsl_matrix *A); int gsl_spmatrix_sp2d(gsl_matrix *A, const gsl_spmatrix *S); /* spprop.c */ int gsl_spmatrix_equal(const gsl_spmatrix *a, const gsl_spmatrix *b); /* spswap.c */ int gsl_spmatrix_transpose(gsl_spmatrix * m); int gsl_spmatrix_transpose2(gsl_spmatrix * m); int gsl_spmatrix_transpose_memcpy(gsl_spmatrix *dest, const gsl_spmatrix *src); __END_DECLS #endif /* __GSL_SPMATRIX_H__ */
{ "alphanum_fraction": 0.6858367566, "avg_line_length": 31.1055555556, "ext": "h", "hexsha": "8e68256f9dfc068ce62af680b6410897483a7d2b", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-06-13T05:31:07.000Z", "max_forks_repo_forks_event_min_datetime": "2018-12-20T16:50:58.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/gsl_spmatrix.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "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": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/gsl_spmatrix.h", "max_line_length": 81, "max_stars_count": 7, "max_stars_repo_head_hexsha": "0ad5e82b49a973cf710f85daa9dffc45261b36ae", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Tjoppen/fmigo", "max_stars_repo_path": "3rdparty/wingsl/include/gsl/gsl_spmatrix.h", "max_stars_repo_stars_event_max_datetime": "2021-05-14T07:38:05.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-18T16:35:21.000Z", "num_tokens": 1650, "size": 5599 }
/** * * @file example_dpotrf.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 of Cholesky factorization * * @version 2.6.0 * @author Bilel Hadri * @date 2010-11-15 * @generated d Tue Jan 7 11:45:20 2014 * **/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <time.h> #include <plasma.h> #include <cblas.h> #include <lapacke.h> #include <core_blas.h> #include "testing_dmain.h" static int check_factorization(int, double*, double*, int, int); //int IONE=1; //int ISEED[4] = {0,0,0,1}; /* initial seed for dlarnv() */ static void GENMAT_SYM_FULL(int m, double *A) { srand48(time(NULL)); int j; for (j = 0; j < m; ++j ) { int i; for( i = j; i < m; ++i ) { double dran = drand48(); A[j*m+i] = A[i*m+j] = dran; } } for(j = 0; j < m; ++j) A[j*m+j] += 10 * m; } int testing_dpotrf(int argc, char **argv) { if (argc != 2){ fprintf(stderr,"POTRF: N LDA\n"); return -1; } int N = atoi(argv[0]); int LDA = atoi(argv[1]); int info_factorization; PLASMA_Set(PLASMA_TILE_SIZE, 388); double *A1 = (double *)malloc(LDA*N*sizeof(double)); #pragma omp register ([LDA*N]A1) double *A2 = (double *)malloc(LDA*N*sizeof(double)); #pragma omp register ([LDA*N]A2) /* Check if unable to allocate memory */ if ((!A1)||(!A2)){ printf("Out of Memory \n "); return 0; } /* Initialize A1 and A2 for Symmetric Positive Matrix */ GENMAT_SYM_FULL(N, A1); int i; for(i = 0; i < N*LDA; ++i){ A2[i] = A1[i]; } /* Plasma routines */ PLASMA_dpotrf(PlasmaUpper, N, A2, LDA); /* Check the factorization */ info_factorization = check_factorization( N, A1, A2, LDA, PlasmaUpper); if ( info_factorization != 0 ) printf("-- Error in DPOTRF example ! \n"); else printf("-- Run of DPOTRF example successful ! \n"); free(A1); free(A2); return 0; } static int check_factorization(int N, double *A1, double *A2, int LDA, int uplo) { double Anorm, Rnorm; double alpha; int info_factorization; int i,j; double eps; eps = LAPACKE_dlamch_work('e'); double *Residual = (double *)malloc(N*N*sizeof(double)); double *L1 = (double *)malloc(N*N*sizeof(double)); double *L2 = (double *)malloc(N*N*sizeof(double)); double *work = (double *)malloc(N*sizeof(double)); memset((void*)L1, 0, N*N*sizeof(double)); memset((void*)L2, 0, N*N*sizeof(double)); alpha= 1.0; LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,' ', N, N, A1, LDA, Residual, N); /* Dealing with L'L or U'U */ if (uplo == PlasmaUpper){ LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L1, N); LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L2, N); cblas_dtrmm(CblasColMajor, CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, N, N, (alpha), L1, N, L2, N); } else{ LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L1, N); LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L2, N); cblas_dtrmm(CblasColMajor, CblasRight, CblasLower, CblasTrans, CblasNonUnit, N, N, (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]; Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, N, Residual, N, work); Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, N, A1, LDA, work); 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)) || (Rnorm/(Anorm*N*eps) > 10.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; } int timing_dpotrf(int argc, char **argv) { int N; int LDA; int bs; int rep; double start, end; double elapsed; FILE *log; int num_threads; if (argc != 4 ) { fprintf(stderr,"DPOTRF n lda bs rep\n"); exit(1); } sscanf(argv[0], "%d", &N); sscanf(argv[1], "%d", &LDA); sscanf(argv[2], "%d", &bs); sscanf(argv[3], "%d", &rep); double *A = malloc(LDA*N*sizeof(double)); #pragma omp register ([LDA*N]A) /* Check if unable to allocate memory */ if (!A){ printf("Out of Memory \n "); return 0; } /* Plasma Initialize */ PLASMA_Set( PLASMA_TILE_SIZE, bs); GENMAT_SYM_FULL(N, A); elapsed = 0.0; int i; for ( i = 0; i < rep; i++ ) { start = gtime(); PLASMA_dpotrf(PlasmaUpper, N, A, LDA); end = gtime(); elapsed += end - start; } num_threads = omp_get_max_threads(); dump_info("plasma_dpotrf.log", num_threads, elapsed, rep); free(A); return 0; }
{ "alphanum_fraction": 0.5934087363, "avg_line_length": 24.3033175355, "ext": "c", "hexsha": "7ef60d589fbcb28b0feb38048b9936c3ac5aaad6", "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_dpotrf.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_dpotrf.c", "max_line_length": 114, "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_dpotrf.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1714, "size": 5128 }
/* 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 reproduction.c * \brief Source file to define the reproduction functions. * \author Javier Burguete Tolosa. * \copyright Copyright 2014 Javier Burguete Tolosa. All rights reserved. */ #define _GNU_SOURCE #include <string.h> #include <glib.h> #include <gsl/gsl_rng.h> //#include "config.h" #include "bits.h" #include "entity.h" #include "reproduction.h" void (*reproduction) (Entity *, Entity *, Entity *, unsigned int, gsl_rng *); ///< Pointer to the function to apply the reproduction operation. /** * Function to mate two genotypes by single-point reproduction of each genome. */ static void reproduction_singlepoints (Entity * father, ///< Father. Entity * mother, ///< Mother. Entity * son, ///< Son. unsigned int nbits, ///< Genome nbits. gsl_rng * rng) ///< GSL random numbers generator. { int i; i = gsl_rng_uniform_int (rng, nbits); bit_copy (son->genome, mother->genome, 0, 0, i); bit_copy (son->genome, father->genome, i, i, nbits - i); } /** * Function to mate two genotypes by double-point reproduction of each genome. */ static void reproduction_doublepoints (Entity * father, ///< Father. Entity * mother, ///< Mother. Entity * son, ///< Son. unsigned int nbits, ///< Genome nbits. gsl_rng * rng) ///< GSL random numbers generator. { unsigned int i, j, k; i = gsl_rng_uniform_int (rng, nbits); j = gsl_rng_uniform_int (rng, nbits); if (i > j) k = i, i = j, j = k; bit_copy (son->genome, mother->genome, 0, 0, i); bit_copy (son->genome, father->genome, i, i, j - i); bit_copy (son->genome, mother->genome, j, j, nbits - j); } /** * Function to mate two genotypes by random mixing both genomes. */ static void reproduction_mixing (Entity * father, ///< Father. Entity * mother, ///< Mother. Entity * son, ///< Son. unsigned int nbits, ///< Genome nbits. gsl_rng * rng) ///< GSL random numbers generator. { unsigned int i; for (i = 0; i < nbits; i++) { if (gsl_rng_uniform_int (rng, 2)) { bit_get (father->genome, i) ? bit_set (son->genome, i) : bit_clear (son->genome, i); } else { bit_get (mother->genome, i) ? bit_set (son->genome, i) : bit_clear (son->genome, i); } } } /** * Function to select the reproduction operations. */ void reproduction_init (unsigned int type) ///< Type of reproduction operations. { switch (type) { case REPRODUCTION_TYPE_SINGLEPOINTS: reproduction = &reproduction_singlepoints; break; case REPRODUCTION_TYPE_DOUBLEPOINTS: reproduction = &reproduction_doublepoints; break; default: reproduction = &reproduction_mixing; } }
{ "alphanum_fraction": 0.6356606777, "avg_line_length": 34.3515625, "ext": "c", "hexsha": "31219bddcc38257c8071ecbf403712d18a715a8f", "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/reproduction.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/reproduction.c", "max_line_length": 79, "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/reproduction.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": 995, "size": 4397 }
#ifndef CWANNIER_ECACHE_H #define CWANNIER_ECACHE_H #include <stdlib.h> #include <stdbool.h> #include <gsl/gsl_vector.h> #include "input.h" typedef struct { int na; int nb; int nc; int num_bands; int G_order[3]; int G_neg[3]; InputFn Efn; bool use_cache; gsl_vector **energies; } EnergyCache; #include "submesh.h" EnergyCache* init_EnergyCache(int na, int nb, int nc, int num_bands, int G_order[3], int G_neg[3], InputFn Efn, bool use_cache); void free_EnergyCache(EnergyCache *Ecache); void energy_from_cache(EnergyCache *Ecache, int i, int j, int k, gsl_vector *energies); void verify_sort(gsl_vector *energies); #endif // CWANNIER_ECACHE_H
{ "alphanum_fraction": 0.7176128093, "avg_line_length": 21.46875, "ext": "h", "hexsha": "73492c0d38337da7d2e6ec29fb04531a3b7ba52b", "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": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tflovorn/ctetra", "max_forks_repo_path": "ecache.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_issues_repo_issues_event_max_datetime": "2016-11-30T15:23:35.000Z", "max_issues_repo_issues_event_min_datetime": "2016-11-19T22:44:14.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "tflovorn/ctetra", "max_issues_repo_path": "ecache.h", "max_line_length": 128, "max_stars_count": null, "max_stars_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tflovorn/ctetra", "max_stars_repo_path": "ecache.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 202, "size": 687 }