source
stringlengths
3
92
c
stringlengths
26
2.25M
layouts.c
/** * This file is a container for all plotting layout algorithms * * c Ronny Lorenz * The ViennaRNA Package */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include "ViennaRNA/utils/basic.h" #include "ViennaRNA/plotting/layouts.h" #ifdef _OPENMP #include <omp.h> #endif #define PUBLIC #define PRIVATE static PUBLIC int rna_plot_type = 1; /* 0 = simple, 1 = naview, 2 = circular plot */ PRIVATE float *angle; PRIVATE int *loop_size, *stack_size; PRIVATE int lp, stk; PRIVATE void loop(int i, int j, short *pair_table); #ifdef _OPENMP /* NOTE: all threadprivate variables are uninitialized when entering a thread! */ #pragma omp threadprivate(angle, loop_size, stack_size, lp, stk) #endif /*---------------------------------------------------------------------------*/ PUBLIC int simple_xy_coordinates(short *pair_table, float *x, float *y) { float INIT_ANGLE=0.; /* initial bending angle */ float INIT_X = 100.; /* coordinate of first digit */ float INIT_Y = 100.; /* see above */ float RADIUS = 15.; int i, length; float alpha; length = pair_table[0]; angle = (float*) vrna_alloc( (length+5)*sizeof(float) ); loop_size = (int*) vrna_alloc( 16+(length/5)*sizeof(int) ); stack_size = (int*) vrna_alloc( 16+(length/5)*sizeof(int) ); lp = stk = 0; loop(0, length, pair_table); loop_size[lp] -= 2; /* correct for cheating with function loop */ alpha = INIT_ANGLE; x[0] = INIT_X; y[0] = INIT_Y; for (i = 1; i <= length; i++) { x[i] = x[i-1]+RADIUS*cos(alpha); y[i] = y[i-1]+RADIUS*sin(alpha); alpha += PI-angle[i+1]; } free(angle); free(loop_size); free(stack_size); return length; } /*---------------------------------------------------------------------------*/ PRIVATE void loop(int i, int j, short *pair_table) /* i, j are the positions AFTER the last pair of a stack; i.e i-1 and j+1 are paired. */ { int count = 2; /* counts the VERTICES of a loop polygon; that's NOT necessarily the number of unpaired bases! Upon entry the loop has already 2 vertices, namely the pair i-1/j+1. */ int r = 0, bubble = 0; /* bubble counts the unpaired digits in loops */ int i_old, partner, k, l, start_k, start_l, fill, ladder; int begin, v, diff; float polygon; short *remember; remember = (short *) vrna_alloc((3+(j-i)/5)*2*sizeof(short)); i_old = i-1, j++; /* j has now been set to the partner of the previous pair for correct while-loop termination. */ while (i != j) { partner = pair_table[i]; if ((!partner) || (i==0)) i++, count++, bubble++; else { count += 2; k = i, l = partner; /* beginning of stack */ remember[++r] = k; remember[++r] = l; i = partner+1; /* next i for the current loop */ start_k = k, start_l = l; ladder = 0; do { k++, l--, ladder++; /* go along the stack region */ } while ((pair_table[k] == l) && (pair_table[k] > k)); fill = ladder-2; if (ladder >= 2) { angle[start_k+1+fill] += PIHALF; /* Loop entries and */ angle[start_l-1-fill] += PIHALF; /* exits get an */ angle[start_k] += PIHALF; /* additional PI/2. */ angle[start_l] += PIHALF; /* Why ? (exercise) */ if (ladder > 2) { for (; fill >= 1; fill--) { angle[start_k+fill] = PI; /* fill in the angles */ angle[start_l-fill] = PI; /* for the backbone */ } } } stack_size[++stk] = ladder; if(k <= l) loop(k, l, pair_table); } } polygon = PI*(count-2)/(float)count; /* bending angle in loop polygon */ remember[++r] = j; begin = i_old < 0 ? 0 : i_old; for (v = 1; v <= r; v++) { diff = remember[v]-begin; for (fill = 0; fill <= diff; fill++) angle[begin+fill] += polygon; if (v > r) break; begin = remember[++v]; } loop_size[++lp] = bubble; free(remember); } /*---------------------------------------------------------------------------*/ PUBLIC int simple_circplot_coordinates(short *pair_table, float *x, float *y){ unsigned int length = (unsigned int) pair_table[0]; unsigned int i; float d = 2*PI/length; for(i=0; i < length; i++){ x[i] = cos(i * d - PI/2); y[i] = sin(i * d - PI/2); } return length; }
blackscholes.simd.c
// Copyright (c) 2007 Intel Corp. // Black-Scholes // Analytical method for calculating European Options // // // Reference Source: Options, Futures, and Other Derivatives, 3rd Edition, Prentice // Hall, John C. Hull, #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #ifndef WIN32 #include <pmmintrin.h> #else #include <xmmintrin.h> #endif #ifdef ENABLE_PARSEC_HOOKS #include <hooks.h> #endif // Multi-threaded pthreads header #ifdef ENABLE_THREADS // Add the following line so that icc 9.0 is compatible with pthread lib. #define __thread __threadp MAIN_ENV #undef __thread #endif // Multi-threaded OpenMP header #ifdef ENABLE_OPENMP #include <omp.h> #endif #ifdef ENABLE_TBB #include "tbb/blocked_range.h" #include "tbb/parallel_for.h" #include "tbb/task_scheduler_init.h" #include "tbb/tick_count.h" using namespace std; using namespace tbb; #endif //ENABLE_TBB // Multi-threaded header for Windows #ifdef WIN32 #pragma warning(disable : 4305) #pragma warning(disable : 4244) #include <windows.h> #endif #ifdef __GNUC__ #define _MM_ALIGN16 __attribute__((aligned (16))) #define MUSTINLINE __attribute__((always_inline)) #else #define MUSTINLINE __forceinline #endif // NCO = Number of Concurrent Options = SIMD Width // NCO is currently set in the Makefile. #ifndef NCO #error NCO must be defined. #endif #if (NCO==2) #define fptype double #define SIMD_WIDTH 2 #define _MMR __m128d #define _MM_LOAD _mm_load_pd #define _MM_STORE _mm_store_pd #define _MM_MUL _mm_mul_pd #define _MM_ADD _mm_add_pd #define _MM_SUB _mm_sub_pd #define _MM_DIV _mm_div_pd #define _MM_SQRT _mm_sqrt_pd #define _MM_SET(A) _mm_set_pd(A,A) #define _MM_SETR _mm_set_pd #endif #if (NCO==4) #define fptype float #define SIMD_WIDTH 4 #define _MMR __m128 #define _MM_LOAD _mm_load_ps #define _MM_STORE _mm_store_ps #define _MM_MUL _mm_mul_ps #define _MM_ADD _mm_add_ps #define _MM_SUB _mm_sub_ps #define _MM_DIV _mm_div_ps #define _MM_SQRT _mm_sqrt_ps #define _MM_SET(A) _mm_set_ps(A,A,A,A) #define _MM_SETR _mm_set_ps #endif #define NUM_RUNS 100 typedef struct OptionData_ { fptype s; // spot price fptype strike; // strike price fptype r; // risk-free interest rate fptype divq; // dividend rate fptype v; // volatility fptype t; // time to maturity or option expiration in years // (1yr = 1.0, 6mos = 0.5, 3mos = 0.25, ..., etc) char OptionType; // Option type. "P"=PUT, "C"=CALL fptype divs; // dividend vals (not used in this test) fptype DGrefval; // DerivaGem Reference Value } OptionData; _MM_ALIGN16 OptionData* data; _MM_ALIGN16 fptype* prices; int numOptions; int * otype; fptype * sptprice; fptype * strike; fptype * rate; fptype * volatility; fptype * otime; int numError = 0; int nThreads; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Cumulative Normal Distribution Function // See Hull, Section 11.8, P.243-244 #define inv_sqrt_2xPI 0.39894228040143270286 MUSTINLINE void CNDF ( fptype * OutputX, fptype * InputX ) { int sign[SIMD_WIDTH]; int i; _MMR xInput; _MMR xNPrimeofX; _MM_ALIGN16 fptype expValues[SIMD_WIDTH]; _MMR xK2; _MMR xK2_2, xK2_3, xK2_4, xK2_5; _MMR xLocal, xLocal_1, xLocal_2, xLocal_3; for (i=0; i<SIMD_WIDTH; i++) { // Check for negative value of InputX if (InputX[i] < 0.0) { InputX[i] = -InputX[i]; sign[i] = 1; } else sign[i] = 0; } // printf("InputX[0]=%lf\n", InputX[0]); // printf("InputX[1]=%lf\n", InputX[1]); xInput = _MM_LOAD(InputX); // local vars // Compute NPrimeX term common to both four & six decimal accuracy calcs for (i=0; i<SIMD_WIDTH; i++) { expValues[i] = exp(-0.5f * InputX[i] * InputX[i]); // printf("exp[%d]: %f\n", i, expValues[i]); } xNPrimeofX = _MM_LOAD(expValues); xNPrimeofX = _MM_MUL(xNPrimeofX, _MM_SET(inv_sqrt_2xPI)); xK2 = _MM_MUL(_MM_SET(0.2316419), xInput); xK2 = _MM_ADD(xK2, _MM_SET(1.0)); xK2 = _MM_DIV(_MM_SET(1.0), xK2); // xK2 = _mm_rcp_pd(xK2); // No rcp function for double-precision xK2_2 = _MM_MUL(xK2, xK2); xK2_3 = _MM_MUL(xK2_2, xK2); xK2_4 = _MM_MUL(xK2_3, xK2); xK2_5 = _MM_MUL(xK2_4, xK2); xLocal_1 = _MM_MUL(xK2, _MM_SET(0.319381530)); xLocal_2 = _MM_MUL(xK2_2, _MM_SET(-0.356563782)); xLocal_3 = _MM_MUL(xK2_3, _MM_SET(1.781477937)); xLocal_2 = _MM_ADD(xLocal_2, xLocal_3); xLocal_3 = _MM_MUL(xK2_4, _MM_SET(-1.821255978)); xLocal_2 = _MM_ADD(xLocal_2, xLocal_3); xLocal_3 = _MM_MUL(xK2_5, _MM_SET(1.330274429)); xLocal_2 = _MM_ADD(xLocal_2, xLocal_3); xLocal_1 = _MM_ADD(xLocal_2, xLocal_1); xLocal = _MM_MUL(xLocal_1, xNPrimeofX); xLocal = _MM_SUB(_MM_SET(1.0), xLocal); _MM_STORE(OutputX, xLocal); // _mm_storel_pd(&OutputX[0], xLocal); // _mm_storeh_pd(&OutputX[1], xLocal); for (i=0; i<SIMD_WIDTH; i++) { if (sign[i]) { OutputX[i] = (1.0 - OutputX[i]); } } } // For debugging void print_xmm(_MMR in, char* s) { int i; _MM_ALIGN16 fptype val[SIMD_WIDTH]; _MM_STORE(val, in); printf("%s: ", s); for (i=0; i<SIMD_WIDTH; i++) { printf("%f ", val[i]); } printf("\n"); } ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// void BlkSchlsEqEuroNoDiv (fptype * OptionPrice, int numOptions, fptype * sptprice, fptype * strike, fptype * rate, fptype * volatility, fptype * time, int * otype, float timet) { int i; // local private working variables for the calculation _MMR xStockPrice; _MMR xStrikePrice; _MMR xRiskFreeRate; _MMR xVolatility; _MMR xTime; _MMR xSqrtTime; _MM_ALIGN16 fptype logValues[NCO]; _MMR xLogTerm; _MMR xD1, xD2; _MMR xPowerTerm; _MMR xDen; _MM_ALIGN16 fptype d1[SIMD_WIDTH]; _MM_ALIGN16 fptype d2[SIMD_WIDTH]; _MM_ALIGN16 fptype FutureValueX[SIMD_WIDTH]; _MM_ALIGN16 fptype NofXd1[SIMD_WIDTH]; _MM_ALIGN16 fptype NofXd2[SIMD_WIDTH]; _MM_ALIGN16 fptype NegNofXd1[SIMD_WIDTH]; _MM_ALIGN16 fptype NegNofXd2[SIMD_WIDTH]; xStockPrice = _MM_LOAD(sptprice); xStrikePrice = _MM_LOAD(strike); xRiskFreeRate = _MM_LOAD(rate); xVolatility = _MM_LOAD(volatility); xTime = _MM_LOAD(time); xSqrtTime = _MM_SQRT(xTime); for(i=0; i<SIMD_WIDTH;i ++) { logValues[i] = log(sptprice[i] / strike[i]); } xLogTerm = _MM_LOAD(logValues); xPowerTerm = _MM_MUL(xVolatility, xVolatility); xPowerTerm = _MM_MUL(xPowerTerm, _MM_SET(0.5)); xD1 = _MM_ADD(xRiskFreeRate, xPowerTerm); xD1 = _MM_MUL(xD1, xTime); xD1 = _MM_ADD(xD1, xLogTerm); xDen = _MM_MUL(xVolatility, xSqrtTime); xD1 = _MM_DIV(xD1, xDen); xD2 = _MM_SUB(xD1, xDen); _MM_STORE(d1, xD1); _MM_STORE(d2, xD2); CNDF( NofXd1, d1 ); CNDF( NofXd2, d2 ); for (i=0; i<SIMD_WIDTH; i++) { FutureValueX[i] = strike[i] * (exp(-(rate[i])*(time[i]))); // printf("FV=%lf\n", FutureValueX[i]); // NofXd1[i] = NofX(d1[i]); // NofXd2[i] = NofX(d2[i]); // printf("NofXd1=%lf\n", NofXd1[i]); // printf("NofXd2=%lf\n", NofXd2[i]); if (otype[i] == 0) { OptionPrice[i] = (sptprice[i] * NofXd1[i]) - (FutureValueX[i] * NofXd2[i]); } else { NegNofXd1[i] = (1.0 - (NofXd1[i])); NegNofXd2[i] = (1.0 - (NofXd2[i])); OptionPrice[i] = (FutureValueX[i] * NegNofXd2[i]) - (sptprice[i] * NegNofXd1[i]); } // printf("OptionPrice[0] = %lf\n", OptionPrice[i]); } } #ifdef ENABLE_TBB struct mainWork { mainWork(){} mainWork(mainWork &w, tbb::split){} void operator()(const tbb::blocked_range<int> &range) const { fptype price[NCO]; fptype priceDelta; int begin = range.begin(); int end = range.end(); for (int i=begin; i!=end; i+=NCO) { /* Calling main function to calculate option value based on * Black & Scholes's equation. */ BlkSchlsEqEuroNoDiv( price, NCO, &(sptprice[i]), &(strike[i]), &(rate[i]), &(volatility[i]), &(otime[i]), &(otype[i]), 0); for (int k=0; k<NCO; k++) { prices[i+k] = price[k]; #ifdef ERR_CHK priceDelta = data[i+k].DGrefval - price[k]; if( fabs(priceDelta) >= 1e-5 ){ fprintf(stderr,"Error on %d. Computed=%.5f, Ref=%.5f, Delta=%.5f\n", i+k, price, data[i+k].DGrefval, priceDelta); numError ++; } #endif } } } }; #endif // ENABLE_TBB ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// #ifdef ENABLE_TBB int bs_thread(void *tid_ptr) { int j; tbb::affinity_partitioner a; mainWork doall; for (j=0; j<NUM_RUNS; j++) { tbb::parallel_for(tbb::blocked_range<int>(0, numOptions), doall, a); } return 0; } #else // !ENABLE_TBB #ifdef WIN32 DWORD WINAPI bs_thread(LPVOID tid_ptr){ #else int bs_thread(void *tid_ptr) { #endif int i, j, k; fptype price[NCO]; fptype priceDelta; int tid = *(int *)tid_ptr; int start = tid * (numOptions / nThreads); int end = start + (numOptions / nThreads); for (j=0; j<NUM_RUNS; j++) { #ifdef ENABLE_OPENMP #pragma omp parallel for private(i, price, priceDelta) for (i=0; i<numOptions; i += NCO) { #else //ENABLE_OPENMP for (i=start; i<end; i += NCO) { #endif //ENABLE_OPENMP // Calling main function to calculate option value based on Black & Scholes's // equation. BlkSchlsEqEuroNoDiv(price, NCO, &(sptprice[i]), &(strike[i]), &(rate[i]), &(volatility[i]), &(otime[i]), &(otype[i]), 0); for (k=0; k<NCO; k++) { prices[i+k] = price[k]; } #ifdef ERR_CHK for (k=0; k<NCO; k++) { priceDelta = data[i+k].DGrefval - price[k]; if (fabs(priceDelta) >= 1e-4) { printf("Error on %d. Computed=%.5f, Ref=%.5f, Delta=%.5f\n", i + k, price[k], data[i+k].DGrefval, priceDelta); numError ++; } } #endif } } return 0; } #endif //ENABLE_TBB int main (int argc, char **argv) { FILE *file; int i; int loopnum; fptype * buffer; int * buffer2; int rv; #ifdef PARSEC_VERSION #define __PARSEC_STRING(x) #x #define __PARSEC_XSTRING(x) __PARSEC_STRING(x) printf("PARSEC Benchmark Suite Version " __PARSEC_XSTRING(PARSEC_VERSION)"\n"); fflush(NULL); #else printf("PARSEC Benchmark Suite\n"); fflush(NULL); #endif //PARSEC_VERSION #ifdef ENABLE_PARSEC_HOOKS __parsec_bench_begin(__parsec_blackscholes); #endif if (argc != 4) { printf("Usage:\n\t%s <nthreads> <inputFile> <outputFile>\n", argv[0]); exit(1); } nThreads = atoi(argv[1]); char *inputFile = argv[2]; char *outputFile = argv[3]; //Read input data from file file = fopen(inputFile, "r"); if(file == NULL) { printf("ERROR: Unable to open file `%s'.\n", inputFile); exit(1); } rv = fscanf(file, "%i", &numOptions); if(rv != 1) { printf("ERROR: Unable to read from file `%s'.\n", inputFile); fclose(file); exit(1); } if(NCO > numOptions) { printf("ERROR: Not enough work for SIMD operation.\n"); fclose(file); exit(1); } if(nThreads > numOptions/NCO) { printf("WARNING: Not enough work, reducing number of threads to match number of SIMD options packets.\n"); nThreads = numOptions/NCO; } #if !defined(ENABLE_THREADS) && !defined(ENABLE_OPENMP) && !defined(ENABLE_TBB) if(nThreads != 1) { printf("Error: <nthreads> must be 1 (serial version)\n"); exit(1); } #endif data = (OptionData*)malloc(numOptions*sizeof(OptionData)); prices = (fptype*)malloc(numOptions*sizeof(fptype)); for ( loopnum = 0; loopnum < numOptions; ++ loopnum ) { rv = fscanf(file, "%f %f %f %f %f %f %c %f %f", &data[loopnum].s, &data[loopnum].strike, &data[loopnum].r, &data[loopnum].divq, &data[loopnum].v, &data[loopnum].t, &data[loopnum].OptionType, &data[loopnum].divs, &data[loopnum].DGrefval); if(rv != 9) { printf("ERROR: Unable to read from file `%s'.\n", inputFile); fclose(file); exit(1); } } rv = fclose(file); if(rv != 0) { printf("ERROR: Unable to close file `%s'.\n", inputFile); exit(1); } #ifdef ENABLE_THREADS MAIN_INITENV(,8000000,nThreads); #endif printf("Num of Options: %d\n", numOptions); printf("Num of Runs: %d\n", NUM_RUNS); #define PAD 256 #define LINESIZE 64 buffer = (fptype *) malloc(5 * numOptions * sizeof(fptype) + PAD); sptprice = (fptype *) (((unsigned long long)buffer + PAD) & ~(LINESIZE - 1)); strike = sptprice + numOptions; rate = strike + numOptions; volatility = rate + numOptions; otime = volatility + numOptions; buffer2 = (int *) malloc(numOptions * sizeof(fptype) + PAD); otype = (int *) (((unsigned long long)buffer2 + PAD) & ~(LINESIZE - 1)); for (i=0; i<numOptions; i++) { otype[i] = (data[i].OptionType == 'P') ? 1 : 0; sptprice[i] = data[i].s; strike[i] = data[i].strike; rate[i] = data[i].r; volatility[i] = data[i].v; otime[i] = data[i].t; } printf("Size of data: %d\n", numOptions * (sizeof(OptionData) + sizeof(int))); #ifdef ENABLE_PARSEC_HOOKS __parsec_roi_begin(); #endif #ifdef ENABLE_THREADS #ifdef WIN32 HANDLE *threads; int *nums; threads = (HANDLE *) malloc (nThreads * sizeof(HANDLE)); nums = (int *) malloc (nThreads * sizeof(int)); for(i=0; i<nThreads; i++) { nums[i] = i; threads[i] = CreateThread(0, 0, bs_thread, &nums[i], 0, 0); } WaitForMultipleObjects(nThreads, threads, TRUE, INFINITE); free(threads); free(nums); #else int *tids; tids = (int *) malloc (nThreads * sizeof(int)); for(i=0; i<nThreads; i++) { tids[i]=i; CREATE_WITH_ARG(bs_thread, &tids[i]); } WAIT_FOR_END(nThreads); free(tids); #endif //WIN32 #else //ENABLE_THREADS #ifdef ENABLE_OPENMP { int tid=0; omp_set_num_threads(nThreads); bs_thread(&tid); } #else //ENABLE_OPENMP #ifdef ENABLE_TBB tbb::task_scheduler_init init(nThreads); int tid=0; bs_thread(&tid); #else //ENABLE_TBB //serial version int tid=0; bs_thread(&tid); #endif //ENABLE_TBB #endif //ENABLE_OPENMP #endif //ENABLE_THREADS #ifdef ENABLE_PARSEC_HOOKS __parsec_roi_end(); #endif //Write prices to output file file = fopen(outputFile, "w"); if(file == NULL) { printf("ERROR: Unable to open file `%s'.\n", outputFile); exit(1); } rv = fprintf(file, "%i\n", numOptions); if(rv < 0) { printf("ERROR: Unable to write to file `%s'.\n", outputFile); fclose(file); exit(1); } for(i=0; i<numOptions; i++) { rv = fprintf(file, "%.18f\n", prices[i]); if(rv < 0) { printf("ERROR: Unable to write to file `%s'.\n", outputFile); fclose(file); exit(1); } } rv = fclose(file); if(rv != 0) { printf("ERROR: Unable to close file `%s'.\n", outputFile); exit(1); } #ifdef ERR_CHK printf("Num Errors: %d\n", numError); #endif free(data); free(prices); #ifdef ENABLE_PARSEC_HOOKS __parsec_bench_end(); #endif return 0; }
MD5_fmt.c
/* * This file is part of John the Ripper password cracker, * Copyright (c) 1996-2001,2008,2010-2012 by Solar Designer * * ...with changes in the jumbo patch, by bartavelle and magnum. * * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * There's ABSOLUTELY NO WARRANTY, express or implied. */ #include <string.h> #include "arch.h" #include "misc.h" #include "simd-intrinsics.h" #include "MD5_std.h" #include "common.h" #include "formats.h" #include "cryptmd5_common.h" #if defined(_OPENMP) && defined(SIMD_PARA_MD5) #ifndef OMP_SCALE #define OMP_SCALE 4 #endif #include <omp.h> #endif #include "memdbg.h" #define FORMAT_LABEL "md5crypt" #define FORMAT_NAME "crypt(3) $1$" #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define PLAINTEXT_LENGTH 15 #define CIPHERTEXT_LENGTH 22 #ifdef SIMD_PARA_MD5 #define BINARY_SIZE 16 #else #define BINARY_SIZE 4 #endif #define BINARY_ALIGN 4 #define SALT_SIZE 9 #define SALT_ALIGN 1 #define MIN_KEYS_PER_CRYPT MD5_N #define MAX_KEYS_PER_CRYPT MD5_N static struct fmt_tests tests[] = { {"$1$12345678$aIccj83HRDBo6ux1bVx7D1", "0123456789ABCDE"}, {"$apr1$Q6ZYh...$RV6ft2bZ8j.NGrxLYaJt9.", "test"}, {"$1$12345678$f8QoJuo0DpBRfQSD0vglc1", "12345678"}, {"$1$$qRPK7m23GJusamGpoGLby/", ""}, {"$apr1$a2Jqm...$grFrwEgiQleDr0zR4Jx1b.", "15 chars is max"}, {"$1$$AuJCr07mI7DSew03TmBIv/", "no salt"}, {"$1$`!@#%^&*$E6hD76/pKTS8qToBCkux30", "invalid salt"}, {"$1$12345678$xek.CpjQUVgdf/P2N9KQf/", ""}, {"$1$1234$BdIMOAWFOV2AQlLsrN/Sw.", "1234"}, {"$apr1$rBXqc...$NlXxN9myBOk95T0AyLAsJ0", "john"}, {"$apr1$Grpld/..$qp5GyjwM2dnA5Cdej9b411", "the"}, {"$apr1$GBx.D/..$yfVeeYFCIiEXInfRhBRpy/", "ripper"}, {"$1$bb$19smCEBG0Q1pVil0/HqK./", "aaaaa"}, {"$1$coin$rebm0t9KJ56mgGWJF5o5M0", "lapin"}, {"$1$pouet$/Ecz/vyk.zCYvrr6wB78h0", "canard"}, {"$1$test2$02MCIATVoxq3IhgK6XRkb1", "test1"}, {"$1$aussi$X67z3kXsWo92F15uChx1H1", "felicie"}, {"$1$boire$gf.YM2y3InYEu9.NbVr.v0", "manger"}, {"$1$bas$qvkmmWnVHRCSv/6LQ1doH/", "haut"}, {"$1$gauche$EPvd6LZlrgb0MMFPxUrJN1", "droite"}, /* following hashes are AIX non-standard smd5 hashes */ {"{smd5}s8/xSJ/v$uGam4GB8hOjTLQqvBfxJ2/", "password"}, {"{smd5}alRJaSLb$aKM3H1.h1ycXl5GEVDH1e1", "aixsucks?"}, {"{smd5}eLB0QWeS$Eg.YfWY8clZuCxF0xNrKg.", "0123456789ABCDE"}, /* following hashes are AIX standard smd5 hashes (with corrected tag) * lpa_options = std_hash=true */ {"$1$JVDbGx8K$T9h8HK4LZxeLPMTAxCfpc1", "password"}, {"$1$1Cu6fEvv$42kuaJ5fMEqyVStPuFG040", "0123456789ABCDE"}, {"$1$ql5x.xXL$vYVDhExol2xUBBpERRWcn1", "jtr>hashcat"}, {"$1$27iyq7Ya$miN09fW1Scj0DHVNyewoU/", ""}, {"$1$84Othc1n$v1cuReaa5lRdGuHaOa76n0", "a"}, {"$1$4zq0BsCR$U2ua9WZtDEhzy4gFSiLxN1", "aa"}, {"$1$DKwjKWxp$PY6PdlPZsXjOppPDoFOz4.", "aaa"}, {"$1$OKDV6ppN$viTVmH48bSePiCrMvXT/./", "aaaa"}, {"$1$QEWsCY0O$xrTTMKTepiHMp7Oxgz0pX/", "aaaaa"}, {"$1$5dfdk2dF$XiJBPNrfKcCgdQ/kcoB40/", "aaaaaa"}, {"$1$Ps6A1Cy6$WsvLg9cQhm9JU0rXkLEtz.", "aaaaaaa"}, {"$1$9IK7nZ4M$4nx7Mdj05KGPJX/mZaDrh.", "aaaaaaaa"}, {"$1$l3pNTqwT$GAc.dcRaxCvC20CFGCjp4/", "aaaaaaaaa"}, {"$1$jSAARhJR$6daQ/ekjAL0MgOUgGJyp10", "aaaaaaaaaa"}, {"$1$wk3Xwqqg$2AtdiucwJvJgbaVT1jWpb0", "aaaaaaaaaaa"}, {"$1$G6Fn69Ei$d7AKJUOIdz/gO4Utc0TQP1", "aaaaaaaaaaaa"}, {"$1$A7XJ7lGK$W5jTnH/4lW4XwZ.6F7n1N.", "aaaaaaaaaaaaa"}, {"$1$Rcm46RfA$LfdIK/OP16yHzMYHSlx/B.", "aaaaaaaaaaaaaa"}, {"$1$4bCSSJMN$TcYKTsukD4SFJE1n4MwMZ/", "aaaaaaaaaaaaaaa"}, #if PLAINTEXT_LENGTH > 15 {"$1$mJxBkkl8$u7OHfWCPmNxvf0um7hH89.", "aaaaaaaaaaaaaaaa"}, {"$1$Ub1gBUt4$TNaLxU7Pq5mk/MiDEb60b/", "aaaaaaaaaaaaaaaaa"}, {"$1$8ot7QScR$x.p4vjIgdFxxS83x29PkJ0", "aaaaaaaaaaaaaaaaaa"}, {"$1$wRi4OjD3$eJjKD2AwLMWfOTRYA30zn.", "aaaaaaaaaaaaaaaaaaa"}, {"$1$lmektrsg$2KSRY4EUFzsYNMg80fG4/0", "aaaaaaaaaaaaaaaaaaaa"}, {"$1$tgVBKBmE$YRvzsi7qHP2MC1Atg8VCV.", "aaaaaaaaaaaaaaaaaaaaa"}, {"$1$oTsk88YC$Eh435T1BQzmjQekfqkHof/", "aaaaaaaaaaaaaaaaaaaaaa"}, {"$1$ykxSZEfP$hJrFeGOFk049L.94Mgggj/", "aaaaaaaaaaaaaaaaaaaaaaa"}, {"$1$LBK4p5tD$5/gAIx8/7hpTVwDC/.KQv/", "aaaaaaaaaaaaaaaaaaaaaaaa"}, {"$1$fkEasaUI$G7CelOWHkol2nVHN8XQP40", "aaaaaaaaaaaaaaaaaaaaaaaaa"}, {"$1$gRevVzeY$eMMQrsl5OHL5dP1p/ktJc/", "aaaaaaaaaaaaaaaaaaaaaaaaaa"}, {"$1$164TNEjj$ppoV6Ju6Vu63j1OlM4zit/", "aaaaaaaaaaaaaaaaaaaaaaaaaaa"}, {"$1$ErPmhjp2$lZZstb2M455Xhk50eeH4i/", "aaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, {"$1$NUssS5fT$QaS4Ywt0IwzxbE0FAGnXn0", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, {"$1$NxlTyiJ7$gxkXTEJdeTzY8P6tqKmcz.", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, {"$1$Cmy9x7gW$kamvHI42Kh1CH4Shy6g6S/", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, {"$1$IsuapfCX$4Yq0Adq5nNZgl0LwbSl5Y0", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, {"$1$rSZfNcKX$N4XPvGrfhKsyoEcRSaqmG0", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, #endif {NULL} }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; #ifdef SIMD_PARA_MD5 static unsigned char cursalt[SALT_SIZE]; static int CryptType; static MD5_word (*sout); static int omp_para = 1; #endif static void init(struct fmt_main *self) { MD5_std_init(self); #if defined(_OPENMP) && defined(SIMD_PARA_MD5) omp_para = omp_get_max_threads(); if (omp_para < 1) omp_para = 1; self->params.min_keys_per_crypt = MD5_N * omp_para; omp_para *= OMP_SCALE; self->params.max_keys_per_crypt = MD5_N * omp_para; #elif MD5_std_mt self->params.min_keys_per_crypt = MD5_std_min_kpc; self->params.max_keys_per_crypt = MD5_std_max_kpc; #endif saved_key = mem_calloc_align(self->params.max_keys_per_crypt, sizeof(*saved_key), MEM_ALIGN_CACHE); #ifdef SIMD_PARA_MD5 sout = mem_calloc(self->params.max_keys_per_crypt, sizeof(*sout) * BINARY_SIZE); #endif } static void done(void) { #ifdef SIMD_PARA_MD5 MEM_FREE(sout); #endif MEM_FREE(saved_key); } static int get_hash_0(int index) { #ifdef SIMD_PARA_MD5 unsigned int x,y; x = index&(SIMD_COEF_32-1); y = (unsigned int)index/SIMD_COEF_32; return ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] & PH_MASK_0; #else init_t(); return MD5_out[index][0] & PH_MASK_0; #endif } static int get_hash_1(int index) { #ifdef SIMD_PARA_MD5 unsigned int x,y; x = index&(SIMD_COEF_32-1); y = (unsigned int)index/SIMD_COEF_32; return ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] & PH_MASK_1; #else init_t(); return MD5_out[index][0] & PH_MASK_1; #endif } static int get_hash_2(int index) { #ifdef SIMD_PARA_MD5 unsigned int x,y; x = index&(SIMD_COEF_32-1); y = (unsigned int)index/SIMD_COEF_32; return ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] & PH_MASK_2; #else init_t(); return MD5_out[index][0] & PH_MASK_2; #endif } static int get_hash_3(int index) { #ifdef SIMD_PARA_MD5 unsigned int x,y; x = index&(SIMD_COEF_32-1); y = (unsigned int)index/SIMD_COEF_32; return ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] & PH_MASK_3; #else init_t(); return MD5_out[index][0] & PH_MASK_3; #endif } static int get_hash_4(int index) { #ifdef SIMD_PARA_MD5 unsigned int x,y; x = index&(SIMD_COEF_32-1); y = (unsigned int)index/SIMD_COEF_32; return ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] & PH_MASK_4; #else init_t(); return MD5_out[index][0] & PH_MASK_4; #endif } static int get_hash_5(int index) { #ifdef SIMD_PARA_MD5 unsigned int x,y; x = index&(SIMD_COEF_32-1); y = (unsigned int)index/SIMD_COEF_32; return ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] & PH_MASK_5; #else init_t(); return MD5_out[index][0] & PH_MASK_5; #endif } static int get_hash_6(int index) { #ifdef SIMD_PARA_MD5 unsigned int x,y; x = index&(SIMD_COEF_32-1); y = (unsigned int)index/SIMD_COEF_32; return ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] & PH_MASK_6; #else init_t(); return MD5_out[index][0] & PH_MASK_6; #endif } static int salt_hash(void *salt) { unsigned int i, h, retval; retval = 0; for (i = 0; i <= 6; i += 2) { h = (unsigned char)atoi64[ARCH_INDEX(((char *)salt)[i])]; h ^= ((unsigned char *)salt)[i + 1]; h <<= 6; h ^= (unsigned char)atoi64[ARCH_INDEX(((char *)salt)[i + 1])]; h ^= ((unsigned char *)salt)[i]; retval += h; } retval ^= retval >> SALT_HASH_LOG; retval &= SALT_HASH_SIZE - 1; return retval; } static void set_key(char *key, int index) { #ifndef SIMD_PARA_MD5 MD5_std_set_key(key, index); #endif strnfcpy(saved_key[index], key, PLAINTEXT_LENGTH); } static char *get_key(int index) { saved_key[index][PLAINTEXT_LENGTH] = 0; return saved_key[index]; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; #ifdef SIMD_PARA_MD5 #ifdef _OPENMP int t; #pragma omp parallel for for (t = 0; t < omp_para; t++) md5cryptsse((unsigned char *)(&saved_key[t*MD5_N]), cursalt, (char *)(&sout[t*MD5_N*BINARY_SIZE/sizeof(MD5_word)]), CryptType); #else md5cryptsse((unsigned char *)saved_key, cursalt, (char *)sout, CryptType); #endif #else MD5_std_crypt(count); #endif return count; } static int cmp_all(void *binary, int count) { #ifdef SIMD_PARA_MD5 unsigned int x,y; for(y=0;y<SIMD_PARA_MD5*omp_para;y++) for(x=0;x<SIMD_COEF_32;x++) { if( ((MD5_word *)binary)[0] == ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] ) return 1; } return 0; #else #if MD5_std_mt int t, n = (count + (MD5_N - 1)) / MD5_N; #endif for_each_t(n) { #if MD5_X2 if (*(MD5_word *)binary == MD5_out[0][0] || *(MD5_word *)binary == MD5_out[1][0]) return 1; #else if (*(MD5_word *)binary == MD5_out[0][0]) return 1; #endif } return 0; #endif } static int cmp_one(void *binary, int index) { #ifdef SIMD_PARA_MD5 unsigned int x,y; x = index&(SIMD_COEF_32-1); y = (unsigned int)index/SIMD_COEF_32; if(((unsigned int*)binary)[0] != ((unsigned int*)sout)[x+y*SIMD_COEF_32*4+0*SIMD_COEF_32]) return 0; if(((unsigned int*)binary)[1] != ((unsigned int*)sout)[x+y*SIMD_COEF_32*4+1*SIMD_COEF_32]) return 0; if(((unsigned int*)binary)[2] != ((unsigned int*)sout)[x+y*SIMD_COEF_32*4+2*SIMD_COEF_32]) return 0; if(((unsigned int*)binary)[3] != ((unsigned int*)sout)[x+y*SIMD_COEF_32*4+3*SIMD_COEF_32]) return 0; return 1; #else init_t(); return *(MD5_word *)binary == MD5_out[index][0]; #endif } static int cmp_exact(char *source, int index) { #ifdef SIMD_PARA_MD5 return 1; #else init_t(); return !memcmp(MD5_std_get_binary(source), MD5_out[index], sizeof(MD5_binary)); #endif } static void set_salt(void *salt) { #ifdef SIMD_PARA_MD5 memcpy(cursalt, salt, SALT_SIZE); CryptType = cursalt[8]; cursalt[8] = 0; #endif MD5_std_set_salt(salt); } static void *get_salt(char *ciphertext) { return MD5_std_get_salt(ciphertext); } static void *get_binary(char *ciphertext) { return MD5_std_get_binary(ciphertext); } struct fmt_main fmt_MD5 = { { FORMAT_LABEL, FORMAT_NAME, "MD5 " MD5_ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, #if MD5_std_mt || defined(SIMD_PARA_MD5) FMT_OMP | #endif FMT_CASE | FMT_8_BIT, { NULL }, { md5_salt_prefix, apr1_salt_prefix, smd5_salt_prefix }, tests }, { init, done, fmt_default_reset, fmt_default_prepare, cryptmd5_common_valid, fmt_default_split, get_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } };
GB_binop__isne_uint8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__isne_uint8) // A.*B function (eWiseMult): GB (_AemultB_01__isne_uint8) // A.*B function (eWiseMult): GB (_AemultB_02__isne_uint8) // A.*B function (eWiseMult): GB (_AemultB_03__isne_uint8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__isne_uint8) // A*D function (colscale): GB (_AxD__isne_uint8) // D*A function (rowscale): GB (_DxB__isne_uint8) // C+=B function (dense accum): GB (_Cdense_accumB__isne_uint8) // C+=b function (dense accum): GB (_Cdense_accumb__isne_uint8) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isne_uint8) // C=scalar+B GB (_bind1st__isne_uint8) // C=scalar+B' GB (_bind1st_tran__isne_uint8) // C=A+scalar GB (_bind2nd__isne_uint8) // C=A'+scalar GB (_bind2nd_tran__isne_uint8) // C type: uint8_t // A type: uint8_t // B,b type: uint8_t // BinaryOp: cij = (aij != bij) #define GB_ATYPE \ uint8_t #define GB_BTYPE \ uint8_t #define GB_CTYPE \ uint8_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint8_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint8_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x != y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISNE || GxB_NO_UINT8 || GxB_NO_ISNE_UINT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__isne_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__isne_uint8) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__isne_uint8) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint8_t uint8_t bwork = (*((uint8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__isne_uint8) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__isne_uint8) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__isne_uint8) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__isne_uint8) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__isne_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__isne_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__isne_uint8) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__isne_uint8) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t x = (*((uint8_t *) x_input)) ; uint8_t *Bx = (uint8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint8_t bij = GBX (Bx, p, false) ; Cx [p] = (x != bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__isne_uint8) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t *Ax = (uint8_t *) Ax_input ; uint8_t y = (*((uint8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint8_t aij = GBX (Ax, p, false) ; Cx [p] = (aij != y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x != aij) ; \ } GrB_Info GB (_bind1st_tran__isne_uint8) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t x = (*((const uint8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij != y) ; \ } GrB_Info GB (_bind2nd_tran__isne_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t y = (*((const uint8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
convert_bsr_x_coo.c
#include "alphasparse/format.h" #include <stdlib.h> #include <alphasparse/opt.h> #include <alphasparse/util.h> #include <memory.h> alphasparse_status_t ONAME(const ALPHA_SPMAT_COO *source, ALPHA_SPMAT_BSR **dest, const ALPHA_INT block_size, const alphasparse_layout_t block_layout) { ALPHA_INT m = source->rows; ALPHA_INT n = source->cols; ALPHA_INT nnz = source->nnz; if (m % block_size != 0 || n % block_size != 0) { printf("in convert_bsr_coo , rows or cols is not divisible by block_size!!!"); return ALPHA_SPARSE_STATUS_INVALID_VALUE; } ALPHA_SPMAT_BSR *mat = alpha_malloc(sizeof(ALPHA_SPMAT_BSR)); *dest = mat; ALPHA_INT block_rows = m / block_size; ALPHA_INT block_cols = n / block_size; ALPHA_INT *block_row_offset = alpha_memalign((block_rows + 1) * sizeof(ALPHA_INT), DEFAULT_ALIGNMENT); mat->rows = block_rows; mat->cols = block_cols; mat->block_size = block_size; mat->block_layout = block_layout; mat->rows_start = block_row_offset; mat->rows_end = block_row_offset + 1; ALPHA_SPMAT_CSR *csr; check_error_return(convert_csr_coo(source, &csr)); ALPHA_INT *pos; ALPHA_INT bcl, ldp; csr_col_partition(csr, 0, m, block_size, &pos, &bcl, &ldp); mat->rows_start[0] = 0; ALPHA_INT block_nnz = 0; for (ALPHA_INT br = 0, brs = 0; brs < m; br += 1, brs += block_size) { ALPHA_INT bre = brs + block_size; for (ALPHA_INT bi = 0; bi < bcl; bi++) { bool has_non_zero = false; for (ALPHA_INT r = brs; r < bre; r++) { if (pos[index2(r, bi + 1, ldp)] - pos[index2(r, bi, ldp)] > 0) { has_non_zero = true; break; } } if (has_non_zero) { block_nnz += 1; } } mat->rows_end[br] = block_nnz; } mat->col_indx = alpha_memalign(block_nnz * sizeof(ALPHA_INT), DEFAULT_ALIGNMENT); mat->values = alpha_memalign(block_nnz * block_size * block_size * sizeof(ALPHA_Number), DEFAULT_ALIGNMENT); ALPHA_INT num_threads = alpha_get_thread_num(); ALPHA_INT* partition = alpha_malloc(sizeof(ALPHA_INT)*(num_threads+1)); balanced_partition_row_by_nnz(mat->rows_end, block_rows, num_threads, partition); #ifdef _OPENMP #pragma omp parallel num_threads(num_threads) #endif { ALPHA_INT tid = alpha_get_thread_id(); ALPHA_INT lrs = partition[tid]; ALPHA_INT lrh = partition[tid + 1]; ALPHA_INT *col_indx = &mat->col_indx[mat->rows_start[lrs]]; ALPHA_Number *values = &mat->values[mat->rows_start[lrs] * block_size * block_size]; ALPHA_INT count = mat->rows_end[lrh - 1] - mat->rows_start[lrs]; ALPHA_INT index = 0; memset(values, '\0', count * block_size * block_size * sizeof(ALPHA_Number)); for (ALPHA_INT brs = lrs * block_size; brs < lrh * block_size; brs += block_size) { ALPHA_INT bre = alpha_min(brs + block_size, lrh * block_size); for (ALPHA_INT bi = 0; bi < bcl; bi++) { bool has_non_zero = false; for (ALPHA_INT r = brs; r < bre; r++) { if (pos[index2(r, bi + 1, ldp)] - pos[index2(r, bi, ldp)] > 0) { has_non_zero = true; break; } } if (has_non_zero) { col_indx[index] = bi; ALPHA_Number *block_values = values + index * block_size * block_size; if (block_layout == ALPHA_SPARSE_LAYOUT_ROW_MAJOR) { for (ALPHA_INT r = brs; r < bre; r++) { for (ALPHA_INT ai = pos[index2(r, bi, ldp)]; ai < pos[index2(r, bi + 1, ldp)]; ai++) { ALPHA_INT ac = csr->col_indx[ai]; block_values[ac - bi * block_size] = csr->values[ai]; } block_values += block_size; } } else { for (ALPHA_INT r = brs; r < bre; r++) { ALPHA_INT block_row_index = r - brs; for (ALPHA_INT ai = pos[index2(r, bi, ldp)]; ai < pos[index2(r, bi + 1, ldp)]; ai++) { ALPHA_INT ac = csr->col_indx[ai]; ALPHA_INT block_col_index = ac - bi * block_size; block_values[index2(block_col_index, block_row_index, block_size)] = csr->values[ai]; } } } index += 1; } } } } destroy_csr(csr); alpha_free(pos); alpha_free(partition); return ALPHA_SPARSE_STATUS_SUCCESS; }
convolution_3x3_int8.h
// BUG1989 is pleased to support the open source community by supporting ncnn available. // // Copyright (C) 2019 BUG1989. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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. static void conv3x3s1_int8_sse(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const signed char *kernel = _kernel; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out0 = top_blob.channel(p); out0.fill(0); const signed char *kernel0 = (const signed char *)kernel + p * inch * 9; for (int q = 0; q < inch; q++) { int *outptr0 = out0; const signed char *img0 = bottom_blob.channel(q); const signed char *r0 = img0; const signed char *r1 = img0 + w; const signed char *r2 = img0 + w * 2; for (int i = 0; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { int sum0 = 0; sum0 += (int)r0[0] * kernel0[0]; sum0 += (int)r0[1] * kernel0[1]; sum0 += (int)r0[2] * kernel0[2]; sum0 += (int)r1[0] * kernel0[3]; sum0 += (int)r1[1] * kernel0[4]; sum0 += (int)r1[2] * kernel0[5]; sum0 += (int)r2[0] * kernel0[6]; sum0 += (int)r2[1] * kernel0[7]; sum0 += (int)r2[2] * kernel0[8]; *outptr0 += sum0; r0++; r1++; r2++; outptr0++; } r0 += 2; r1 += 2; r2 += 2; } kernel0 += 9; } } } static void conv3x3s1_winograd23_transform_kernel_int8_sse(const Mat& kernel, Mat& kernel_tm, int inch, int outch) { kernel_tm.create(4*4, inch, outch, 2ul); // G const short ktm[4][3] = { { 2, 0, 0}, { 1, 1, 1}, { 1, -1, 1}, { 0, 0, 2} }; #pragma omp parallel for for (int p = 0; p<outch; p++) { for (int q = 0; q<inch; q++) { const signed char* kernel0 = (const signed char*)kernel + p*inch * 9 + q * 9; short* kernel_tm0 = kernel_tm.channel(p).row<short>(q); // transform kernel const signed char* k0 = kernel0; const signed char* k1 = kernel0 + 3; const signed char* k2 = kernel0 + 6; // h short tmp[4][3]; for (int i=0; i<4; i++) { tmp[i][0] = (short)k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = (short)k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = (short)k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // U for (int j=0; j<4; j++) { short* tmpp = &tmp[j][0]; for (int i=0; i<4; i++) { kernel_tm0[j*4 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } } static void conv3x3s1_winograd23_int8_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 2n+2, winograd F(2,3) Mat bottom_blob_bordered = bottom_blob; outw = (outw + 1) / 2 * 2; outh = (outh + 1) / 2 * 2; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f, opt.workspace_allocator, opt.num_threads); // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 2 * 4; int h_tm = outh / 2 * 4; int nColBlocks = h_tm/4; // may be the block num in Feathercnn int nRowBlocks = w_tm/4; const int tiles = nColBlocks * nRowBlocks; bottom_blob_tm.create(4*4, tiles, inch, 2u, opt.workspace_allocator); // BT // const float itm[4][4] = { // {1.0f, 0.0f, -1.0f, 0.0f}, // {0.0f, 1.0f, 1.00f, 0.0f}, // {0.0f, -1.0f, 1.00f, 0.0f}, // {0.0f, -1.0f, 0.00f, 1.0f} // }; #pragma omp parallel for num_threads(opt.num_threads) for (int q=0; q<inch; q++) { const signed char* img = bottom_blob_bordered.channel(q); short* out_tm0 = bottom_blob_tm.channel(q); for (int j = 0; j < nColBlocks; j++) { const signed char* r0 = img + w * j * 2; const signed char* r1 = r0 + w; const signed char* r2 = r1 + w; const signed char* r3 = r2 + w; for (int i = 0; i < nRowBlocks; i++) { short d0[4],d1[4],d2[4],d3[4]; short w0[4],w1[4],w2[4],w3[4]; short t0[4],t1[4],t2[4],t3[4]; // load for (int n = 0; n < 4; n++) { d0[n] = r0[n]; d1[n] = r1[n]; d2[n] = r2[n]; d3[n] = r3[n]; } // w = B_t * d for (int n = 0; n < 4; n++) { w0[n] = d0[n] - d2[n]; w1[n] = d1[n] + d2[n]; w2[n] = d2[n] - d1[n]; w3[n] = d3[n] - d1[n]; } // transpose d to d_t { t0[0]=w0[0]; t1[0]=w0[1]; t2[0]=w0[2]; t3[0]=w0[3]; t0[1]=w1[0]; t1[1]=w1[1]; t2[1]=w1[2]; t3[1]=w1[3]; t0[2]=w2[0]; t1[2]=w2[1]; t2[2]=w2[2]; t3[2]=w2[3]; t0[3]=w3[0]; t1[3]=w3[1]; t2[3]=w3[2]; t3[3]=w3[3]; } // U = B_t * d_t for (int n = 0; n < 4; n++) { d0[n] = t0[n] - t2[n]; d1[n] = t1[n] + t2[n]; d2[n] = t2[n] - t1[n]; d3[n] = t3[n] - t1[n]; } // save to out_tm for (int n = 0; n < 4; n++) { out_tm0[n ] = d0[n]; out_tm0[n+ 4] = d1[n]; out_tm0[n+ 8] = d2[n]; out_tm0[n+12] = d3[n]; } r0 += 2; r1 += 2; r2 += 2; r3 += 2; out_tm0 += 16; } } } } bottom_blob_bordered = Mat(); // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 2 * 4; int h_tm = outh / 2 * 4; int nColBlocks = h_tm/4; // may be the block num in Feathercnn int nRowBlocks = w_tm/4; const int tiles = nColBlocks * nRowBlocks; top_blob_tm.create(16, tiles, outch, 4u, opt.workspace_allocator); int nn_outch = outch >> 2; int remain_outch_start = nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp=0; pp<nn_outch; pp++) { int p = pp * 4; Mat out0_tm = top_blob_tm.channel(p); Mat out1_tm = top_blob_tm.channel(p+1); Mat out2_tm = top_blob_tm.channel(p+2); Mat out3_tm = top_blob_tm.channel(p+3); const Mat kernel0_tm = kernel_tm.channel(p); const Mat kernel1_tm = kernel_tm.channel(p+1); const Mat kernel2_tm = kernel_tm.channel(p+2); const Mat kernel3_tm = kernel_tm.channel(p+3); for (int i=0; i<tiles; i++) { int* output0_tm = out0_tm.row<int>(i); int* output1_tm = out1_tm.row<int>(i); int* output2_tm = out2_tm.row<int>(i); int* output3_tm = out3_tm.row<int>(i); int sum0[16] = {0}; int sum1[16] = {0}; int sum2[16] = {0}; int sum3[16] = {0}; int q = 0; for (; q+3<inch; q+=4) { const short* r0 = bottom_blob_tm.channel(q).row<short>(i); const short* r1 = bottom_blob_tm.channel(q+1).row<short>(i); const short* r2 = bottom_blob_tm.channel(q+2).row<short>(i); const short* r3 = bottom_blob_tm.channel(q+3).row<short>(i); const short* k0 = kernel0_tm.row<short>(q); const short* k1 = kernel1_tm.row<short>(q); const short* k2 = kernel2_tm.row<short>(q); const short* k3 = kernel3_tm.row<short>(q); for (int n=0; n<16; n++) { sum0[n] += (int)r0[n] * k0[n]; k0 += 16; sum0[n] += (int)r1[n] * k0[n]; k0 += 16; sum0[n] += (int)r2[n] * k0[n]; k0 += 16; sum0[n] += (int)r3[n] * k0[n]; k0 -= 16 * 3; sum1[n] += (int)r0[n] * k1[n]; k1 += 16; sum1[n] += (int)r1[n] * k1[n]; k1 += 16; sum1[n] += (int)r2[n] * k1[n]; k1 += 16; sum1[n] += (int)r3[n] * k1[n]; k1 -= 16 * 3; sum2[n] += (int)r0[n] * k2[n]; k2 += 16; sum2[n] += (int)r1[n] * k2[n]; k2 += 16; sum2[n] += (int)r2[n] * k2[n]; k2 += 16; sum2[n] += (int)r3[n] * k2[n]; k2 -= 16 * 3; sum3[n] += (int)r0[n] * k3[n]; k3 += 16; sum3[n] += (int)r1[n] * k3[n]; k3 += 16; sum3[n] += (int)r2[n] * k3[n]; k3 += 16; sum3[n] += (int)r3[n] * k3[n]; k3 -= 16 * 3; } } for (; q<inch; q++) { const short* r0 = bottom_blob_tm.channel(q).row<short>(i); const short* k0 = kernel0_tm.row<short>(q); const short* k1 = kernel1_tm.row<short>(q); const short* k2 = kernel2_tm.row<short>(q); const short* k3 = kernel3_tm.row<short>(q); for (int n=0; n<16; n++) { sum0[n] += (int)r0[n] * k0[n]; sum1[n] += (int)r0[n] * k1[n]; sum2[n] += (int)r0[n] * k2[n]; sum3[n] += (int)r0[n] * k3[n]; } } for (int n=0; n<16; n++) { output0_tm[n] = sum0[n]; output1_tm[n] = sum1[n]; output2_tm[n] = sum2[n]; output3_tm[n] = sum3[n]; } } } #pragma omp parallel for num_threads(opt.num_threads) for (int p=remain_outch_start; p<outch; p++) { Mat out0_tm = top_blob_tm.channel(p); const Mat kernel0_tm = kernel_tm.channel(p); for (int i=0; i<tiles; i++) { int* output0_tm = out0_tm.row<int>(i); int sum0[16] = {0}; int q = 0; for (; q+3<inch; q+=4) { const short* r0 = bottom_blob_tm.channel(q).row<short>(i); const short* r1 = bottom_blob_tm.channel(q+1).row<short>(i); const short* r2 = bottom_blob_tm.channel(q+2).row<short>(i); const short* r3 = bottom_blob_tm.channel(q+3).row<short>(i); const short* k0 = kernel0_tm.row<short>(q); const short* k1 = kernel0_tm.row<short>(q+1); const short* k2 = kernel0_tm.row<short>(q+2); const short* k3 = kernel0_tm.row<short>(q+3); for (int n=0; n<16; n++) { sum0[n] += (int)r0[n] * k0[n]; sum0[n] += (int)r1[n] * k1[n]; sum0[n] += (int)r2[n] * k2[n]; sum0[n] += (int)r3[n] * k3[n]; } } for (; q<inch; q++) { const short* r0 = bottom_blob_tm.channel(q).row<short>(i); const short* k0 = kernel0_tm.row<short>(q); for (int n=0; n<16; n++) { sum0[n] += (int)r0[n] * k0[n]; } } for (int n=0; n<16; n++) { output0_tm[n] = sum0[n]; } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; top_blob_bordered.create(outw, outh, outch, 4u, opt.workspace_allocator); { // AT // const float itm[2][4] = { // {1.0f, 1.0f, 1.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 1.0f} // }; int w_tm = outw / 2 * 4; int h_tm = outh / 2 * 4; int nColBlocks = h_tm/4; // may be the block num in Feathercnn int nRowBlocks = w_tm/4; #pragma omp parallel for num_threads(opt.num_threads) for (int p=0; p<outch; p++) { Mat out_tm = top_blob_tm.channel(p); Mat out = top_blob_bordered.channel(p); for (int j=0; j<nColBlocks; j++) { int* outRow0 = out.row<int>(j*2); int* outRow1 = out.row<int>(j*2+1); for(int i=0; i<nRowBlocks; i++) { int* out_tile = out_tm.row<int>(j*nRowBlocks + i); int s0[4],s1[4],s2[4],s3[4]; int w0[4],w1[4]; int d0[2],d1[2],d2[2],d3[2]; int o0[2],o1[2]; // load for (int n = 0; n < 4; n++) { s0[n] = out_tile[n]; s1[n] = out_tile[n+ 4]; s2[n] = out_tile[n+ 8]; s3[n] = out_tile[n+12]; } // w = A_T * W for (int n = 0; n < 4; n++) { w0[n] = s0[n] + s1[n] + s2[n]; w1[n] = s1[n] - s2[n] + s3[n]; } // transpose w to w_t { d0[0] = w0[0]; d0[1] = w1[0]; d1[0] = w0[1]; d1[1] = w1[1]; d2[0] = w0[2]; d2[1] = w1[2]; d3[0] = w0[3]; d3[1] = w1[3]; } // Y = A_T * w_t for (int n = 0; n < 2; n++) { o0[n] = d0[n] + d1[n] + d2[n]; o1[n] = d1[n] - d2[n] + d3[n]; } // save to top blob tm,why right 2,because the G' = G*2 outRow0[0] = o0[0] >> 2; outRow0[1] = o0[1] >> 2; outRow1[0] = o1[0] >> 2; outRow1[1] = o1[1] >> 2; outRow0 += 2; outRow1 += 2; } } } } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt.blob_allocator, opt.num_threads); } static void conv3x3s1_winograd43_transform_kernel_int8_sse(const Mat& kernel, Mat& kernel_tm, int inch, int outch) { kernel_tm.create(6*6, inch, outch, 2ul); // G // const float ktm[6][3] = { // { 1.0f/4, 0.0f, 0.0f}, // { -1.0f/6, -1.0f/6, -1.0f/6}, // { -1.0f/6, 1.0f/6, -1.0f/6}, // { 1.0f/24, 1.0f/12, 1.0f/6}, // { 1.0f/24, -1.0f/12, 1.0f/6}, // { 0.0f, 0.0f, 1.0f} // }; const short ktm[6][3] = { { 6, 0, 0}, { -4, -4, -4}, { -4, 4, -4}, { 1, 2, 4}, { 1, -2, 4}, { 0, 0, 24} }; #pragma omp parallel for for (int p = 0; p<outch; p++) { for (int q = 0; q<inch; q++) { const signed char* kernel0 = (const signed char*)kernel + p*inch * 9 + q * 9; short* kernel_tm0 = kernel_tm.channel(p).row<short>(q); // transform kernel const signed char* k0 = kernel0; const signed char* k1 = kernel0 + 3; const signed char* k2 = kernel0 + 6; // h short tmp[6][3]; for (int i=0; i<6; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // U for (int j=0; j<6; j++) { short* tmpp = &tmp[j][0]; for (int i=0; i<6; i++) { kernel_tm0[j*6 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } } static void conv3x3s1_winograd43_int8_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 4n+2, winograd F(4,3) Mat bottom_blob_bordered = bottom_blob; outw = (outw + 3) / 4 * 4; outh = (outh + 3) / 4 * 4; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f, opt.workspace_allocator, opt.num_threads); // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; int nColBlocks = h_tm/6; // may be the block num in Feathercnn int nRowBlocks = w_tm/6; const int tiles = nColBlocks * nRowBlocks; bottom_blob_tm.create(6*6, tiles, inch, 2u, opt.workspace_allocator); // BT // const float itm[4][4] = { // {4.0f, 0.0f, -5.0f, 0.0f, 1.0f, 0.0f}, // {0.0f,-4.0f, -4.0f, 1.0f, 1.0f, 0.0f}, // {0.0f, 4.0f, -4.0f,-1.0f, 1.0f, 0.0f}, // {0.0f,-2.0f, -1.0f, 2.0f, 1.0f, 0.0f}, // {0.0f, 2.0f, -1.0f,-2.0f, 1.0f, 0.0f}, // {0.0f, 4.0f, 0.0f,-5.0f, 0.0f, 1.0f} // }; // 0 = 4 * r00 - 5 * r02 + r04 // 1 = -4 * (r01 + r02) + r03 + r04 // 2 = 4 * (r01 - r02) - r03 + r04 // 3 = -2 * r01 - r02 + 2 * r03 + r04 // 4 = 2 * r01 - r02 - 2 * r03 + r04 // 5 = 4 * r01 - 5 * r03 + r05 #pragma omp parallel for num_threads(opt.num_threads) for (int q=0; q<inch; q++) { const signed char* img = bottom_blob_bordered.channel(q); short* out_tm0 = bottom_blob_tm.channel(q); for (int j = 0; j < nColBlocks; j++) { const signed char* r0 = img + w * j * 4; const signed char* r1 = r0 + w; const signed char* r2 = r1 + w; const signed char* r3 = r2 + w; const signed char* r4 = r3 + w; const signed char* r5 = r4 + w; for (int i = 0; i < nRowBlocks; i++) { short d0[6],d1[6],d2[6],d3[6],d4[6],d5[6]; short w0[6],w1[6],w2[6],w3[6],w4[6],w5[6]; short t0[6],t1[6],t2[6],t3[6],t4[6],t5[6]; // load for (int n = 0; n < 6; n++) { d0[n] = r0[n]; d1[n] = r1[n]; d2[n] = r2[n]; d3[n] = r3[n]; d4[n] = r4[n]; d5[n] = r5[n]; } // w = B_t * d for (int n = 0; n < 6; n++) { w0[n] = 4*d0[n] - 5*d2[n] + d4[n]; w1[n] = -4*d1[n] - 4*d2[n] + d3[n] + d4[n]; w2[n] = 4*d1[n] - 4*d2[n] - d3[n] + d4[n]; w3[n] = -2*d1[n] - d2[n] + 2*d3[n] + d4[n]; w4[n] = 2*d1[n] - d2[n] - 2*d3[n] + d4[n]; w5[n] = 4*d1[n] - 5*d3[n] + d5[n]; } // transpose d to d_t { t0[0]=w0[0]; t1[0]=w0[1]; t2[0]=w0[2]; t3[0]=w0[3]; t4[0]=w0[4]; t5[0]=w0[5]; t0[1]=w1[0]; t1[1]=w1[1]; t2[1]=w1[2]; t3[1]=w1[3]; t4[1]=w1[4]; t5[1]=w1[5]; t0[2]=w2[0]; t1[2]=w2[1]; t2[2]=w2[2]; t3[2]=w2[3]; t4[2]=w2[4]; t5[2]=w2[5]; t0[3]=w3[0]; t1[3]=w3[1]; t2[3]=w3[2]; t3[3]=w3[3]; t4[3]=w3[4]; t5[3]=w3[5]; t0[4]=w4[0]; t1[4]=w4[1]; t2[4]=w4[2]; t3[4]=w4[3]; t4[4]=w4[4]; t5[4]=w4[5]; t0[5]=w5[0]; t1[5]=w5[1]; t2[5]=w5[2]; t3[5]=w5[3]; t4[5]=w5[4]; t5[5]=w5[5]; } // d = B_t * d_t for (int n = 0; n < 6; n++) { d0[n] = 4*t0[n] - 5*t2[n] + t4[n]; d1[n] = - 4*t1[n] - 4*t2[n] + t3[n] + t4[n]; d2[n] = 4*t1[n] - 4*t2[n] - t3[n] + t4[n]; d3[n] = - 2*t1[n] - t2[n] + 2*t3[n] + t4[n]; d4[n] = 2*t1[n] - t2[n] - 2*t3[n] + t4[n]; d5[n] = 4*t1[n] - 5*t3[n] + t5[n]; } // save to out_tm for (int n = 0; n < 6; n++) { out_tm0[n ] = d0[n]; out_tm0[n+ 6] = d1[n]; out_tm0[n+12] = d2[n]; out_tm0[n+18] = d3[n]; out_tm0[n+24] = d4[n]; out_tm0[n+30] = d5[n]; } r0 += 4; r1 += 4; r2 += 4; r3 += 4; r4 += 4; r5 += 4; out_tm0 += 36; } } } } bottom_blob_bordered = Mat(); // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; int nColBlocks = h_tm/6; // may be the block num in Feathercnn int nRowBlocks = w_tm/6; const int tiles = nColBlocks * nRowBlocks; top_blob_tm.create(36, tiles, outch, 4u, opt.workspace_allocator); #pragma omp parallel for num_threads(opt.num_threads) for (int p=0; p<outch; p++) { Mat out0_tm = top_blob_tm.channel(p); const Mat kernel0_tm = kernel_tm.channel(p); for (int i=0; i<tiles; i++) { int* output0_tm = out0_tm.row<int>(i); int sum0[36] = {0}; for (int q=0; q<inch; q++) { const short* r0 = bottom_blob_tm.channel(q).row<short>(i); const short* k0 = kernel0_tm.row<short>(q); for (int n=0; n<36; n++) { sum0[n] += (int)r0[n] * k0[n]; } } for (int n=0; n<36; n++) { output0_tm[n] = sum0[n]; } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; top_blob_bordered.create(outw, outh, outch, 4u, opt.workspace_allocator); { // AT // const float itm[4][6] = { // {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 1.0f} // }; // 0 = r00 + r01 + r02 + r03 + r04 // 1 = r01 - r02 + 2 * (r03 - r04) // 2 = r01 + r02 + 4 * (r03 + r04) // 3 = r01 - r02 + 8 * (r03 - r04) + r05 int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; int nColBlocks = h_tm/6; // may be the block num in Feathercnn int nRowBlocks = w_tm/6; #pragma omp parallel for num_threads(opt.num_threads) for (int p=0; p<outch; p++) { Mat out_tm = top_blob_tm.channel(p); Mat out = top_blob_bordered.channel(p); for (int j=0; j<nColBlocks; j++) { int* outRow0 = out.row<int>(j*4); int* outRow1 = out.row<int>(j*4+1); int* outRow2 = out.row<int>(j*4+2); int* outRow3 = out.row<int>(j*4+3); for(int i=0; i<nRowBlocks; i++) { int* out_tile = out_tm.row<int>(j*nRowBlocks + i); int s0[6],s1[6],s2[6],s3[6],s4[6],s5[6]; int w0[6],w1[6],w2[6],w3[6]; int d0[4],d1[4],d2[4],d3[4],d4[4],d5[4]; int o0[4],o1[4],o2[4],o3[4]; // load for (int n = 0; n < 6; n++) { s0[n] = out_tile[n]; s1[n] = out_tile[n+ 6]; s2[n] = out_tile[n+12]; s3[n] = out_tile[n+18]; s4[n] = out_tile[n+24]; s5[n] = out_tile[n+30]; } // w = A_T * W for (int n = 0; n < 6; n++) { w0[n] = s0[n] + s1[n] + s2[n] + s3[n] + s4[n]; w1[n] = s1[n] - s2[n] + 2*s3[n] - 2*s4[n]; w2[n] = s1[n] + s2[n] + 4*s3[n] + 4*s4[n]; w3[n] = s1[n] - s2[n] + 8*s3[n] - 8*s4[n] + s5[n]; } // transpose w to w_t { d0[0] = w0[0]; d0[1] = w1[0]; d0[2] = w2[0]; d0[3] = w3[0]; d1[0] = w0[1]; d1[1] = w1[1]; d1[2] = w2[1]; d1[3] = w3[1]; d2[0] = w0[2]; d2[1] = w1[2]; d2[2] = w2[2]; d2[3] = w3[2]; d3[0] = w0[3]; d3[1] = w1[3]; d3[2] = w2[3]; d3[3] = w3[3]; d4[0] = w0[4]; d4[1] = w1[4]; d4[2] = w2[4]; d4[3] = w3[4]; d5[0] = w0[5]; d5[1] = w1[5]; d5[2] = w2[5]; d5[3] = w3[5]; } // Y = A_T * w_t for (int n = 0; n < 4; n++) { o0[n] = d0[n] + d1[n] + d2[n] + d3[n] + d4[n]; o1[n] = d1[n] - d2[n] + 2*d3[n] - 2*d4[n]; o2[n] = d1[n] + d2[n] + 4*d3[n] + 4*d4[n]; o3[n] = d1[n] - d2[n] + 8*d3[n] - 8*d4[n] + d5[n]; } // save to top blob tm for (int n = 0; n < 4; n++) { outRow0[n] = o0[n] / 576; outRow1[n] = o1[n] / 576; outRow2[n] = o2[n] / 576; outRow3[n] = o3[n] / 576; } outRow0 += 4; outRow1 += 4; outRow2 += 4; outRow3 += 4; } } } } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt.blob_allocator, opt.num_threads); } static void conv3x3s2_int8_sse(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2 * outw + w; const signed char *kernel = _kernel; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out0 = top_blob.channel(p); out0.fill(0); const signed char *kernel0 = (const signed char *)kernel + p * inch * 9; for (int q = 0; q < inch; q++) { int *outptr0 = out0; const signed char *img0 = bottom_blob.channel(q); const signed char *r0 = img0; const signed char *r1 = img0 + w; const signed char *r2 = img0 + w * 2; for (int i = 0; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { int sum0 = 0; sum0 += (int)r0[0] * kernel0[0]; sum0 += (int)r0[1] * kernel0[1]; sum0 += (int)r0[2] * kernel0[2]; sum0 += (int)r1[0] * kernel0[3]; sum0 += (int)r1[1] * kernel0[4]; sum0 += (int)r1[2] * kernel0[5]; sum0 += (int)r2[0] * kernel0[6]; sum0 += (int)r2[1] * kernel0[7]; sum0 += (int)r2[2] * kernel0[8]; *outptr0 += sum0; r0 += 2; r1 += 2; r2 += 2; outptr0++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } kernel0 += 9; } } } static void conv3x3s1_int8_dequant_sse(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel, const Mat &_bias, std::vector<float> scales_dequant, const Option& opt) { int kernel_w = 3; int kernel_h = 3; int stride_w = 1; int stride_h = 1; conv_im2col_sgemm_int8_dequant_sse(bottom_blob, top_blob, _kernel, kernel_w, kernel_h, stride_w, stride_h, _bias, scales_dequant, opt); } static void conv3x3s2_int8_dequant_sse(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel, const Mat &_bias, std::vector<float> scales_dequant, const Option& opt) { int kernel_w = 3; int kernel_h = 3; int stride_w = 2; int stride_h = 2; conv_im2col_sgemm_int8_dequant_sse(bottom_blob, top_blob, _kernel, kernel_w, kernel_h, stride_w, stride_h, _bias, scales_dequant, opt); } static void conv3x3s1_int8_requant_sse(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel, const Mat &_bias, std::vector<float> scales_requant, const Option& opt) { int kernel_w = 3; int kernel_h = 3; int stride_w = 1; int stride_h = 1; conv_im2col_sgemm_int8_requant_sse(bottom_blob, top_blob, _kernel, kernel_w, kernel_h, stride_w, stride_h, _bias, scales_requant, opt); } static void conv3x3s2_int8_requant_sse(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel, const Mat &_bias, std::vector<float> scales_requant, const Option& opt) { int kernel_w = 3; int kernel_h = 3; int stride_w = 2; int stride_h = 2; conv_im2col_sgemm_int8_requant_sse(bottom_blob, top_blob, _kernel, kernel_w, kernel_h, stride_w, stride_h, _bias, scales_requant, opt); }
bml_transpose_dense_typed.c
#ifdef BML_USE_MAGMA #include "magma_v2.h" #endif #include "../../macros.h" #include "../../typed.h" #include "../bml_allocate.h" #include "../bml_parallel.h" #include "../bml_transpose.h" #include "../bml_types.h" #include "bml_allocate_dense.h" #include "bml_transpose_dense.h" #include "bml_types_dense.h" #include <complex.h> #include <stdlib.h> #include <string.h> #include <math.h> #ifdef _OPENMP #include <omp.h> #endif /** Transpose a matrix. * * \ingroup transpose_group * * \param A The matrix to be transposed * \return The transposed A */ bml_matrix_dense_t *TYPED_FUNC( bml_transpose_new_dense) ( bml_matrix_dense_t * A) { int N = A->N; bml_matrix_dimension_t matrix_dimension = { A->N, A->N, A->N }; bml_matrix_dense_t *B = TYPED_FUNC(bml_zero_matrix_dense) (matrix_dimension, A->distribution_mode); REAL_T *A_matrix = A->matrix; REAL_T *B_matrix = B->matrix; int *A_localRowMin = A->domain->localRowMin; int *A_localRowMax = A->domain->localRowMax; int myRank = bml_getMyRank(); #ifdef BML_USE_MAGMA MAGMABLAS(transpose) (A->N, A->N, A->matrix, A->ld, B->matrix, B->ld, bml_queue()); #else #pragma omp parallel for \ shared(N, A_matrix, B_matrix) \ shared(A_localRowMin, A_localRowMax, myRank) //for (int i = 0; i < N; i++) for (int i = A_localRowMin[myRank]; i < A_localRowMax[myRank]; i++) { for (int j = 0; j < N; j++) { B_matrix[ROWMAJOR(i, j, N, N)] = A_matrix[ROWMAJOR(j, i, N, N)]; } } #endif return B; } /** Transpose a matrix in place. * * \ingroup transpose_group * * \param A The matrix to be transposed * \return The transposed A */ void TYPED_FUNC( bml_transpose_dense) ( bml_matrix_dense_t * A) { int N = A->N; #ifdef BML_USE_MAGMA MAGMABLAS(transpose_inplace) (A->N, A->matrix, A->ld, bml_queue()); #else REAL_T *A_matrix = A->matrix; REAL_T tmp; #pragma omp parallel for \ private(tmp) \ shared(N, A_matrix) for (int i = 0; i < N - 1; i++) { for (int j = i + 1; j < N; j++) { if (i != j) { tmp = A_matrix[ROWMAJOR(i, j, N, N)]; A_matrix[ROWMAJOR(i, j, N, N)] = A_matrix[ROWMAJOR(j, i, N, N)]; A_matrix[ROWMAJOR(j, i, N, N)] = tmp; } } } #endif }
convolution_sgemm_int8.h
// BUG1989 is pleased to support the open source community by supporting ncnn available. // // Copyright (C) 2019 BUG1989. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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. #if __aarch64__ #if 1 #include "gemm_symm_int8.h" static void conv_im2col_sgemm_transform_kernel_int8_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_size) { const int m = outch; const int k = inch * kernel_size; kernel_tm.create(m * k, (size_t)1u); const int8_t *a = _kernel; int8_t *sa = kernel_tm; reorder_a((int8_t*)a, sa, m, k, k); } static void conv_im2col_sgemm_int8_neon(const Mat &bottom_blob, Mat &top_blob, const Mat &kernel_tm, \ const int kernel_w, const int kernel_h, const int stride_w, const int stride_h, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // im2col Mat bottom_im2col(outw*outh, kernel_h*kernel_w*inch, 1UL, opt.workspace_allocator); { const int stride = kernel_h*kernel_w*outw*outh; signed char* ret = (signed char*)bottom_im2col; #pragma omp parallel for num_threads(opt.num_threads) for (int p=0; p<inch; p++) { const signed char* input = bottom_blob.channel(p); int retID = stride * p; for (int u=0; u<kernel_h; u++) { for (int v=0; v<kernel_w; v++) { for (int i=0; i<outh; i++) { for (int j=0; j<outw; j++) { int row = u + i * stride_h; int col = v + j * stride_w; int index = row * w + col; ret[retID] = input[index]; retID++; } } } } } } const int m = outch; const int n = outw * outh; const int k = inch * kernel_w * kernel_h; ncnn::Mat bottom_tm(k * n, (size_t)1u, opt.workspace_allocator); { const int8_t *pData = bottom_im2col; int8_t *pReorder = bottom_tm; reorder_b(pData, pReorder, k, n, n); } // GEMM int32_t *pc = top_blob; const int8_t *pa = kernel_tm; int8_t *pb = bottom_tm; const size_t ldc = top_blob.cstep; int8kernel((void*)pc, pa, pb, m, k, n, ldc, nullptr, nullptr, opt); } #else static void conv_im2col_sgemm_transform_kernel_int8_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_size) { const signed char* kernel = _kernel; // kernel memory packed 4 x 4 kernel_tm.create(4*kernel_size, inch, outch/4 + outch%4, (size_t)1u); int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 2; remain_outch_start = nn_outch << 2; for (int pp=0; pp<nn_outch; pp++) { int p = pp * 4; const signed char* k0 = kernel + (p+0)*inch*kernel_size; const signed char* k1 = kernel + (p+1)*inch*kernel_size; const signed char* k2 = kernel + (p+2)*inch*kernel_size; const signed char* k3 = kernel + (p+3)*inch*kernel_size; signed char* ktmp = kernel_tm.channel(p/4); int q=0; for (; q+1<inch*kernel_size; q+=2) { ktmp[0] = k0[0]; ktmp[1] = k0[1]; ktmp[2] = k1[0]; ktmp[3] = k1[1]; ktmp[4] = k2[0]; ktmp[5] = k2[1]; ktmp[6] = k3[0]; ktmp[7] = k3[1]; ktmp += 8; k0 += 2; k1 += 2; k2 += 2; k3 += 2; } for (; q<inch*kernel_size; q++) { ktmp[0] = k0[0]; ktmp[1] = k1[0]; ktmp[2] = k2[0]; ktmp[3] = k3[0]; ktmp += 4; k0 += 1; k1 += 1; k2 += 1; k3 += 1; } } for (int p=remain_outch_start; p<outch; p++) { const signed char* k0 = kernel + (p+0)*inch*kernel_size; signed char* ktmp = kernel_tm.channel(p/4 + p%4); int q=0; for (; q+1<inch*kernel_size; q=q+2) { ktmp[0] = k0[0]; ktmp[1] = k0[1]; ktmp += 2; k0 += 2; } for (; q<inch*kernel_size; q++) { ktmp[0] = k0[0]; ktmp++; k0++; } } } static void conv_im2col_sgemm_int8_neon(const Mat &bottom_blob, Mat &top_blob, const Mat &kernel_tm, \ const int kernel_w, const int kernel_h, const int stride_w, const int stride_h, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // im2row Mat bottom_im2row(kernel_h*kernel_w*inch, outw*outh, 1UL, opt.workspace_allocator); { int out_stride = kernel_h*kernel_w*inch*outw; signed char* ret = (signed char*)bottom_im2row; // #pragma omp parallel for num_threads(opt.num_threads) for (int i=0; i<outh; i++) { int retID = out_stride * i; for (int j=0; j<outw; j++) { for (int p=0; p<inch; p++) { const signed char* input = bottom_blob.channel(p); for (int u=0; u<kernel_h; u++) { for (int v=0; v<kernel_w; v++) { int row = u + i * stride_h; int col = v + j * stride_w; int index = row * w + col; ret[retID] = input[index]; retID++; } } } } } } int kernel_size = kernel_w * kernel_h; int out_size = outw * outh; // int M = outch; // outch int N = outw * outh; // outsize or out stride int K = kernel_w * kernel_h * inch; // ksize * inch // bottom_im2row memory packed 4 x 4 Mat bottom_tm(4*kernel_size, inch, out_size/4 + out_size%4, (size_t)1u, opt.workspace_allocator); { int nn_size = out_size >> 2; int remain_size_start = nn_size << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int ii=0; ii<nn_size; ii++) { int i = ii * 4; const signed char* img0 = bottom_im2row.row<signed char>(i); const signed char* img1 = bottom_im2row.row<signed char>(i+1); const signed char* img2 = bottom_im2row.row<signed char>(i+2); const signed char* img3 = bottom_im2row.row<signed char>(i+3); signed char* tmpptr = bottom_tm.channel(i/4); int q = 0; for (; q+1<inch*kernel_size; q=q+2) { tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr[2] = img1[0]; tmpptr[3] = img1[1]; tmpptr[4] = img2[0]; tmpptr[5] = img2[1]; tmpptr[6] = img3[0]; tmpptr[7] = img3[1]; tmpptr += 8; img0 += 2; img1 += 2; img2 += 2; img3 += 2; } for (; q<inch*kernel_size; q++) { tmpptr[0] = img0[0]; tmpptr[1] = img1[0]; tmpptr[2] = img2[0]; tmpptr[3] = img3[0]; tmpptr += 4; img0 += 1; img1 += 1; img2 += 1; img3 += 1; } } #pragma omp parallel for num_threads(opt.num_threads) for (int i=remain_size_start; i<out_size; i++) { const signed char* img0 = bottom_im2row.row<signed char>(i); signed char* tmpptr = bottom_tm.channel(i/4 + i%4); int q=0; for (; q+1<inch*kernel_size; q=q+2) { tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr += 2; img0 += 2; } for (; q<inch*kernel_size; q++) { tmpptr[0] = img0[0]; tmpptr += 1; img0 += 1; } } } // 4x4 // sgemm(int M, int N, int K, float* A, float* B, float* C) { // int M = outch; // outch // int N = outw * outh; // outsize or out stride // int L = kernel_w * kernel_h * inch; // ksize * inch int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 2; remain_outch_start = nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp=0; pp<nn_outch; pp++) { int i = pp * 4; int* output0 = top_blob.channel(i); int* output1 = top_blob.channel(i+1); int* output2 = top_blob.channel(i+2); int* output3 = top_blob.channel(i+3); int j=0; for (; j+3<N; j=j+4) { const signed char* vb = bottom_tm.channel(j/4); const signed char* va = kernel_tm.channel(i/4); #if __ARM_NEON asm volatile( "prfm pldl1keep, [%4, #128] \n" "prfm pldl1keep, [%5, #128] \n" "eor v16.16b, v16.16b, v16.16b \n" // sum0 "eor v17.16b, v17.16b, v17.16b \n" // sum1 "eor v18.16b, v18.16b, v18.16b \n" // sum2 "eor v19.16b, v19.16b, v19.16b \n" // sum3 "lsr w4, %w12, #2 \n"// r4 = nn = L >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n"// for (; k+3<L; k=k+4) "ld1 {v0.16b}, [%4] \n"// i0, i1, i2, i3 "ld1 {v4.16b}, [%5] \n"// k0, k1, k2, k3 "add %4, %4, #16 \n" "add %5, %5, #16 \n" "rev32 v1.8h, v0.8h \n"// i1, i0, i3, i2 "rev64 v2.4s, v0.4s \n"// i2, i3, i0, i1 "rev64 v3.8h, v0.8h \n"// i3, i2, i1, i0 "smull v8.8h, v4.8b, v0.8b \n" "smull v9.8h, v4.8b, v1.8b \n" "smull v10.8h, v4.8b, v2.8b \n" "smull v11.8h, v4.8b, v3.8b \n" "prfm pldl1keep, [%4, #128] \n" "prfm pldl1keep, [%5, #128] \n" "smlal2 v8.8h, v4.16b, v0.16b \n" "smlal2 v9.8h, v4.16b, v1.16b \n" "smlal2 v10.8h, v4.16b, v2.16b \n" "smlal2 v11.8h, v4.16b, v3.16b \n" "sadalp v16.4s, v8.8h \n"// i0k0, i1k1, i2k2, i3k3 "sadalp v17.4s, v9.8h \n"// i1k0, i0k1, i3k2, i2k3 "sadalp v18.4s, v10.8h \n"// i2k0, i3k1, i0k2, i1k3 "sadalp v19.4s, v11.8h \n"// i3k0, i2k1, i1k2, i0k3 "subs w4, w4, #1 \n" "bne 0b \n" "1: \n"// for (; k+1<L; k=k+2) // remain loop "and w4, %w12, #3 \n"// w4 = remain = K & 3; "cmp w4, #0 \n" "beq 3f \n" "lsr w4, w4, #1 \n"// r4 = nn = L >> 1 "cmp w4, #0 \n" "beq 3f \n" "2: \n"// for (; k+1<L; k=k+2) "ld1 {v0.8b}, [%4] \n"// i0, i1, i2, i3 "ld1 {v4.8b}, [%5] \n"// k0, k1, k2, k3 "add %4, %4, #8 \n" "add %5, %5, #8 \n" "rev32 v1.4h, v0.4h \n"// i2, i3, i0, i1 "rev64 v2.2s, v0.2s \n"// i1, i0, i3, i2 "rev64 v3.4h, v0.4h \n"// i0, i1, i2, i3 "smull v8.8h, v4.8b, v0.8b \n" "smull v9.8h, v4.8b, v1.8b \n" "smull v10.8h, v4.8b, v2.8b \n" "smull v11.8h, v4.8b, v3.8b \n" "sadalp v16.4s, v8.8h \n" "sadalp v17.4s, v9.8h \n" "sadalp v18.4s,v10.8h \n" "sadalp v19.4s,v11.8h \n" "subs w4, w4, #1 \n" "bne 2b \n" "3: \n"// realloc "mov v20.s[0], v16.s[0] \n" "mov v20.s[1], v17.s[0] \n" "mov v20.s[2], v18.s[0] \n" "mov v20.s[3], v19.s[0] \n" "mov v21.s[0], v17.s[1] \n" "mov v21.s[1], v16.s[1] \n" "mov v21.s[2], v19.s[1] \n" "mov v21.s[3], v18.s[1] \n" "mov v22.s[0], v18.s[2] \n" "mov v22.s[1], v19.s[2] \n" "mov v22.s[2], v16.s[2] \n" "mov v22.s[3], v17.s[2] \n" "mov v23.s[0], v19.s[3] \n" "mov v23.s[1], v18.s[3] \n" "mov v23.s[2], v17.s[3] \n" "mov v23.s[3], v16.s[3] \n" "and w4, %w12, #1 \n"// w4 = remain = K & 1; "cmp w4, #0 \n" "beq 5f \n" "4: \n" "ld1 {v0.8b}, [%4] \n" "ld1 {v1.8b}, [%5] \n" "add %4, %4, #4 \n" "add %5, %5, #4 \n" "sshll v0.8h, v0.8b, #0 \n"// i0[0], i1[0], i2[0], i3[0] "sshll v1.8h, v1.8b, #0 \n"// k0[0], k1[0], k2[0], k3[0] "smlal v20.4s, v0.4h, v1.h[0] \n"// i0k0, i1k0, i2k0, i3k0 "smlal v21.4s, v0.4h, v1.h[1] \n"// i0k1, i1k1, i2k1, i3k1 "smlal v22.4s, v0.4h, v1.h[2] \n"// i0k2, i1k2, i2k2, i3k2 "smlal v23.4s, v0.4h, v1.h[3] \n"// i0k3, i1k3, i2k3, i3k3 "subs w4, w4, #1 \n" "bne 2b \n" "5: \n" "st1 {v20.4s}, [%0] \n" "st1 {v21.4s}, [%1] \n" "st1 {v22.4s}, [%2] \n" "st1 {v23.4s}, [%3] \n" : "=r"(output0), // %0 "=r"(output1), // %1 "=r"(output2), // %2 "=r"(output3), // %3 "=r"(vb), // %4 "=r"(va) // %5 : "0"(output0), "1"(output1), "2"(output2), "3"(output3), "4"(vb), "5"(va), "r"(K) // %12 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23" ); #else int sum0[4] = {0}; int sum1[4] = {0}; int sum2[4] = {0}; int sum3[4] = {0}; int k=0; for (; k+1<K; k=k+2) { for (int n=0; n<4; n++) { sum0[n] += (int)va[0] * vb[2*n]; // k0 sum0[n] += (int)va[1] * vb[2*n+1]; sum1[n] += (int)va[2] * vb[2*n]; // k1 sum1[n] += (int)va[3] * vb[2*n+1]; sum2[n] += (int)va[4] * vb[2*n]; // k2 sum2[n] += (int)va[5] * vb[2*n+1]; sum3[n] += (int)va[6] * vb[2*n]; // k3 sum3[n] += (int)va[7] * vb[2*n+1]; } va += 8; vb += 8; } for (; k<K; k++) { for (int n=0; n<4; n++) { sum0[n] += (int)va[0] * vb[n]; sum1[n] += (int)va[1] * vb[n]; sum2[n] += (int)va[2] * vb[n]; sum3[n] += (int)va[3] * vb[n]; } va += 4; vb += 4; } for (int n=0; n<4; n++) { output0[n] = sum0[n]; output1[n] = sum1[n]; output2[n] = sum2[n]; output3[n] = sum3[n]; } #endif output0 += 4; output1 += 4; output2 += 4; output3 += 4; } for (; j<N; j++) { const signed char* vb = bottom_tm.channel(j/4 + j%4); const signed char* va = kernel_tm.channel(i/4); #if 0//__ARM_NEON int32x4_t _sum = vdupq_n_s32(0); int k=0; for (; k+3<K; k=k+4) { int8x8_t _r0 = vld1_s8(vb); // i0[0-3] int8x8x2_t _k = vld2_s8(va); // k0[0-1], k1[0-1], k2[0-1], k3[0-1];k0[2-3], k1[2-3], k2[2-3], k3[2-3] int16x8_t _r0_s16 = vmovl_s8(_r0); // i0[0],i0[1],i0[2],i0[3] int16x8_t _k02_s16 = vmovl_s8(_k.val[0]); // k0[0],k1[0],k2[0],k3[0],k0[2],k1[2],k2[2],k3[2] int16x8_t _k13_s16 = vmovl_s8(_k.val[1]); // k0[1],k1[1],k2[1],k3[1],k0[3],k1[3],k2[3],k3[3] _sum = vmlal_lane_s16(_sum, vget_low_s16(_k02_s16), vget_low_s16(_r0_s16), 0); // i0[0]*k[0-3][0] _sum = vmlal_lane_s16(_sum, vget_low_s16(_k13_s16), vget_low_s16(_r0_s16), 1); // i0[1]*k[0-3][1] _sum = vmlal_lane_s16(_sum, vget_high_s16(_k02_s16), vget_low_s16(_r0_s16), 2); // i0[2]*k[0-3][2] _sum = vmlal_lane_s16(_sum, vget_high_s16(_k13_s16), vget_low_s16(_r0_s16), 3); // i0[3]*k[0-3][3] va += 16; vb += 4; } for (; k+1<K; k=k+2) { int8x8_t _r0 = vld1_s8(vb); // i0[0-3] int8x8_t _k = vld1_s8(va); // k0[0-1], k1[0-1], k2[0-1], k3[0-1] _r0[2] = _r0[0]; _r0[3] = _r0[1]; _r0[4] = _r0[0]; _r0[5] = _r0[1]; _r0[6] = _r0[0]; _r0[7] = _r0[1]; int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vpadalq_s16(_sum, _tp0); va += 8; vb += 2; } for (; k<K; k++) { int8x8_t _r0 = vld1_s8(vb); // i0[0-3] int8x8_t _k = vld1_s8(va); // k[0-3][0] int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vaddw_s16(_sum, vget_low_s16(_tp0)); va += 4; vb += 1; } vst1q_lane_s32(output0, _sum, 0); vst1q_lane_s32(output1, _sum, 1); vst1q_lane_s32(output2, _sum, 2); vst1q_lane_s32(output3, _sum, 3); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; int k=0; for (; k+1<K; k=k+2) { sum0 += (int)va[0] * vb[0]; sum0 += (int)va[1] * vb[1]; sum1 += (int)va[2] * vb[0]; sum1 += (int)va[3] * vb[1]; sum2 += (int)va[4] * vb[0]; sum2 += (int)va[5] * vb[1]; sum3 += (int)va[6] * vb[0]; sum3 += (int)va[7] * vb[1]; va += 8; vb += 2; } for (; k<K; k++) { sum0 += (int)va[0] * vb[0]; sum1 += (int)va[1] * vb[0]; sum2 += (int)va[2] * vb[0]; sum3 += (int)va[3] * vb[0]; va += 4; vb += 1; } output0[0] = sum0; output1[0] = sum1; output2[0] = sum2; output3[0] = sum3; #endif output0++; output1++; output2++; output3++; } } #pragma omp parallel for num_threads(opt.num_threads) for (int i=remain_outch_start; i<outch; i++) { int* output = top_blob.channel(i); int j=0; for (; j+3<N; j=j+4) { const signed char* vb = bottom_tm.channel(j/4); const signed char* va = kernel_tm.channel(i/4 + i%4); #if __ARM_NEON int32x4_t _sum = vdupq_n_s32(0); int k=0; for (; k+1<K; k=k+2) { int8x8_t _r0 = vld1_s8(vb); // i0[0-1], i1[0-1], i2[0-1], i3[0-1] int8x8_t _k = vld1_s8(va); // k0[0-1] _k[2] = _k[0]; _k[3] = _k[1]; _k[4] = _k[0]; _k[5] = _k[1]; _k[6] = _k[0]; _k[7] = _k[1]; int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vpadalq_s16(_sum, _tp0); va += 2; vb += 8; } for (; k<K; k++) { int8x8_t _r0 = vld1_s8(vb); // i0[0], i1[0], i2[0], i3[0] int8x8_t _k = vld1_s8(va); // k[0][0] int16x8_t _r0_s16 = vmovl_s8(_r0); int16x8_t _k_s16 = vmovl_s8(_k); _sum = vmlal_lane_s16(_sum, vget_low_s16(_r0_s16), vget_low_s16(_k_s16), 0); // i0k0, i1k0, i2k0, i3k0 va += 1; vb += 4; } vst1q_s32(output, _sum); #else int sum[4] = {0}; int k=0; for (; k+1<K; k=k+2) { for (int n=0; n<4; n++) { sum[n] += (int)va[0] * vb[2*n]; sum[n] += (int)va[1] * vb[2*n+1]; } va += 2; vb += 8; } for (; k<K; k++) { for (int n=0; n<4; n++) { sum[n] += (int)va[0] * vb[n]; } va += 1; vb += 4; } for (int n=0; n<4; n++) { output[n] = sum[n]; } #endif output += 4; } for (; j<N; j++) { int sum = 0; const signed char* vb = bottom_tm.channel(j/4 + j%4); const signed char* va = kernel_tm.channel(i/4 + i%4); for (int k=0; k<K; k++) { sum += (int)va[0] * vb[0]; va += 1; vb += 1; } output[0] = sum; output++; } } } // // sgemm(int M, int N, int K, float* A, float* B, float* C) // { // for (int i=0; i<M; i++) // { // int* output = top_blob.channel(i); // for (int j=0; j<N; j++) // { // int sum = 0; // signed char* vb = (signed char*)bottom_im2row + K * j; // const signed char* va = kernel + K * i; // for (int k=0; k<K; k++) // { // sum += (int)va[0] * vb[0]; // va += 1; // vb += 1; // } // output[0] = sum; // output++; // } // } // } } #endif #else static void conv_im2col_sgemm_transform_kernel_int8_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_size) { const signed char* kernel = _kernel; #if __ARM_NEON && __aarch64__ // kernel memory packed 8 x 8 kernel_tm.create(8*kernel_size, inch, outch/8 + (outch%8)/4 + outch%4, (size_t)1u); #else // kernel memory packed 4 x 8 kernel_tm.create(4*kernel_size, inch, outch/4 + outch%4, (size_t)1u); #endif int nn_outch = 0; int remain_outch_start = 0; #if __ARM_NEON && __aarch64__ nn_outch = outch >> 3; remain_outch_start = nn_outch << 3; for (int pp=0; pp<nn_outch; pp++) { int p = pp * 8; const signed char* k0 = kernel + (p+0)*inch*kernel_size; const signed char* k1 = kernel + (p+1)*inch*kernel_size; const signed char* k2 = kernel + (p+2)*inch*kernel_size; const signed char* k3 = kernel + (p+3)*inch*kernel_size; const signed char* k4 = kernel + (p+4)*inch*kernel_size; const signed char* k5 = kernel + (p+5)*inch*kernel_size; const signed char* k6 = kernel + (p+6)*inch*kernel_size; const signed char* k7 = kernel + (p+7)*inch*kernel_size; signed char* ktmp = kernel_tm.channel(p/8); for (int q=0; q<inch*kernel_size; q++) { ktmp[0] = k0[0]; ktmp[1] = k1[0]; ktmp[2] = k2[0]; ktmp[3] = k3[0]; ktmp[4] = k4[0]; ktmp[5] = k5[0]; ktmp[6] = k6[0]; ktmp[7] = k7[0]; ktmp += 8; k0 += 1; k1 += 1; k2 += 1; k3 += 1; k4 += 1; k5 += 1; k6 += 1; k7 += 1; } } #endif nn_outch = (outch - remain_outch_start) >> 2; for (int pp=0; pp<nn_outch; pp++) { int p = remain_outch_start + pp * 4; const signed char* k0 = kernel + (p+0)*inch*kernel_size; const signed char* k1 = kernel + (p+1)*inch*kernel_size; const signed char* k2 = kernel + (p+2)*inch*kernel_size; const signed char* k3 = kernel + (p+3)*inch*kernel_size; #if __ARM_NEON && __aarch64__ signed char* ktmp = kernel_tm.channel(p/8 + (p%8)/4); #else signed char* ktmp = kernel_tm.channel(p/4); #endif // __ARM_NEON && __aarch64__ for (int q=0; q<inch*kernel_size; q++) { ktmp[0] = k0[0]; ktmp[1] = k1[0]; ktmp[2] = k2[0]; ktmp[3] = k3[0]; ktmp += 4; k0 += 1; k1 += 1; k2 += 1; k3 += 1; } } remain_outch_start += nn_outch << 2; for (int p=remain_outch_start; p<outch; p++) { const signed char* k0 = kernel + (p+0)*inch*kernel_size; #if __ARM_NEON && __aarch64__ signed char* ktmp = kernel_tm.channel(p/8 + (p%8)/4 + p%4); #else signed char* ktmp = kernel_tm.channel(p/4 + p%4); #endif // __ARM_NEON && __aarch64__ for (int q=0; q<inch*kernel_size; q++) { ktmp[0] = k0[0]; ktmp++; k0++; } } } static void conv_im2col_sgemm_int8_neon(const Mat &bottom_blob, Mat &top_blob, const Mat & kernel_tm, \ const int kernel_w, const int kernel_h, const int stride_w, const int stride_h, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // im2col Mat bottom_im2col(outw*outh, kernel_h*kernel_w*inch, 1UL, opt.workspace_allocator); { const int stride = kernel_h*kernel_w*outw*outh; signed char* ret = (signed char*)bottom_im2col; #pragma omp parallel for num_threads(opt.num_threads) for (int p=0; p<inch; p++) { const signed char* input = bottom_blob.channel(p); int retID = stride * p; for (int u=0; u<kernel_h; u++) { for (int v=0; v<kernel_w; v++) { for (int i=0; i<outh; i++) { for (int j=0; j<outw; j++) { int row = u + i * stride_h; int col = v + j * stride_w; int index = row * w + col; ret[retID] = input[index]; retID++; } } } } } } int kernel_size = kernel_w * kernel_h; int out_size = outw * outh; // bottom_im2col memory packed 8 x 8 Mat bottom_tm(8*kernel_size, inch, out_size/8 + out_size%8, (size_t)1u, opt.workspace_allocator); { int nn_size = out_size >> 3; int remain_size_start = nn_size << 3; #pragma omp parallel for num_threads(opt.num_threads) for (int ii=0; ii<nn_size; ii++) { int i = ii * 8; const signed char* img0 = bottom_im2col.channel(0); img0 += i; signed char* tmpptr = bottom_tm.channel(i/8); for (int q=0; q<inch*kernel_size; q++) { #if __ARM_NEON #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #64] \n" "ld1 {v0.8b}, [%0] \n" "st1 {v0.8b}, [%1] \n" : "=r"(img0), // %0 "=r"(tmpptr) // %1 : "0"(img0), "1"(tmpptr) : "cc", "memory", "v0" ); #else asm volatile( "pld [%0, #64] \n" "vld1.s8 {d0}, [%0] \n" "vst1.s8 {d0}, [%1] \n" : "=r"(img0), // %0 "=r"(tmpptr) // %1 : "0"(img0), "1"(tmpptr) : "cc", "memory", "d0" ); #endif // __aarch64__ #else tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr[2] = img0[2]; tmpptr[3] = img0[3]; tmpptr[4] = img0[4]; tmpptr[5] = img0[5]; tmpptr[6] = img0[6]; tmpptr[7] = img0[7]; #endif // __ARM_NEON tmpptr += 8; img0 += out_size; } } #pragma omp parallel for num_threads(opt.num_threads) for (int i=remain_size_start; i<out_size; i++) { const signed char* img0 = bottom_im2col.channel(0); img0 += i; signed char* tmpptr = bottom_tm.channel(i/8 + i%8); for (int q=0; q<inch*kernel_size; q++) { tmpptr[0] = img0[0]; tmpptr += 1; img0 += out_size; } } } // sgemm(int M, int N, int L, float* A, float* B, float* C) { //int M = outch; // outch int N = outw * outh; // outsize or out stride int L = kernel_w * kernel_h * inch; // ksize * inch int nn_outch = 0; int remain_outch_start = 0; #if __ARM_NEON && __aarch64__ nn_outch = outch >> 3; remain_outch_start = nn_outch << 3; #pragma omp parallel for num_threads(opt.num_threads) for (int pp=0; pp<nn_outch; pp++) { int i = pp * 8; int* output0 = top_blob.channel(i); int* output1 = top_blob.channel(i+1); int* output2 = top_blob.channel(i+2); int* output3 = top_blob.channel(i+3); int* output4 = top_blob.channel(i+4); int* output5 = top_blob.channel(i+5); int* output6 = top_blob.channel(i+6); int* output7 = top_blob.channel(i+7); int j=0; for (; j+7<N; j=j+8) { signed char* vb = bottom_tm.channel(j/8); const signed char* va = kernel_tm.channel(i/8); #if __aarch64__ asm volatile( "eor v16.16b, v16.16b, v16.16b \n" // sum0 "eor v17.16b, v17.16b, v17.16b \n" // sum0n "eor v18.16b, v18.16b, v18.16b \n" // sum1 "eor v19.16b, v19.16b, v19.16b \n" // sum1n "eor v20.16b, v20.16b, v20.16b \n" // sum2 "eor v21.16b, v21.16b, v21.16b \n" // sum2n "eor v22.16b, v22.16b, v22.16b \n" // sum3 "eor v23.16b, v23.16b, v23.16b \n" // sum3n "eor v24.16b, v24.16b, v24.16b \n" // sum4 "eor v25.16b, v25.16b, v25.16b \n" // sum4n "eor v26.16b, v26.16b, v26.16b \n" // sum5 "eor v27.16b, v27.16b, v27.16b \n" // sum5n "eor v28.16b, v28.16b, v28.16b \n" // sum6 "eor v29.16b, v29.16b, v29.16b \n" // sum6n "eor v30.16b, v30.16b, v30.16b \n" // sum7 "eor v31.16b, v31.16b, v31.16b \n" // sum7n "lsr w4, %w20, #2 \n"// r4 = nn = L >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n"// for (; k+3<L; k=k+4) "prfm pldl1keep, [%9, #128] \n" "ld1 {v0.8b, v1.8b, v2.8b, v3.8b}, [%9], #32 \n" "prfm pldl1keep, [%8, #128] \n" "ld1 {v8.8b, v9.8b, v10.8b, v11.8b}, [%8], #32 \n" "sshll v0.8h, v0.8b, #0 \n" // k00 - k70 "sshll v1.8h, v1.8b, #0 \n" // k01 - k71 "sshll v2.8h, v2.8b, #0 \n" // k02 - k72 "sshll v3.8h, v3.8b, #0 \n" // k03 - k73 "sshll v8.8h, v8.8b, #0 \n" // a00 - a70 "sshll v9.8h, v9.8b, #0 \n" // a01 - a71 "sshll v10.8h, v10.8b, #0 \n" // a02 - a72 "sshll v11.8h, v11.8b, #0 \n" // a03 - a73 // k0 "smlal v16.4s, v8.4h, v0.h[0] \n"// sum0 += (a00-a70) * k00 "smlal2 v17.4s, v8.8h, v0.h[0] \n"// "smlal v18.4s, v8.4h, v0.h[1] \n"// sum1 += (a00-a70) * k10 "smlal2 v19.4s, v8.8h, v0.h[1] \n"// "smlal v20.4s, v8.4h, v0.h[2] \n"// sum2 += (a00-a70) * k20 "smlal2 v21.4s, v8.8h, v0.h[2] \n"// "smlal v22.4s, v8.4h, v0.h[3] \n"// sum3 += (a00-a70) * k30 "smlal2 v23.4s, v8.8h, v0.h[3] \n"// "smlal v24.4s, v8.4h, v0.h[4] \n"// sum4 += (a00-a70) * k40 "smlal2 v25.4s, v8.8h, v0.h[4] \n"// "smlal v26.4s, v8.4h, v0.h[5] \n"// sum5 += (a00-a70) * k50 "smlal2 v27.4s, v8.8h, v0.h[5] \n"// "smlal v28.4s, v8.4h, v0.h[6] \n"// sum6 += (a00-a70) * k60 "smlal2 v29.4s, v8.8h, v0.h[6] \n"// "smlal v30.4s, v8.4h, v0.h[7] \n"// sum7 += (a00-a70) * k70 "smlal2 v31.4s, v8.8h, v0.h[7] \n"// // k1 "smlal v16.4s, v9.4h, v1.h[0] \n"// sum0 += (a01-a71) * k01 "smlal2 v17.4s, v9.8h, v1.h[0] \n"// "smlal v18.4s, v9.4h, v1.h[1] \n"// sum1 += (a01-a71) * k11 "smlal2 v19.4s, v9.8h, v1.h[1] \n"// "smlal v20.4s, v9.4h, v1.h[2] \n"// sum2 += (a01-a71) * k21 "smlal2 v21.4s, v9.8h, v1.h[2] \n"// "smlal v22.4s, v9.4h, v1.h[3] \n"// sum3 += (a01-a71) * k31 "smlal2 v23.4s, v9.8h, v1.h[3] \n"// "smlal v24.4s, v9.4h, v1.h[4] \n"// sum4 += (a01-a71) * k41 "smlal2 v25.4s, v9.8h, v1.h[4] \n"// "smlal v26.4s, v9.4h, v1.h[5] \n"// sum5 += (a01-a71) * k51 "smlal2 v27.4s, v9.8h, v1.h[5] \n"// "smlal v28.4s, v9.4h, v1.h[6] \n"// sum6 += (a01-a71) * k61 "smlal2 v29.4s, v9.8h, v1.h[6] \n"// "smlal v30.4s, v9.4h, v1.h[7] \n"// sum7 += (a01-a71) * k71 "smlal2 v31.4s, v9.8h, v1.h[7] \n"// // k2 "smlal v16.4s, v10.4h, v2.h[0] \n"// sum0 += (a02-a72) * k02 "smlal2 v17.4s, v10.8h, v2.h[0] \n"// "smlal v18.4s, v10.4h, v2.h[1] \n"// sum1 += (a02-a72) * k12 "smlal2 v19.4s, v10.8h, v2.h[1] \n"// "smlal v20.4s, v10.4h, v2.h[2] \n"// sum2 += (a02-a72) * k22 "smlal2 v21.4s, v10.8h, v2.h[2] \n"// "smlal v22.4s, v10.4h, v2.h[3] \n"// sum3 += (a02-a72) * k32 "smlal2 v23.4s, v10.8h, v2.h[3] \n"// "smlal v24.4s, v10.4h, v2.h[4] \n"// sum4 += (a02-a72) * k42 "smlal2 v25.4s, v10.8h, v2.h[4] \n"// "smlal v26.4s, v10.4h, v2.h[5] \n"// sum5 += (a02-a72) * k52 "smlal2 v27.4s, v10.8h, v2.h[5] \n"// "smlal v28.4s, v10.4h, v2.h[6] \n"// sum6 += (a02-a72) * k62 "smlal2 v29.4s, v10.8h, v2.h[6] \n"// "smlal v30.4s, v10.4h, v2.h[7] \n"// sum7 += (a02-a72) * k72 "smlal2 v31.4s, v10.8h, v2.h[7] \n"// // k3 "smlal v16.4s, v11.4h, v3.h[0] \n"// sum0 += (a03-a73) * k03 "smlal2 v17.4s, v11.8h, v3.h[0] \n"// "smlal v18.4s, v11.4h, v3.h[1] \n"// sum1 += (a03-a73) * k13 "smlal2 v19.4s, v11.8h, v3.h[1] \n"// "smlal v20.4s, v11.4h, v3.h[2] \n"// sum2 += (a03-a73) * k23 "smlal2 v21.4s, v11.8h, v3.h[2] \n"// "smlal v22.4s, v11.4h, v3.h[3] \n"// sum3 += (a03-a73) * k33 "smlal2 v23.4s, v11.8h, v3.h[3] \n"// "smlal v24.4s, v11.4h, v3.h[4] \n"// sum4 += (a03-a73) * k43 "smlal2 v25.4s, v11.8h, v3.h[4] \n"// "smlal v26.4s, v11.4h, v3.h[5] \n"// sum5 += (a03-a73) * k53 "smlal2 v27.4s, v11.8h, v3.h[5] \n"// "smlal v28.4s, v11.4h, v3.h[6] \n"// sum6 += (a03-a73) * k63 "smlal2 v29.4s, v11.8h, v3.h[6] \n"// "smlal v30.4s, v11.4h, v3.h[7] \n"// sum7 += (a03-a73) * k73 "smlal2 v31.4s, v11.8h, v3.h[7] \n"// "subs w4, w4, #1 \n" "bne 0b \n" "1: \n" // remain loop "and w4, %w20, #3 \n"// w4 = remain = inch & 3; "cmp w4, #0 \n" "beq 3f \n" "2: \n" "prfm pldl1keep, [%9, #128] \n" "ld1 {v0.8b}, [%9], #8 \n" "prfm pldl1keep, [%8, #128] \n" "ld1 {v8.8b}, [%8], #8 \n" "sshll v0.8h, v0.8b, #0 \n" // k00 - k70 "sshll v8.8h, v8.8b, #0 \n" // a00 - a70 // k0 "smlal v16.4s, v8.4h, v0.h[0] \n"// sum0 += (a00-a70) * k00 "smlal2 v17.4s, v8.8h, v0.h[0] \n"// "smlal v18.4s, v8.4h, v0.h[1] \n"// sum1 += (a00-a70) * k10 "smlal2 v19.4s, v8.8h, v0.h[1] \n"// "smlal v20.4s, v8.4h, v0.h[2] \n"// sum2 += (a00-a70) * k20 "smlal2 v21.4s, v8.8h, v0.h[2] \n"// "smlal v22.4s, v8.4h, v0.h[3] \n"// sum3 += (a00-a70) * k30 "smlal2 v23.4s, v8.8h, v0.h[3] \n"// "smlal v24.4s, v8.4h, v0.h[4] \n"// sum4 += (a00-a70) * k40 "smlal2 v25.4s, v8.8h, v0.h[4] \n"// "smlal v26.4s, v8.4h, v0.h[5] \n"// sum5 += (a00-a70) * k50 "smlal2 v27.4s, v8.8h, v0.h[5] \n"// "smlal v28.4s, v8.4h, v0.h[6] \n"// sum6 += (a00-a70) * k60 "smlal2 v29.4s, v8.8h, v0.h[6] \n"// "smlal v30.4s, v8.4h, v0.h[7] \n"// sum7 += (a00-a70) * k70 "smlal2 v31.4s, v8.8h, v0.h[7] \n"// "subs w4, w4, #1 \n" "bne 2b \n" "3: \n" "st1 {v16.4s, v17.4s}, [%0] \n" "st1 {v18.4s, v19.4s}, [%1] \n" "st1 {v20.4s, v21.4s}, [%2] \n" "st1 {v22.4s, v23.4s}, [%3] \n" "st1 {v24.4s, v25.4s}, [%4] \n" "st1 {v26.4s, v27.4s}, [%5] \n" "st1 {v28.4s, v29.4s}, [%6] \n" "st1 {v30.4s, v31.4s}, [%7] \n" : "=r"(output0), // %0 "=r"(output1), // %1 "=r"(output2), // %2 "=r"(output3), // %3 "=r"(output4), // %4 "=r"(output5), // %5 "=r"(output6), // %6 "=r"(output7), // %7 "=r"(vb), // %8 "=r"(va) // %9 : "0"(output0), "1"(output1), "2"(output2), "3"(output3), "4"(output4), "5"(output5), "6"(output6), "7"(output7), "8"(vb), "9"(va), "r"(L) // %20 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31" ); #else int sum0[8] = {0}; int sum1[8] = {0}; int sum2[8] = {0}; int sum3[8] = {0}; int sum4[8] = {0}; int sum5[8] = {0}; int sum6[8] = {0}; int sum7[8] = {0}; int k=0; for (; k+7<L; k=k+8) { for (int n=0; n<8; n++) { sum0[n] += (int)va[0] * vb[n]; sum1[n] += (int)va[1] * vb[n]; sum2[n] += (int)va[2] * vb[n]; sum3[n] += (int)va[3] * vb[n]; sum4[n] += (int)va[4] * vb[n]; sum5[n] += (int)va[5] * vb[n]; sum6[n] += (int)va[6] * vb[n]; sum7[n] += (int)va[7] * vb[n]; va += 8; sum0[n] += (int)va[0] * vb[n+8]; sum1[n] += (int)va[1] * vb[n+8]; sum2[n] += (int)va[2] * vb[n+8]; sum3[n] += (int)va[3] * vb[n+8]; sum4[n] += (int)va[4] * vb[n+8]; sum5[n] += (int)va[5] * vb[n+8]; sum6[n] += (int)va[6] * vb[n+8]; sum7[n] += (int)va[7] * vb[n+8]; va += 8; sum0[n] += (int)va[0] * vb[n+16]; sum1[n] += (int)va[1] * vb[n+16]; sum2[n] += (int)va[2] * vb[n+16]; sum3[n] += (int)va[3] * vb[n+16]; sum4[n] += (int)va[4] * vb[n+16]; sum5[n] += (int)va[5] * vb[n+16]; sum6[n] += (int)va[6] * vb[n+16]; sum7[n] += (int)va[7] * vb[n+16]; va += 8; sum0[n] += (int)va[0] * vb[n+24]; sum1[n] += (int)va[1] * vb[n+24]; sum2[n] += (int)va[2] * vb[n+24]; sum3[n] += (int)va[3] * vb[n+24]; sum4[n] += (int)va[4] * vb[n+24]; sum5[n] += (int)va[5] * vb[n+24]; sum6[n] += (int)va[6] * vb[n+24]; sum7[n] += (int)va[7] * vb[n+24]; va += 8; sum0[n] += (int)va[0] * vb[n+32]; sum1[n] += (int)va[1] * vb[n+32]; sum2[n] += (int)va[2] * vb[n+32]; sum3[n] += (int)va[3] * vb[n+32]; sum4[n] += (int)va[4] * vb[n+32]; sum5[n] += (int)va[5] * vb[n+32]; sum6[n] += (int)va[6] * vb[n+32]; sum7[n] += (int)va[7] * vb[n+32]; va += 8; sum0[n] += (int)va[0] * vb[n+40]; sum1[n] += (int)va[1] * vb[n+40]; sum2[n] += (int)va[2] * vb[n+40]; sum3[n] += (int)va[3] * vb[n+40]; sum4[n] += (int)va[4] * vb[n+40]; sum5[n] += (int)va[5] * vb[n+40]; sum6[n] += (int)va[6] * vb[n+40]; sum7[n] += (int)va[7] * vb[n+40]; va += 8; sum0[n] += (int)va[0] * vb[n+48]; sum1[n] += (int)va[1] * vb[n+48]; sum2[n] += (int)va[2] * vb[n+48]; sum3[n] += (int)va[3] * vb[n+48]; sum4[n] += (int)va[4] * vb[n+48]; sum5[n] += (int)va[5] * vb[n+48]; sum6[n] += (int)va[6] * vb[n+48]; sum7[n] += (int)va[7] * vb[n+48]; va += 8; sum0[n] += (int)va[0] * vb[n+56]; sum1[n] += (int)va[1] * vb[n+56]; sum2[n] += (int)va[2] * vb[n+56]; sum3[n] += (int)va[3] * vb[n+56]; sum4[n] += (int)va[4] * vb[n+56]; sum5[n] += (int)va[5] * vb[n+56]; sum6[n] += (int)va[6] * vb[n+56]; sum7[n] += (int)va[7] * vb[n+56]; va -= 56; } va += 64; vb += 64; } for (; k<L; k++) { for (int n=0; n<8; n++) { sum0[n] += (int)va[0] * vb[n]; sum1[n] += (int)va[1] * vb[n]; sum2[n] += (int)va[2] * vb[n]; sum3[n] += (int)va[3] * vb[n]; sum4[n] += (int)va[4] * vb[n]; sum5[n] += (int)va[5] * vb[n]; sum6[n] += (int)va[6] * vb[n]; sum7[n] += (int)va[7] * vb[n]; } va += 8; vb += 8; } for (int n=0; n<8; n++) { output0[n] = sum0[n]; output1[n] = sum1[n]; output2[n] = sum2[n]; output3[n] = sum3[n]; output4[n] = sum4[n]; output5[n] = sum5[n]; output6[n] = sum6[n]; output7[n] = sum7[n]; } #endif // __aarch64__ output0 += 8; output1 += 8; output2 += 8; output3 += 8; output4 += 8; output5 += 8; output6 += 8; output7 += 8; } for (; j<N; j++) { signed char* vb = bottom_tm.channel(j/8 + j%8); const signed char* va = kernel_tm.channel(i/8); #if __aarch64__ asm volatile( "eor v14.16b, v14.16b, v14.16b \n" // sum0_3 "eor v15.16b, v15.16b, v15.16b \n" // sum4_7 "eor v16.16b, v16.16b, v16.16b \n" // sum0 "eor v17.16b, v17.16b, v17.16b \n" // sum1 "eor v18.16b, v18.16b, v18.16b \n" // sum2 "eor v19.16b, v19.16b, v19.16b \n" // sum3 "eor v20.16b, v20.16b, v20.16b \n" // sum4 "eor v21.16b, v21.16b, v21.16b \n" // sum5 "eor v22.16b, v22.16b, v22.16b \n" // sum6 "eor v23.16b, v23.16b, v23.16b \n" // sum7 "lsr w4, %w20, #2 \n"// r4 = nn = L >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n"// for (; k+3<L; k=k+4) "prfm pldl1keep, [%9, #128] \n" "ld1 {v0.8b, v1.8b, v2.8b, v3.8b}, [%9], #32 \n" // k //"prfm pldl1keep, [%8, #128] \n" "ld1 {v4.8b}, [%8] \n" // d "add %8, %8, #4 \n" "sshll v0.8h, v0.8b, #0 \n" // k00 - k70 "sshll v1.8h, v1.8b, #0 \n" // k01 - k71 "sshll v2.8h, v2.8b, #0 \n" // k02 - k72 "sshll v3.8h, v3.8b, #0 \n" // k03 - k73 "sshll v4.8h, v4.8b, #0 \n" // a00 - a30 // k0 "smlal v16.4s, v0.4h, v4.h[0] \n"// sum0 += (k00-k70) * a00 "smlal2 v17.4s, v0.8h, v4.h[0] \n"// "smlal v18.4s, v1.4h, v4.h[1] \n"// sum1 += (k01-k71) * a10 "smlal2 v19.4s, v1.8h, v4.h[1] \n"// "smlal v20.4s, v2.4h, v4.h[2] \n"// sum2 += (k02-k72) * a20 "smlal2 v21.4s, v2.8h, v4.h[2] \n"// "smlal v22.4s, v3.4h, v4.h[3] \n"// sum3 += (k03-k73) * a30 "smlal2 v23.4s, v3.8h, v4.h[3] \n"// "subs w4, w4, #1 \n" "bne 0b \n" "add v16.4s, v16.4s, v18.4s \n" "add v17.4s, v17.4s, v19.4s \n" "add v20.4s, v20.4s, v22.4s \n" "add v21.4s, v21.4s, v23.4s \n" "add v14.4s, v16.4s, v20.4s \n" "add v15.4s, v17.4s, v21.4s \n" "1: \n" // remain loop "and w4, %w20, #3 \n"// w4 = remain = inch & 3; "cmp w4, #0 \n" "beq 3f \n" "2: \n" //"prfm pldl1keep, [%9, #128] \n" "ld1 {v0.8b}, [%9], #8 \n" //"prfm pldl1keep, [%8, #128] \n" "ld1 {v4.8b}, [%8] \n" "add %8, %8, #1 \n" "sshll v0.8h, v0.8b, #0 \n" // k00 - k70 "sshll v4.8h, v4.8b, #0 \n" // a00 // k0 "smlal v14.4s, v0.4h, v4.h[0] \n"// sum0 += (k00-k70) * a00 "smlal2 v15.4s, v0.8h, v4.h[0] \n"// "subs w4, w4, #1 \n" "bne 2b \n" "3: \n" "st1 {v14.s}[0], [%0] \n" "st1 {v14.s}[1], [%1] \n" "st1 {v14.s}[2], [%2] \n" "st1 {v14.s}[3], [%3] \n" "st1 {v15.s}[0], [%4] \n" "st1 {v15.s}[1], [%5] \n" "st1 {v15.s}[2], [%6] \n" "st1 {v15.s}[3], [%7] \n" : "=r"(output0), // %0 "=r"(output1), // %1 "=r"(output2), // %2 "=r"(output3), // %3 "=r"(output4), // %4 "=r"(output5), // %5 "=r"(output6), // %6 "=r"(output7), // %7 "=r"(vb), // %8 "=r"(va) // %9 : "0"(output0), "1"(output1), "2"(output2), "3"(output3), "4"(output4), "5"(output5), "6"(output6), "7"(output7), "8"(vb), "9"(va), "r"(L) // %20 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23" ); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; int sum4 = 0; int sum5 = 0; int sum6 = 0; int sum7 = 0; for (int k=0; k<L; k++) { sum0 += (int)va[0] * vb[0]; sum1 += (int)va[1] * vb[0]; sum2 += (int)va[2] * vb[0]; sum3 += (int)va[3] * vb[0]; sum4 += (int)va[4] * vb[0]; sum5 += (int)va[5] * vb[0]; sum6 += (int)va[6] * vb[0]; sum7 += (int)va[7] * vb[0]; va += 8; vb += 1; } output0[0] = sum0; output1[0] = sum1; output2[0] = sum2; output3[0] = sum3; output4[0] = sum4; output5[0] = sum5; output6[0] = sum6; output7[0] = sum7; #endif // __aarch64__ output0++; output1++; output2++; output3++; output4++; output5++; output6++; output7++; } } #endif // __ARM_NEON && __aarch64__ nn_outch = (outch - remain_outch_start) >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp=0; pp<nn_outch; pp++) { int i = remain_outch_start + pp * 4; int* output0 = top_blob.channel(i); int* output1 = top_blob.channel(i+1); int* output2 = top_blob.channel(i+2); int* output3 = top_blob.channel(i+3); int j=0; for (; j+7<N; j=j+8) { signed char* vb = bottom_tm.channel(j/8); #if __ARM_NEON && __aarch64__ const signed char* va = kernel_tm.channel(i/8 + (i%8)/4); #else const signed char* va = kernel_tm.channel(i/4); #endif // __ARM_NEON && __aarch64__ #if __ARM_NEON #if __aarch64__ asm volatile( "eor v16.16b, v16.16b, v16.16b \n" // sum0 "eor v17.16b, v17.16b, v17.16b \n" // sum0n "eor v18.16b, v18.16b, v18.16b \n" // sum1 "eor v19.16b, v19.16b, v19.16b \n" // sum1n "eor v20.16b, v20.16b, v20.16b \n" // sum2 "eor v21.16b, v21.16b, v21.16b \n" // sum2n "eor v22.16b, v22.16b, v22.16b \n" // sum3 "eor v23.16b, v23.16b, v23.16b \n" // sum3n "lsr w4, %w12, #2 \n"// r4 = nn = L >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n"// for (; k+3<L; k=k+4) "prfm pldl1keep, [%5, #128] \n" "ld1 {v0.8b, v1.8b}, [%5], #16 \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v8.8b, v9.8b, v10.8b, v11.8b}, [%4], #32 \n" "sshll v0.8h, v0.8b, #0 \n" // k00 - k30,k01 - k31 "sshll v1.8h, v1.8b, #0 \n" // k02 - k32,k03 - k33 "sshll v8.8h, v8.8b, #0 \n" // a00 - a70 "sshll v9.8h, v9.8b, #0 \n" // a01 - a71 "sshll v10.8h, v10.8b, #0 \n" // a02 - a72 "sshll v11.8h, v11.8b, #0 \n" // a03 - a73 // k0 "smlal v16.4s, v8.4h, v0.h[0] \n"// sum0 += (a00-a70) * k00 "smlal2 v17.4s, v8.8h, v0.h[0] \n"// "smlal v18.4s, v8.4h, v0.h[1] \n"// sum1 += (a00-a70) * k10 "smlal2 v19.4s, v8.8h, v0.h[1] \n"// "smlal v20.4s, v8.4h, v0.h[2] \n"// sum2 += (a00-a70) * k20 "smlal2 v21.4s, v8.8h, v0.h[2] \n"// "smlal v22.4s, v8.4h, v0.h[3] \n"// sum3 += (a00-a70) * k30 "smlal2 v23.4s, v8.8h, v0.h[3] \n"// // k1 "smlal v16.4s, v9.4h, v0.h[4] \n"// sum0 += (a01-a71) * k01 "smlal2 v17.4s, v9.8h, v0.h[4] \n"// "smlal v18.4s, v9.4h, v0.h[5] \n"// sum1 += (a01-a71) * k11 "smlal2 v19.4s, v9.8h, v0.h[5] \n"// "smlal v20.4s, v9.4h, v0.h[6] \n"// sum2 += (a01-a71) * k21 "smlal2 v21.4s, v9.8h, v0.h[6] \n"// "smlal v22.4s, v9.4h, v0.h[7] \n"// sum3 += (a01-a71) * k31 "smlal2 v23.4s, v9.8h, v0.h[7] \n"// // k2 "smlal v16.4s, v10.4h, v1.h[0] \n"// sum0 += (a02-a72) * k02 "smlal2 v17.4s, v10.8h, v1.h[0] \n"// "smlal v18.4s, v10.4h, v1.h[1] \n"// sum1 += (a02-a72) * k12 "smlal2 v19.4s, v10.8h, v1.h[1] \n"// "smlal v20.4s, v10.4h, v1.h[2] \n"// sum2 += (a02-a72) * k22 "smlal2 v21.4s, v10.8h, v1.h[2] \n"// "smlal v22.4s, v10.4h, v1.h[3] \n"// sum3 += (a02-a72) * k32 "smlal2 v23.4s, v10.8h, v1.h[3] \n"// // k3 "smlal v16.4s, v11.4h, v1.h[4] \n"// sum0 += (a03-a73) * k03 "smlal2 v17.4s, v11.8h, v1.h[4] \n"// "smlal v18.4s, v11.4h, v1.h[5] \n"// sum1 += (a03-a73) * k13 "smlal2 v19.4s, v11.8h, v1.h[5] \n"// "smlal v20.4s, v11.4h, v1.h[6] \n"// sum2 += (a03-a73) * k23 "smlal2 v21.4s, v11.8h, v1.h[6] \n"// "smlal v22.4s, v11.4h, v1.h[7] \n"// sum3 += (a03-a73) * k33 "smlal2 v23.4s, v11.8h, v1.h[7] \n"// "subs w4, w4, #1 \n" "bne 0b \n" "1: \n" // remain loop "and w4, %w12, #3 \n"// w4 = remain = inch & 3; "cmp w4, #0 \n" "beq 3f \n" "2: \n" //"prfm pldl1keep, [%5, #128] \n" "ld1 {v0.8b}, [%5] \n" //"prfm pldl1keep, [%4, #128] \n" "ld1 {v8.8b}, [%4], #8 \n" "add %5, %5, #4 \n" "sshll v0.8h, v0.8b, #0 \n" // k00 - k30 "sshll v8.8h, v8.8b, #0 \n" // a00 - a70 // k0 "smlal v16.4s, v8.4h, v0.h[0] \n"// sum0 += (a00-a70) * k00 "smlal2 v17.4s, v8.8h, v0.h[0] \n"// "smlal v18.4s, v8.4h, v0.h[1] \n"// sum1 += (a00-a70) * k10 "smlal2 v19.4s, v8.8h, v0.h[1] \n"// "smlal v20.4s, v8.4h, v0.h[2] \n"// sum2 += (a00-a70) * k20 "smlal2 v21.4s, v8.8h, v0.h[2] \n"// "smlal v22.4s, v8.4h, v0.h[3] \n"// sum3 += (a00-a70) * k30 "smlal2 v23.4s, v8.8h, v0.h[3] \n"// "subs w4, w4, #1 \n" "bne 2b \n" "3: \n" "st1 {v16.4s, v17.4s}, [%0] \n" "st1 {v18.4s, v19.4s}, [%1] \n" "st1 {v20.4s, v21.4s}, [%2] \n" "st1 {v22.4s, v23.4s}, [%3] \n" : "=r"(output0), // %0 "=r"(output1), // %1 "=r"(output2), // %2 "=r"(output3), // %3 "=r"(vb), // %4 "=r"(va) // %5 : "0"(output0), "1"(output1), "2"(output2), "3"(output3), "4"(vb), "5"(va), "r"(L) // %12 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23" ); #else asm volatile( // K loop "vmov.s32 q8, #0 \n" "vmov.s32 q9, #0 \n" "vmov.s32 q10, #0 \n" "vmov.s32 q11, #0 \n" "vmov.s32 q12, #0 \n" "vmov.s32 q13, #0 \n" "vmov.s32 q14, #0 \n" "vmov.s32 q15, #0 \n" "lsr r4, %12, #3 \n"// r4 = nn = L >> 3 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%4, #128] \n" "vld1.s8 {d8-d11}, [%4]! \n"// tmpr a00-a07,a10-a17,a20-a27,a30-a37 a(inch)(data) "vmovl.s8 q7, d11 \n"// a30-a37 "vmovl.s8 q6, d10 \n"// a20-a27 "vmovl.s8 q5, d9 \n"// a10-a17 "vmovl.s8 q4, d8 \n"// a00-a07 "pld [%5, #128] \n" "vld1.s8 {d0-d3}, [%5]! \n"// kptr k00-k30,k01-k31, k02-k32,k03-k33, k04-k34,k05-k35, k06-k36,k07-k37 k(outch)(inch) "vmovl.s8 q3, d3 \n"// k06-k36,k07-k37 "vmovl.s8 q2, d2 \n"// k04-k34,k05-k35 "vmovl.s8 q1, d1 \n"// k02-k32,k03-k33 "vmovl.s8 q0, d0 \n"// k00-k30,k01-k31 "vmlal.s16 q8, d8, d0[0] \n"// sum0 = (a00-a07) * k00 "vmlal.s16 q9, d9, d0[0] \n" "vmlal.s16 q10, d8, d0[1] \n"// sum1 = (a00-a07) * k10 "vmlal.s16 q11, d9, d0[1] \n" "vmlal.s16 q12, d8, d0[2] \n"// sum2 = (a00-a07) * k20 "vmlal.s16 q13, d9, d0[2] \n" "vmlal.s16 q14, d8, d0[3] \n"// sum3 = (a00-a07) * k30 "vmlal.s16 q15, d9, d0[3] \n" "vmlal.s16 q8, d10, d1[0] \n"// sum0 += (a10-a17) * k01 "vmlal.s16 q9, d11, d1[0] \n" "vmlal.s16 q10, d10, d1[1] \n"// sum1 += (a10-a17) * k11 "vmlal.s16 q11, d11, d1[1] \n" "vmlal.s16 q12, d10, d1[2] \n"// sum2 += (a10-a17) * k21 "vmlal.s16 q13, d11, d1[2] \n" "vmlal.s16 q14, d10, d1[3] \n"// sum3 += (a10-a17) * k31 "vmlal.s16 q15, d11, d1[3] \n" "pld [%4, #128] \n" "vld1.s8 {d8-d9}, [%4]! \n"// tmpr a00-a07,a10-a17,a20-a27,a30-a37 a(inch)(data) "vmovl.s8 q5, d9 \n"// a10-a17 "vmovl.s8 q4, d8 \n"// a00-a07 "vmlal.s16 q8, d12, d2[0] \n"// sum0 += (a20-a27) * k02 "vmlal.s16 q9, d13, d2[0] \n" "vmlal.s16 q10, d12, d2[1] \n"// sum1 += (a20-a27) * k12 "vmlal.s16 q11, d13, d2[1] \n" "vmlal.s16 q12, d12, d2[2] \n"// sum2 += (a20-a27) * k22 "vmlal.s16 q13, d13, d2[2] \n" "vmlal.s16 q14, d12, d2[3] \n"// sum3 += (a20-a27) * k32 "vmlal.s16 q15, d13, d2[3] \n" "vmlal.s16 q8, d14, d3[0] \n"// sum0 += (a30-a37) * k03 "vmlal.s16 q9, d15, d3[0] \n" "vmlal.s16 q10, d14, d3[1] \n"// sum1 += (a30-a37) * k13 "vmlal.s16 q11, d15, d3[1] \n" "vmlal.s16 q12, d14, d3[2] \n"// sum2 += (a30-a37) * k23 "vmlal.s16 q13, d15, d3[2] \n" "vmlal.s16 q14, d14, d3[3] \n"// sum3 += (a30-a37) * k33 "vmlal.s16 q15, d15, d3[3] \n" "pld [%4, #128] \n" "vld1.s8 {d0-d1}, [%4]! \n"// tmpr a00-a07,a10-a17,a20-a27,a30-a37 a(inch)(data) "vmovl.s8 q1, d1 \n"// a10-a17 "vmovl.s8 q0, d0 \n"// a00-a07 "vmlal.s16 q8, d8, d4[0] \n"// sum0 += (a40-a47) * k04 "vmlal.s16 q9, d9, d4[0] \n" "vmlal.s16 q10, d8, d4[1] \n"// sum1 += (a40-a47) * k14 "vmlal.s16 q11, d9, d4[1] \n" "vmlal.s16 q12, d8, d4[2] \n"// sum2 += (a40-a47) * k24 "vmlal.s16 q13, d9, d4[2] \n" "vmlal.s16 q14, d8, d4[3] \n"// sum3 += (a40-a47) * k34 "vmlal.s16 q15, d9, d4[3] \n" "vmlal.s16 q8, d10, d5[0] \n"// sum0 += (a50-a57) * k05 "vmlal.s16 q9, d11, d5[0] \n" "vmlal.s16 q10, d10, d5[1] \n"// sum1 += (a50-a57) * k15 "vmlal.s16 q11, d11, d5[1] \n" "vmlal.s16 q12, d10, d5[2] \n"// sum2 += (a50-a57) * k25 "vmlal.s16 q13, d11, d5[2] \n" "vmlal.s16 q14, d10, d5[3] \n"// sum3 += (a50-a57) * k35 "vmlal.s16 q15, d11, d5[3] \n" "vmlal.s16 q8, d0, d6[0] \n"// sum0 += (a60-a67) * k06 "vmlal.s16 q9, d1, d6[0] \n" "vmlal.s16 q10, d0, d6[1] \n"// sum1 += (a60-a67) * k16 "vmlal.s16 q11, d1, d6[1] \n" "vmlal.s16 q12, d0, d6[2] \n"// sum2 += (a60-a67) * k26 "vmlal.s16 q13, d1, d6[2] \n" "vmlal.s16 q14, d0, d6[3] \n"// sum3 += (a60-a67) * k36 "vmlal.s16 q15, d1, d6[3] \n" "vmlal.s16 q8, d2, d7[0] \n"// sum0 += (a70-a77) * k07 "vmlal.s16 q9, d3, d7[0] \n" "vmlal.s16 q10, d2, d7[1] \n"// sum1 += (a70-a77) * k17 "vmlal.s16 q11, d3, d7[1] \n" "vmlal.s16 q12, d2, d7[2] \n"// sum2 += (a70-a77) * k27 "vmlal.s16 q13, d3, d7[2] \n" "vmlal.s16 q14, d2, d7[3] \n"// sum3 += (a70-a77) * k37 "vmlal.s16 q15, d3, d7[3] \n" "subs r4, r4, #1 \n" "bne 0b \n"// end for "1: \n" // remain loop "and r4, %12, #7 \n"// r4 = remain = inch & 7 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%4]! \n"// tmpr a00-a70 a(inch)(data) "vld1.s8 {d0}, [%5] \n"// kptr k00-k30 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %5, #4 \n" "vmlal.s16 q8, d2, d0[0] \n"// sum0 += (a00-a70) * k00 "vmlal.s16 q9, d3, d0[0] \n" "vmlal.s16 q10, d2, d0[1] \n"// sum1 += (a00-a70) * k10 "vmlal.s16 q11, d3, d0[1] \n" "vmlal.s16 q12, d2, d0[2] \n"// sum2 += (a00-a70) * k20 "vmlal.s16 q13, d3, d0[2] \n" "vmlal.s16 q14, d2, d0[3] \n"// sum3 += (a00-a70) * k30 "vmlal.s16 q15, d3, d0[3] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory "vst1.s32 {d16-d19}, [%0] \n" "vst1.s32 {d20-d23}, [%1] \n" "vst1.s32 {d24-d27}, [%2] \n" "vst1.s32 {d28-d31}, [%3] \n" : "=r"(output0), // %0 "=r"(output1), // %1 "=r"(output2), // %2 "=r"(output3), // %3 "=r"(vb), // %4 "=r"(va) // %5 : "0"(output0), "1"(output1), "2"(output2), "3"(output3), "4"(vb), "5"(va), "r"(L) // %12 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ #else int sum0[8] = {0}; int sum1[8] = {0}; int sum2[8] = {0}; int sum3[8] = {0}; int k=0; for (; k+7<L; k=k+8) { for (int n=0; n<8; n++) { sum0[n] += (int)va[0] * vb[n]; sum1[n] += (int)va[1] * vb[n]; sum2[n] += (int)va[2] * vb[n]; sum3[n] += (int)va[3] * vb[n]; va += 4; sum0[n] += (int)va[0] * vb[n+8]; sum1[n] += (int)va[1] * vb[n+8]; sum2[n] += (int)va[2] * vb[n+8]; sum3[n] += (int)va[3] * vb[n+8]; va += 4; sum0[n] += (int)va[0] * vb[n+16]; sum1[n] += (int)va[1] * vb[n+16]; sum2[n] += (int)va[2] * vb[n+16]; sum3[n] += (int)va[3] * vb[n+16]; va += 4; sum0[n] += (int)va[0] * vb[n+24]; sum1[n] += (int)va[1] * vb[n+24]; sum2[n] += (int)va[2] * vb[n+24]; sum3[n] += (int)va[3] * vb[n+24]; va += 4; sum0[n] += (int)va[0] * vb[n+32]; sum1[n] += (int)va[1] * vb[n+32]; sum2[n] += (int)va[2] * vb[n+32]; sum3[n] += (int)va[3] * vb[n+32]; va += 4; sum0[n] += (int)va[0] * vb[n+40]; sum1[n] += (int)va[1] * vb[n+40]; sum2[n] += (int)va[2] * vb[n+40]; sum3[n] += (int)va[3] * vb[n+40]; va += 4; sum0[n] += (int)va[0] * vb[n+48]; sum1[n] += (int)va[1] * vb[n+48]; sum2[n] += (int)va[2] * vb[n+48]; sum3[n] += (int)va[3] * vb[n+48]; va += 4; sum0[n] += (int)va[0] * vb[n+56]; sum1[n] += (int)va[1] * vb[n+56]; sum2[n] += (int)va[2] * vb[n+56]; sum3[n] += (int)va[3] * vb[n+56]; va -= 28; } va += 32; vb += 64; } for (; k<L; k++) { for (int n=0; n<8; n++) { sum0[n] += (int)va[0] * vb[n]; sum1[n] += (int)va[1] * vb[n]; sum2[n] += (int)va[2] * vb[n]; sum3[n] += (int)va[3] * vb[n]; } va += 4; vb += 8; } for (int n=0; n<8; n++) { output0[n] = sum0[n]; output1[n] = sum1[n]; output2[n] = sum2[n]; output3[n] = sum3[n]; } #endif // __ARM_NEON output0 += 8; output1 += 8; output2 += 8; output3 += 8; } for (; j<N; j++) { signed char* vb = bottom_tm.channel(j/8 + j%8); #if __ARM_NEON && __aarch64__ const signed char* va = kernel_tm.channel(i/8 + (i%8)/4); #else const signed char* va = kernel_tm.channel(i/4); #endif // __ARM_NEON && __aarch64__ #if __ARM_NEON #if __aarch64__ asm volatile( "eor v14.16b, v14.16b, v14.16b \n" // sum0_3 "eor v16.16b, v16.16b, v16.16b \n" // sum0 "eor v17.16b, v17.16b, v17.16b \n" // sum1 "eor v18.16b, v18.16b, v18.16b \n" // sum2 "eor v19.16b, v19.16b, v19.16b \n" // sum3 "lsr w4, %w12, #2 \n"// r4 = nn = L >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n"// for (; k+3<L; k=k+4) "prfm pldl1keep, [%5, #128] \n" "ld1 {v0.8b, v1.8b}, [%5], #16 \n" // k //"prfm pldl1keep, [%4, #128] \n" "ld1 {v4.8b}, [%4] \n" // d "add %4, %4, #4 \n" "sshll v0.8h, v0.8b, #0 \n" // k00 - k30,k01 - k31 "sshll v1.8h, v1.8b, #0 \n" // k02 - k32,k03 - k33 "sshll v4.8h, v4.8b, #0 \n" // a00 - a30 "subs w4, w4, #1 \n" // k0 "smlal v16.4s, v0.4h, v4.h[0] \n"// sum0 += (k00-k30) * a00 "smlal2 v17.4s, v0.8h, v4.h[0] \n"// sum1 += (k01-k31) * a10 "smlal v18.4s, v1.4h, v4.h[1] \n"// sum2 += (k02-k32) * a20 "smlal2 v19.4s, v1.8h, v4.h[1] \n"// sum3 += (k03-k33) * a30 "bne 0b \n" "add v16.4s, v16.4s, v18.4s \n" "add v17.4s, v17.4s, v19.4s \n" "add v14.4s, v16.4s, v17.4s \n" "1: \n" // remain loop "and w4, %w12, #3 \n"// w4 = remain = inch & 3; "cmp w4, #0 \n" "beq 3f \n" "2: \n" //"prfm pldl1keep, [%5, #128] \n" "ld1 {v0.8b}, [%5] \n" //"prfm pldl1keep, [4, #128] \n" "ld1 {v4.8b}, [%4] \n" "add %4, %4, #1 \n" "add %5, %5, #4 \n" "subs w4, w4, #1 \n" "sshll v0.8h, v0.8b, #0 \n" // k00 - k30 "sshll v4.8h, v4.8b, #0 \n" // a00 // k0 "smlal v14.4s, v0.4h, v4.h[0] \n"// sum0 += (k00-k30) * a00 "bne 2b \n" "3: \n" "st1 {v14.s}[0], [%0] \n" "st1 {v14.s}[1], [%1] \n" "st1 {v14.s}[2], [%2] \n" "st1 {v14.s}[3], [%3] \n" : "=r"(output0), // %0 "=r"(output1), // %1 "=r"(output2), // %2 "=r"(output3), // %3 "=r"(vb), // %4 "=r"(va) // %5 : "0"(output0), "1"(output1), "2"(output2), "3"(output3), "4"(vb), "5"(va), "r"(L) // %12 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19" ); #else asm volatile( // inch loop "veor q6, q6, q6 \n" "veor q7, q7, q7 \n" "veor q8, q8, q8 \n" "veor q9, q9, q9 \n" "veor q10, q10, q10 \n" "veor q11, q11, q11 \n" "veor q12, q12, q12 \n" "veor q13, q13, q13 \n" "vmov.s32 q14, #0 \n" "lsr r4, %12, #3 \n"// r4 = nn = L >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%4, #128] \n" "vld1.s8 {d0}, [%4]! \n"// tmpr a00,a10,a20,a30 a(inch)(data) "vmovl.s8 q0, d0 \n"// a00-a07 "pld [%5, #128] \n" "vld1.s8 {d2-d5}, [%5]! \n"// kptr k00-k30,k01-k31, k02-k32,k03-k33, k04-k34,k05-k35, k06-k36,k07-k37 k(outch)(inch) "vmovl.s8 q4, d5 \n"// k06-k36,k07-k37 "vmovl.s8 q3, d4 \n"// k04-k34,k05-k35 "vmovl.s8 q2, d3 \n"// k02-k32,k03-k33 "vmovl.s8 q1, d2 \n"// k00-k30,k01-k31 "vmlal.s16 q6, d2, d0[0] \n"// (k00-k30) * a00 "vmlal.s16 q7, d3, d0[1] \n"// (k01-k31) * a01 "vmlal.s16 q8, d4, d0[2] \n"// (k02-k32) * a02 "vmlal.s16 q9, d5, d0[3] \n"// (k03-k33) * a03 "vmlal.s16 q10, d6, d1[0] \n"// (k04-k34) * a04 "vmlal.s16 q11, d7, d1[1] \n"// (k05-k35) * a05 "vmlal.s16 q12, d8, d1[2] \n"// (k06-k36) * a06 "vmlal.s16 q13, d9, d1[3] \n"// (k07-k37) * a07 "subs r4, r4, #1 \n" "bne 0b \n"// end for "vadd.s32 q6, q6, q7 \n" "vadd.s32 q9, q9, q8 \n" "vadd.s32 q11, q11, q10 \n" "vadd.s32 q13, q13, q12 \n" "vadd.s32 q9, q9, q6 \n" "vadd.s32 q13, q13, q11 \n" "vadd.s32 q14, q13, q9 \n" "1: \n" // remain loop "and r4, %12, #7 \n"// r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%4] \n"// tmpr a00 a(inch)(data) "vld1.s8 {d0}, [%5] \n"// kptr k00-k30 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %4, #1 \n" "add %5, #4 \n" "vmlal.s16 q14, d0, d2[0] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory "vst1.s32 {d28[0]}, [%0] \n" "vst1.s32 {d28[1]}, [%1] \n" "vst1.s32 {d29[0]}, [%2] \n" "vst1.s32 {d29[1]}, [%3] \n" : "=r"(output0), // %0 "=r"(output1), // %1 "=r"(output2), // %2 "=r"(output3), // %3 "=r"(vb), // %4 "=r"(va) // %5 : "0"(output0), "1"(output1), "2"(output2), "3"(output3), "4"(vb), "5"(va), "r"(L) // %12 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14" ); #endif // __aarch64__ #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; for (int k=0; k<L; k++) { sum0 += (int)va[0] * vb[0]; sum1 += (int)va[1] * vb[0]; sum2 += (int)va[2] * vb[0]; sum3 += (int)va[3] * vb[0]; va += 4; vb += 1; } output0[0] = sum0; output1[0] = sum1; output2[0] = sum2; output3[0] = sum3; #endif // __ARM_NEON output0++; output1++; output2++; output3++; } } remain_outch_start += nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int i=remain_outch_start; i<outch; i++) { int* output = top_blob.channel(i); int j=0; for (; j+7<N; j=j+8) { signed char* vb = bottom_tm.channel(j/8); #if __ARM_NEON && __aarch64__ const signed char* va = kernel_tm.channel(i/8 + (i%8)/4 + i%4); #else const signed char* va = kernel_tm.channel(i/4 + i%4); #endif // __ARM_NEON && __aarch64__ #if __ARM_NEON #if __aarch64__ asm volatile( "eor v16.16b, v16.16b, v16.16b \n" // sum0 "eor v17.16b, v17.16b, v17.16b \n" // sum0n "lsr w4, %w6, #2 \n"// r4 = nn = L >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n"// for (; k+3<L; k=k+4) "prfm pldl1keep, [%2, #128] \n" "ld1 {v0.8b}, [%2] \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v8.8b, v9.8b, v10.8b, v11.8b}, [%1], #32 \n" "add %2, %2, #4 \n" "sshll v0.8h, v0.8b, #0 \n" // k00 - k03 "sshll v8.8h, v8.8b, #0 \n" // a00 - a70 "sshll v9.8h, v9.8b, #0 \n" // a01 - a71 "sshll v10.8h, v10.8b, #0 \n" // a02 - a72 "sshll v11.8h, v11.8b, #0 \n" // a03 - a73 // k0 "smlal v16.4s, v8.4h, v0.h[0] \n"// sum0 += (a00-a70) * k00 "smlal2 v17.4s, v8.8h, v0.h[0] \n"// // k1 "smlal v16.4s, v9.4h, v0.h[1] \n"// sum0 += (a01-a71) * k01 "smlal2 v17.4s, v9.8h, v0.h[1] \n"// // k2 "smlal v16.4s, v10.4h, v0.h[2] \n"// sum0 += (a02-a72) * k02 "smlal2 v17.4s, v10.8h, v0.h[2] \n"// // k3 "smlal v16.4s, v11.4h, v0.h[3] \n"// sum0 += (a03-a73) * k03 "smlal2 v17.4s, v11.8h, v0.h[3] \n"// "subs w4, w4, #1 \n" "bne 0b \n" "1: \n" // remain loop "and w4, %w6, #3 \n"// w4 = remain = inch & 3; "cmp w4, #0 \n" "beq 3f \n" "2: \n" //"prfm pldl1keep, [%2, #128] \n" "ld1 {v0.8b}, [%2] \n" //"prfm pldl1keep, [%1, #128] \n" "ld1 {v8.8b}, [%1], #8 \n" "add %2, %2, #1 \n" "sshll v0.8h, v0.8b, #0 \n" // k00 - k30 "sshll v8.8h, v8.8b, #0 \n" // a00 - a70 // k0 "smlal v16.4s, v8.4h, v0.h[0] \n"// sum0 += (a00-a70) * k00 "smlal2 v17.4s, v8.8h, v0.h[0] \n"// "subs w4, w4, #1 \n" "bne 2b \n" "3: \n" "st1 {v16.4s, v17.4s}, [%0] \n" : "=r"(output), // %0 "=r"(vb), // %1 "=r"(va) // %2 : "0"(output), "1"(vb), "2"(va), "r"(L) // %6 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17" ); #else asm volatile( // inch loop "vmov.s32 q6, #0 \n" "vmov.s32 q7, #0 \n" "lsr r4, %6, #3 \n"// r4 = nn = inch >> 3 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%1, #128] \n" "vld1.s8 {d4-d7}, [%1]! \n"// tmpr a00-a07,a10-a17,a20-a27,a30-a37 a(inch)(data) "vmovl.s8 q5, d7 \n"// a30-a37 "vmovl.s8 q4, d6 \n"// a20-a27 "vmovl.s8 q3, d5 \n"// a10-a17 "vmovl.s8 q2, d4 \n"// a00-a07 "pld [%2, #128] \n" "vld1.s8 {d0}, [%2]! \n"// kptr k00-k07 k(outch)(inch) "vmovl.s8 q1, d1 \n"// k04,k05,k06,k07 "vmovl.s8 q0, d0 \n"// k00,k01,k02,k03 "vmlal.s16 q6, d4, d0[0] \n"// (a00-a07) * k00 "vmlal.s16 q7, d5, d0[0] \n" "vmlal.s16 q6, d6, d0[1] \n"// (a10-a17) * k01 "vmlal.s16 q7, d7, d0[1] \n" "vmlal.s16 q6, d8, d0[2] \n"// (a20-a27) * k02 "vmlal.s16 q7, d9, d0[2] \n" "vmlal.s16 q6, d10, d0[3] \n"// (a30-a37) * k03 "vmlal.s16 q7, d11, d0[3] \n" "pld [%1, #128] \n" "vld1.s8 {d4-d7}, [%1]! \n"// tmpr a40-a47,a50-a57,a60-a67,a70-a77 a(inch)(data) "vmovl.s8 q5, d7 \n"// a70-a77 "vmovl.s8 q4, d6 \n"// a60-a67 "vmovl.s8 q3, d5 \n"// a50-a57 "vmovl.s8 q2, d4 \n"// a40-a47 "vmlal.s16 q6, d4, d1[0] \n"// (a00-a07) * k00 "vmlal.s16 q7, d5, d1[0] \n" "vmlal.s16 q6, d6, d1[1] \n"// (a10-a17) * k01 "vmlal.s16 q7, d7, d1[1] \n" "vmlal.s16 q6, d8, d1[2] \n"// (a20-a27) * k02 "vmlal.s16 q7, d9, d1[2] \n" "vmlal.s16 q6, d10, d1[3] \n"// (a30-a37) * k03 "vmlal.s16 q7, d11, d1[3] \n" "subs r4, r4, #1 \n" "bne 0b \n"// end for "1: \n" // remain loop "and r4, %6, #7 \n"// r4 = remain = inch & 7 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%1]! \n"// tmpr a00-a07 a(inch)(data) "vld1.s8 {d0}, [%2] \n"// kptr k00 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %2, #1 \n" "vmlal.s16 q6, d2, d0[0] \n"// (a00-a07) * k00 "vmlal.s16 q7, d3, d0[0] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory "vst1.s32 {d12-d15}, [%0] \n" : "=r"(output), // %0 "=r"(vb), // %1 "=r"(va) // %2 : "0"(output), "1"(vb), "2"(va), "r"(L) // %6 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7" ); #endif // __aarch64__ #else int sum[8] = {0}; int k=0; for (; k+7<L; k=k+8) { for (int n=0; n<8; n++) { sum[n] += (int)va[0] * vb[n]; sum[n] += (int)va[1] * vb[n+8]; sum[n] += (int)va[2] * vb[n+16]; sum[n] += (int)va[3] * vb[n+24]; sum[n] += (int)va[4] * vb[n+32]; sum[n] += (int)va[5] * vb[n+40]; sum[n] += (int)va[6] * vb[n+48]; sum[n] += (int)va[7] * vb[n+56]; } va += 8; vb += 64; } for (; k<L; k++) { for (int n=0; n<8; n++) { sum[n] += (int)va[0] * vb[n]; } va += 1; vb += 8; } for (int n=0; n<8; n++) { output[n] = sum[n]; } #endif // __ARM_NEON output += 8; } for (; j<N; j++) { int sum = 0; signed char* vb = bottom_tm.channel(j/8 + j%8); #if __ARM_NEON && __aarch64__ const signed char* va = kernel_tm.channel(i/8 + (i%8)/4 + i%4); #else const signed char* va = kernel_tm.channel(i/4 + i%4); #endif // __ARM_NEON && __aarch64__ for (int k=0; k<L; k++) { sum += (int)va[0] * vb[0]; va += 1; vb += 1; } output[0] = sum; output++; } } } } #endif
ompfor2.c
/* loop scheduling */ #include <stdio.h> #ifdef _OPENMP #include <omp.h> #endif int a[20]; void foo(int lower, int upper, int stride) { int i; #pragma omp single printf("---------default schedule--------------\n"); #pragma omp for nowait for (i=lower;i<upper;i+=stride) { a[i]=i*2; printf("Iteration %2d is carried out by thread %2d\n",\ i, omp_get_thread_num()); } #pragma omp barrier #pragma omp single printf("---------static schedule--------------\n"); #pragma omp for schedule(static) for (i=lower;i<upper;i+=stride) { a[i]=i*2; printf("Iteration %2d is carried out by thread %2d\n",\ i, omp_get_thread_num()); } #pragma omp single printf("---------(static,5) schedule--------------\n"); #pragma omp for schedule(static,5) for (i=lower;i<upper;i+=stride) { a[i]=i*2; printf("Iteration %2d is carried out by thread %2d\n",\ i, omp_get_thread_num()); } #pragma omp single printf("---------(dynamic,3) schedule--------------\n"); #pragma omp for schedule(dynamic,3) for (i=lower;i<upper;i+=stride) { a[i]=i*2; printf("Iteration %2d is carried out by thread %2d\n",\ i, omp_get_thread_num()); } #if 1 #pragma omp single printf("---------(guided) schedule--------------\n"); #pragma omp for schedule(guided) for (i=lower;i<upper;i+=stride) { a[i]=i*2; printf("Iteration %2d is carried out by thread %2d\n",\ i, omp_get_thread_num()); } #endif #pragma omp single printf("---------(runtime) ordered schedule--------------\n"); #pragma omp for schedule(runtime) ordered for (i=lower;i<upper;i+=stride) { a[i]=i*2; printf("Iteration %2d is carried out by thread %2d\n",\ i, omp_get_thread_num()); } } int main(void) { //#pragma omp parallel for schedule (auto) #pragma omp parallel { #pragma omp single printf ("Using %d threads.\n",omp_get_num_threads()); foo(0,20,3); } return 0; }
8110.c
// this source is derived from CHILL AST originally from file '/uufs/chpc.utah.edu/common/home/u1142914/lib/ytopt_vinu/polybench/polybench-code/stencils/heat-3d/kernel.c' as parsed by frontend compiler rose void kernel_heat_3d(int tsteps, int n, double A[120 + 0][120 + 0][120 + 0], double B[120 + 0][120 + 0][120 + 0]) { int t12; int t10; int t8; int t6; int t4; int t2; for (t2 = 1; t2 <= 500; t2 += 1) { #pragma omp parallel for private(t4,t8,t10,t12,t14) for (t4 = 1; t4 <= n - 2; t4 += 8) for (t6 = t4; t6 <= (t4 + 7 < n - 2 ? t4 + 7 : n - 2); t6 += 1) for (t8 = 1; t8 <= n - 2; t8 += 16) for (t10 = t8; t10 <= (t8 + 15 < n - 2 ? t8 + 15 : n - 2); t10 += 1) for (t12 = 1; t12 <= n - 2; t12 += 1) B[t6][t10][t12] = 0.125 * (A[t6 + 1][t10][t12] - 2 * A[t6][t10][t12] + A[t6 - 1][t10][t12]) + 0.125 * (A[t6][t10 + 1][t12] - 2 * A[t6][t10][t12] + A[t6][t10 - 1][t12]) + 0.125 * (A[t6][t10][t12 + 1] - 2 * A[t6][t10][t12] + A[t6][t10][t12 - 1]) + A[t6][t10][t12]; #pragma omp parallel for private(t4,t8,t10,t12,t14) for (t4 = 1; t4 <= n - 2; t4 += 8) for (t6 = t4; t6 <= (t4 + 7 < n - 2 ? t4 + 7 : n - 2); t6 += 1) for (t8 = 1; t8 <= n - 2; t8 += 16) for (t10 = t8; t10 <= (t8 + 15 < n - 2 ? t8 + 15 : n - 2); t10 += 1) for (t12 = 1; t12 <= n - 2; t12 += 1) A[t6][t10][t12] = 0.125 * (B[t6 + 1][t10][t12] - 2 * B[t6][t10][t12] + B[t6 - 1][t10][t12]) + 0.125 * (B[t6][t10 + 1][t12] - 2 * B[t6][t10][t12] + B[t6][t10 - 1][t12]) + 0.125 * (B[t6][t10][t12 + 1] - 2 * B[t6][t10][t12] + B[t6][t10][t12 - 1]) + B[t6][t10][t12]; } }
test.c
#include <stdio.h> #pragma omp requires unified_shared_memory int main() { int a[100]; int *p = &a[0]; int i; for(i=0; i<100; i++) a[i] = i; #pragma omp target data map(tofrom: a, p[0:100]) { #pragma omp target map(tofrom: a, p[0:100]) { int *q = p; for(i=0; i<100; i++) { a[i]++; *q = (*q) + 1; q++; } } } int error = 0; for(i=0; i<100; i++) if (a[i] != i+2) printf("%d, got %d, wanted %d, error %d\n", i, a[i], i+2, ++error); printf("finished with %d errors\n", error); return 1; }
par_ilu_solve.c
/****************************************************************************** * Copyright (c) 1998 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * ILU solve routine * *****************************************************************************/ #include "_hypre_parcsr_ls.h" #include "_hypre_utilities.hpp" #include "par_ilu.h" /*-------------------------------------------------------------------- * hypre_ILUSolve *--------------------------------------------------------------------*/ HYPRE_Int hypre_ILUSolve( void *ilu_vdata, hypre_ParCSRMatrix *A, hypre_ParVector *f, hypre_ParVector *u ) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); // HYPRE_Int i; hypre_ParILUData *ilu_data = (hypre_ParILUData*) ilu_vdata; #ifdef HYPRE_USING_CUDA /* pointers to cusparse data, note that they are not NULL only when needed */ cusparseMatDescr_t matL_des = hypre_ParILUDataMatLMatrixDescription(ilu_data); cusparseMatDescr_t matU_des = hypre_ParILUDataMatUMatrixDescription(ilu_data); void *ilu_solve_buffer = hypre_ParILUDataILUSolveBuffer(ilu_data);//device memory cusparseSolvePolicy_t ilu_solve_policy = hypre_ParILUDataILUSolvePolicy(ilu_data); hypre_CSRMatrix *matALU_d = hypre_ParILUDataMatAILUDevice(ilu_data); hypre_CSRMatrix *matBLU_d = hypre_ParILUDataMatBILUDevice(ilu_data); //hypre_CSRMatrix *matSLU_d = hypre_ParILUDataMatSILUDevice(ilu_data); hypre_CSRMatrix *matE_d = hypre_ParILUDataMatEDevice(ilu_data); hypre_CSRMatrix *matF_d = hypre_ParILUDataMatFDevice(ilu_data); csrsv2Info_t matAL_info = hypre_ParILUDataMatALILUSolveInfo(ilu_data); csrsv2Info_t matAU_info = hypre_ParILUDataMatAUILUSolveInfo(ilu_data); csrsv2Info_t matBL_info = hypre_ParILUDataMatBLILUSolveInfo(ilu_data); csrsv2Info_t matBU_info = hypre_ParILUDataMatBUILUSolveInfo(ilu_data); csrsv2Info_t matSL_info = hypre_ParILUDataMatSLILUSolveInfo(ilu_data); csrsv2Info_t matSU_info = hypre_ParILUDataMatSUILUSolveInfo(ilu_data); hypre_ParCSRMatrix *Aperm = hypre_ParILUDataAperm(ilu_data); //hypre_ParCSRMatrix *R = hypre_ParILUDataR(ilu_data); //hypre_ParCSRMatrix *P = hypre_ParILUDataP(ilu_data); #endif /* get matrices */ HYPRE_Int ilu_type = hypre_ParILUDataIluType(ilu_data); HYPRE_Int *perm = hypre_ParILUDataPerm(ilu_data); HYPRE_Int *qperm = hypre_ParILUDataQPerm(ilu_data); hypre_ParCSRMatrix *matA = hypre_ParILUDataMatA(ilu_data); hypre_ParCSRMatrix *matL = hypre_ParILUDataMatL(ilu_data); HYPRE_Real *matD = hypre_ParILUDataMatD(ilu_data); hypre_ParCSRMatrix *matU = hypre_ParILUDataMatU(ilu_data); #ifndef HYPRE_USING_CUDA hypre_ParCSRMatrix *matmL = hypre_ParILUDataMatLModified(ilu_data); HYPRE_Real *matmD = hypre_ParILUDataMatDModified(ilu_data); hypre_ParCSRMatrix *matmU = hypre_ParILUDataMatUModified(ilu_data); #endif hypre_ParCSRMatrix *matS = hypre_ParILUDataMatS(ilu_data); HYPRE_Int iter, num_procs, my_id; hypre_ParVector *F_array = hypre_ParILUDataF(ilu_data); hypre_ParVector *U_array = hypre_ParILUDataU(ilu_data); /* get settings */ HYPRE_Real tol = hypre_ParILUDataTol(ilu_data); HYPRE_Int logging = hypre_ParILUDataLogging(ilu_data); HYPRE_Int print_level = hypre_ParILUDataPrintLevel(ilu_data); HYPRE_Int max_iter = hypre_ParILUDataMaxIter(ilu_data); HYPRE_Real *norms = hypre_ParILUDataRelResNorms(ilu_data); hypre_ParVector *Ftemp = hypre_ParILUDataFTemp(ilu_data); hypre_ParVector *Utemp = hypre_ParILUDataUTemp(ilu_data); hypre_ParVector *Xtemp = hypre_ParILUDataXTemp(ilu_data); hypre_ParVector *Ytemp = hypre_ParILUDataYTemp(ilu_data); HYPRE_Real *fext = hypre_ParILUDataFExt(ilu_data); HYPRE_Real *uext = hypre_ParILUDataUExt(ilu_data); hypre_ParVector *residual; HYPRE_Real alpha = -1; HYPRE_Real beta = 1; HYPRE_Real conv_factor = 0.0; HYPRE_Real resnorm = 1.0; HYPRE_Real init_resnorm = 0.0; HYPRE_Real rel_resnorm; HYPRE_Real rhs_norm = 0.0; HYPRE_Real old_resnorm; HYPRE_Real ieee_check = 0.0; HYPRE_Real operat_cmplxty = hypre_ParILUDataOperatorComplexity(ilu_data); HYPRE_Int Solve_err_flag; #ifdef HYPRE_USING_CUDA HYPRE_Int test_opt; #endif /* problem size */ HYPRE_Int n = hypre_CSRMatrixNumRows(hypre_ParCSRMatrixDiag(A)); HYPRE_Int nLU = hypre_ParILUDataNLU(ilu_data); HYPRE_Int *u_end = hypre_ParILUDataUEnd(ilu_data); /* Schur system solve */ HYPRE_Solver schur_solver = hypre_ParILUDataSchurSolver(ilu_data); HYPRE_Solver schur_precond = hypre_ParILUDataSchurPrecond(ilu_data); hypre_ParVector *rhs = hypre_ParILUDataRhs(ilu_data); hypre_ParVector *x = hypre_ParILUDataX(ilu_data); /* begin */ HYPRE_ANNOTATE_FUNC_BEGIN; if (logging > 1) { residual = hypre_ParILUDataResidual(ilu_data); } hypre_ParILUDataNumIterations(ilu_data) = 0; hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); /*----------------------------------------------------------------------- * Write the solver parameters *-----------------------------------------------------------------------*/ if (my_id == 0 && print_level > 1) { hypre_ILUWriteSolverParams(ilu_data); } /*----------------------------------------------------------------------- * Initialize the solver error flag *-----------------------------------------------------------------------*/ Solve_err_flag = 0; /*----------------------------------------------------------------------- * write some initial info *-----------------------------------------------------------------------*/ if (my_id == 0 && print_level > 1 && tol > 0.) { hypre_printf("\n\n ILU SOLVER SOLUTION INFO:\n"); } /*----------------------------------------------------------------------- * Compute initial residual and print *-----------------------------------------------------------------------*/ if (print_level > 1 || logging > 1 || tol > 0.) { if ( logging > 1 ) { hypre_ParVectorCopy(f, residual ); if (tol > 0.0) { hypre_ParCSRMatrixMatvec(alpha, A, u, beta, residual ); } resnorm = sqrt(hypre_ParVectorInnerProd( residual, residual )); } else { hypre_ParVectorCopy(f, Ftemp); if (tol > 0.0) { hypre_ParCSRMatrixMatvec(alpha, A, u, beta, Ftemp); } resnorm = sqrt(hypre_ParVectorInnerProd(Ftemp, Ftemp)); } /* Since it is does not diminish performance, attempt to return an error flag and notify users when they supply bad input. */ if (resnorm != 0.) { ieee_check = resnorm / resnorm; /* INF -> NaN conversion */ } if (ieee_check != ieee_check) { /* ...INFs or NaNs in input can make ieee_check a NaN. This test for ieee_check self-equality works on all IEEE-compliant compilers/ machines, c.f. page 8 of "Lecture Notes on the Status of IEEE 754" by W. Kahan, May 31, 1996. Currently (July 2002) this paper may be found at http://HTTP.CS.Berkeley.EDU/~wkahan/ieee754status/IEEE754.PDF */ if (print_level > 0) { hypre_printf("\n\nERROR detected by Hypre ... BEGIN\n"); hypre_printf("ERROR -- hypre_ILUSolve: INFs and/or NaNs detected in input.\n"); hypre_printf("User probably placed non-numerics in supplied A, x_0, or b.\n"); hypre_printf("ERROR detected by Hypre ... END\n\n\n"); } hypre_error(HYPRE_ERROR_GENERIC); HYPRE_ANNOTATE_FUNC_END; return hypre_error_flag; } init_resnorm = resnorm; rhs_norm = sqrt(hypre_ParVectorInnerProd(f, f)); if (rhs_norm > HYPRE_REAL_EPSILON) { rel_resnorm = init_resnorm / rhs_norm; } else { /* rhs is zero, return a zero solution */ hypre_ParVectorSetConstantValues(U_array, 0.0); if (logging > 0) { rel_resnorm = 0.0; hypre_ParILUDataFinalRelResidualNorm(ilu_data) = rel_resnorm; } HYPRE_ANNOTATE_FUNC_END; return hypre_error_flag; } } else { rel_resnorm = 1.; } if (my_id == 0 && print_level > 1) { hypre_printf(" relative\n"); hypre_printf(" residual factor residual\n"); hypre_printf(" -------- ------ --------\n"); hypre_printf(" Initial %e %e\n", init_resnorm, rel_resnorm); } matA = A; U_array = u; F_array = f; /************** Main Solver Loop - always do 1 iteration ************/ iter = 0; while ((rel_resnorm >= tol || iter < 1) && iter < max_iter) { /* Do one solve on LUe=r */ switch (ilu_type) { case 0: case 1: #ifdef HYPRE_USING_CUDA /* Apply GPU-accelerated LU solve */ hypre_ILUSolveCusparseLU(matA, matL_des, matU_des, matBL_info, matBU_info, matBLU_d, ilu_solve_policy, ilu_solve_buffer, F_array, U_array, perm, n, Utemp, Ftemp);//BJ-cusparse #else hypre_ILUSolveLU(matA, F_array, U_array, perm, n, matL, matD, matU, Utemp, Ftemp); //BJ #endif break; case 10: case 11: #ifdef HYPRE_USING_CUDA /* Apply GPU-accelerated LU solve */ hypre_ILUSolveCusparseSchurGMRES(matA, F_array, U_array, perm, nLU, matS, Utemp, Ftemp, schur_solver, schur_precond, rhs, x, u_end, matL_des, matU_des, matBL_info, matBU_info, matSL_info, matSU_info, matBLU_d, matE_d, matF_d, ilu_solve_policy, ilu_solve_buffer);//GMRES-cusparse #else hypre_ILUSolveSchurGMRES(matA, F_array, U_array, perm, perm, nLU, matL, matD, matU, matS, Utemp, Ftemp, schur_solver, schur_precond, rhs, x, u_end); //GMRES #endif break; case 20: case 21: hypre_ILUSolveSchurNSH(matA, F_array, U_array, perm, nLU, matL, matD, matU, matS, Utemp, Ftemp, schur_solver, rhs, x, u_end); //MR+NSH break; case 30: case 31: hypre_ILUSolveLURAS(matA, F_array, U_array, perm, matL, matD, matU, Utemp, Utemp, fext, uext); //RAS break; case 40: case 41: hypre_ILUSolveSchurGMRES(matA, F_array, U_array, perm, qperm, nLU, matL, matD, matU, matS, Utemp, Ftemp, schur_solver, schur_precond, rhs, x, u_end); //GMRES break; case 50: #ifdef HYPRE_USING_CUDA test_opt = hypre_ParILUDataTestOption(ilu_data); hypre_ILUSolveRAPGMRES(matA, F_array, U_array, perm, nLU, matS, Utemp, Ftemp, Xtemp, Ytemp, schur_solver, schur_precond, rhs, x, u_end, matL_des, matU_des, matAL_info, matAU_info, matBL_info, matBU_info, matSL_info, matSU_info, Aperm, matALU_d, matBLU_d, matE_d, matF_d, ilu_solve_policy, ilu_solve_buffer, test_opt);//GMRES-RAP #else hypre_ILUSolveRAPGMRESHOST(matA, F_array, U_array, perm, nLU, matL, matD, matU, matmL, matmD, matmU, Utemp, Ftemp, Xtemp, Ytemp, schur_solver, schur_precond, rhs, x, u_end);//GMRES-RAP #endif break; default: #ifdef HYPRE_USING_CUDA /* Apply GPU-accelerated LU solve */ hypre_ILUSolveCusparseLU(matA, matL_des, matU_des, matBL_info, matBU_info, matBLU_d, ilu_solve_policy, ilu_solve_buffer, F_array, U_array, perm, n, Utemp, Ftemp);//BJ-cusparse #else hypre_ILUSolveLU(matA, F_array, U_array, perm, n, matL, matD, matU, Utemp, Ftemp); //BJ #endif break; } /*--------------------------------------------------------------- * Compute residual and residual norm *----------------------------------------------------------------*/ if (print_level > 1 || logging > 1 || tol > 0.) { old_resnorm = resnorm; if ( logging > 1 ) { hypre_ParVectorCopy(F_array, residual); hypre_ParCSRMatrixMatvec(alpha, matA, U_array, beta, residual ); resnorm = sqrt(hypre_ParVectorInnerProd( residual, residual )); } else { hypre_ParVectorCopy(F_array, Ftemp); hypre_ParCSRMatrixMatvec(alpha, matA, U_array, beta, Ftemp); resnorm = sqrt(hypre_ParVectorInnerProd(Ftemp, Ftemp)); } if (old_resnorm) { conv_factor = resnorm / old_resnorm; } else { conv_factor = resnorm; } if (rhs_norm > HYPRE_REAL_EPSILON) { rel_resnorm = resnorm / rhs_norm; } else { rel_resnorm = resnorm; } norms[iter] = rel_resnorm; } ++iter; hypre_ParILUDataNumIterations(ilu_data) = iter; hypre_ParILUDataFinalRelResidualNorm(ilu_data) = rel_resnorm; if (my_id == 0 && print_level > 1) { hypre_printf(" ILUSolve %2d %e %f %e \n", iter, resnorm, conv_factor, rel_resnorm); } } /* check convergence within max_iter */ if (iter == max_iter && tol > 0.) { Solve_err_flag = 1; hypre_error(HYPRE_ERROR_CONV); } /*----------------------------------------------------------------------- * Print closing statistics * Add operator and grid complexity stats *-----------------------------------------------------------------------*/ if (iter > 0 && init_resnorm) { conv_factor = pow((resnorm / init_resnorm), (1.0 / (HYPRE_Real) iter)); } else { conv_factor = 1.; } if (print_level > 1) { /*** compute operator and grid complexity (fill factor) here ?? ***/ if (my_id == 0) { if (Solve_err_flag == 1) { hypre_printf("\n\n=============================================="); hypre_printf("\n NOTE: Convergence tolerance was not achieved\n"); hypre_printf(" within the allowed %d iterations\n", max_iter); hypre_printf("=============================================="); } hypre_printf("\n\n Average Convergence Factor = %f \n", conv_factor); hypre_printf(" operator = %f\n", operat_cmplxty); } } HYPRE_ANNOTATE_FUNC_END; return hypre_error_flag; } /* Schur Complement solve with GMRES on schur complement * ParCSRMatrix S is already built in ilu data sturcture, here directly use S * L, D and U factors only have local scope (no off-diagonal processor terms) * so apart from the residual calculation (which uses A), the solves with the * L and U factors are local. * S is the global Schur complement * schur_solver is a GMRES solver * schur_precond is the ILU preconditioner for GMRES * rhs and x are helper vector for solving Schur system */ HYPRE_Int hypre_ILUSolveSchurGMRES(hypre_ParCSRMatrix *A, hypre_ParVector *f, hypre_ParVector *u, HYPRE_Int *perm, HYPRE_Int *qperm, HYPRE_Int nLU, hypre_ParCSRMatrix *L, HYPRE_Real* D, hypre_ParCSRMatrix *U, hypre_ParCSRMatrix *S, hypre_ParVector *ftemp, hypre_ParVector *utemp, HYPRE_Solver schur_solver, HYPRE_Solver schur_precond, hypre_ParVector *rhs, hypre_ParVector *x, HYPRE_Int *u_end) { /* data objects for communication */ // MPI_Comm comm = hypre_ParCSRMatrixComm(A); /* data objects for L and U */ hypre_CSRMatrix *L_diag = hypre_ParCSRMatrixDiag(L); HYPRE_Real *L_diag_data = hypre_CSRMatrixData(L_diag); HYPRE_Int *L_diag_i = hypre_CSRMatrixI(L_diag); HYPRE_Int *L_diag_j = hypre_CSRMatrixJ(L_diag); hypre_CSRMatrix *U_diag = hypre_ParCSRMatrixDiag(U); HYPRE_Real *U_diag_data = hypre_CSRMatrixData(U_diag); HYPRE_Int *U_diag_i = hypre_CSRMatrixI(U_diag); HYPRE_Int *U_diag_j = hypre_CSRMatrixJ(U_diag); hypre_Vector *utemp_local = hypre_ParVectorLocalVector(utemp); HYPRE_Real *utemp_data = hypre_VectorData(utemp_local); hypre_Vector *ftemp_local = hypre_ParVectorLocalVector(ftemp); HYPRE_Real *ftemp_data = hypre_VectorData(ftemp_local); HYPRE_Real alpha; HYPRE_Real beta; HYPRE_Int i, j, k1, k2, col; /* problem size */ HYPRE_Int n = hypre_CSRMatrixNumRows(L_diag); // HYPRE_Int m = n - nLU; /* other data objects for computation */ // hypre_Vector *f_local; // HYPRE_Real *f_data; hypre_Vector *rhs_local; HYPRE_Real *rhs_data; hypre_Vector *x_local; HYPRE_Real *x_data; /* begin */ beta = 1.0; alpha = -1.0; /* compute residual */ hypre_ParCSRMatrixMatvecOutOfPlace(alpha, A, u, beta, f, ftemp); /* 1st need to solve LBi*xi = fi * L solve, solve xi put in u_temp upper */ // f_local = hypre_ParVectorLocalVector(f); // f_data = hypre_VectorData(f_local); /* now update with L to solve */ for (i = 0 ; i < nLU ; i ++) { utemp_data[qperm[i]] = ftemp_data[perm[i]]; k1 = L_diag_i[i] ; k2 = L_diag_i[i + 1]; for (j = k1 ; j < k2 ; j ++) { utemp_data[qperm[i]] -= L_diag_data[j] * utemp_data[qperm[L_diag_j[j]]]; } } /* 2nd need to compute g'i = gi - Ei*UBi^-1*xi * now put g'i into the f_temp lower */ for (i = nLU ; i < n ; i ++) { k1 = L_diag_i[i] ; k2 = L_diag_i[i + 1]; for (j = k1 ; j < k2 ; j ++) { col = L_diag_j[j]; ftemp_data[perm[i]] -= L_diag_data[j] * utemp_data[qperm[col]]; } } /* 3rd need to solve global Schur Complement Sy = g' * for now only solve the local system * solve y put in u_temp lower * only solve whe S is not NULL */ if (S) { /*initialize solution to zero for residual equation */ hypre_ParVectorSetConstantValues(x, 0.0); /* setup vectors for solve */ rhs_local = hypre_ParVectorLocalVector(rhs); rhs_data = hypre_VectorData(rhs_local); x_local = hypre_ParVectorLocalVector(x); x_data = hypre_VectorData(x_local); /* set rhs value */ for (i = nLU ; i < n ; i ++) { rhs_data[i - nLU] = ftemp_data[perm[i]]; } /* solve */ HYPRE_GMRESSolve(schur_solver, (HYPRE_Matrix)S, (HYPRE_Vector)rhs, (HYPRE_Vector)x); /* copy value back to original */ for (i = nLU ; i < n ; i ++) { utemp_data[qperm[i]] = x_data[i - nLU]; } } /* 4th need to compute zi = xi - LBi^-1*Fi*yi * put zi in f_temp upper * only do this computation when nLU < n * U is unsorted, search is expensive when unnecessary */ if (nLU < n) { for (i = 0 ; i < nLU ; i ++) { ftemp_data[perm[i]] = utemp_data[qperm[i]]; k1 = u_end[i] ; k2 = U_diag_i[i + 1]; for (j = k1 ; j < k2 ; j ++) { col = U_diag_j[j]; ftemp_data[perm[i]] -= U_diag_data[j] * utemp_data[qperm[col]]; } } for (i = 0 ; i < nLU ; i ++) { utemp_data[qperm[i]] = ftemp_data[perm[i]]; } } /* 5th need to solve UBi*ui = zi */ /* put result in u_temp upper */ for (i = nLU - 1 ; i >= 0 ; i --) { k1 = U_diag_i[i] ; k2 = u_end[i]; for (j = k1 ; j < k2 ; j ++) { col = U_diag_j[j]; utemp_data[qperm[i]] -= U_diag_data[j] * utemp_data[qperm[col]]; } utemp_data[qperm[i]] *= D[i]; } /* done, now everything are in u_temp, update solution */ hypre_ParVectorAxpy(beta, utemp, u); return hypre_error_flag; } /* Newton-Schulz-Hotelling solve * ParCSRMatrix S is already built in ilu data sturcture * S here is the INVERSE of Schur Complement * L, D and U factors only have local scope (no off-diagonal processor terms) * so apart from the residual calculation (which uses A), the solves with the * L and U factors are local. * S is the inverse global Schur complement * rhs and x are helper vector for solving Schur system */ HYPRE_Int hypre_ILUSolveSchurNSH(hypre_ParCSRMatrix *A, hypre_ParVector *f, hypre_ParVector *u, HYPRE_Int *perm, HYPRE_Int nLU, hypre_ParCSRMatrix *L, HYPRE_Real* D, hypre_ParCSRMatrix *U, hypre_ParCSRMatrix *S, hypre_ParVector *ftemp, hypre_ParVector *utemp, HYPRE_Solver schur_solver, hypre_ParVector *rhs, hypre_ParVector *x, HYPRE_Int *u_end) { /* data objects for communication */ // MPI_Comm comm = hypre_ParCSRMatrixComm(A); /* data objects for L and U */ hypre_CSRMatrix *L_diag = hypre_ParCSRMatrixDiag(L); HYPRE_Real *L_diag_data = hypre_CSRMatrixData(L_diag); HYPRE_Int *L_diag_i = hypre_CSRMatrixI(L_diag); HYPRE_Int *L_diag_j = hypre_CSRMatrixJ(L_diag); hypre_CSRMatrix *U_diag = hypre_ParCSRMatrixDiag(U); HYPRE_Real *U_diag_data = hypre_CSRMatrixData(U_diag); HYPRE_Int *U_diag_i = hypre_CSRMatrixI(U_diag); HYPRE_Int *U_diag_j = hypre_CSRMatrixJ(U_diag); hypre_Vector *utemp_local = hypre_ParVectorLocalVector(utemp); HYPRE_Real *utemp_data = hypre_VectorData(utemp_local); hypre_Vector *ftemp_local = hypre_ParVectorLocalVector(ftemp); HYPRE_Real *ftemp_data = hypre_VectorData(ftemp_local); HYPRE_Real alpha; HYPRE_Real beta; HYPRE_Int i, j, k1, k2, col; /* problem size */ HYPRE_Int n = hypre_CSRMatrixNumRows(L_diag); // HYPRE_Int m = n - nLU; /* other data objects for computation */ // hypre_Vector *f_local; // HYPRE_Real *f_data; hypre_Vector *rhs_local; HYPRE_Real *rhs_data; hypre_Vector *x_local; HYPRE_Real *x_data; /* begin */ beta = 1.0; alpha = -1.0; /* compute residual */ hypre_ParCSRMatrixMatvecOutOfPlace(alpha, A, u, beta, f, ftemp); /* 1st need to solve LBi*xi = fi * L solve, solve xi put in u_temp upper */ // f_local = hypre_ParVectorLocalVector(f); // f_data = hypre_VectorData(f_local); /* now update with L to solve */ for (i = 0 ; i < nLU ; i ++) { utemp_data[perm[i]] = ftemp_data[perm[i]]; k1 = L_diag_i[i] ; k2 = L_diag_i[i + 1]; for (j = k1 ; j < k2 ; j ++) { utemp_data[perm[i]] -= L_diag_data[j] * utemp_data[perm[L_diag_j[j]]]; } } /* 2nd need to compute g'i = gi - Ei*UBi^-1*xi * now put g'i into the f_temp lower */ for (i = nLU ; i < n ; i ++) { k1 = L_diag_i[i] ; k2 = L_diag_i[i + 1]; for (j = k1 ; j < k2 ; j ++) { col = L_diag_j[j]; ftemp_data[perm[i]] -= L_diag_data[j] * utemp_data[perm[col]]; } } /* 3rd need to solve global Schur Complement Sy = g' * for now only solve the local system * solve y put in u_temp lower * only solve when S is not NULL */ if (S) { /*initialize solution to zero for residual equation */ hypre_ParVectorSetConstantValues(x, 0.0); /* setup vectors for solve */ rhs_local = hypre_ParVectorLocalVector(rhs); rhs_data = hypre_VectorData(rhs_local); x_local = hypre_ParVectorLocalVector(x); x_data = hypre_VectorData(x_local); /* set rhs value */ for (i = nLU ; i < n ; i ++) { rhs_data[i - nLU] = ftemp_data[perm[i]]; } /* Solve Schur system with approx inverse * x = S*rhs */ hypre_NSHSolve(schur_solver, S, rhs, x); /* copy value back to original */ for (i = nLU ; i < n ; i ++) { utemp_data[perm[i]] = x_data[i - nLU]; } } /* 4th need to compute zi = xi - LBi^-1*yi * put zi in f_temp upper * only do this computation when nLU < n * U is unsorted, search is expensive when unnecessary */ if (nLU < n) { for (i = 0 ; i < nLU ; i ++) { ftemp_data[perm[i]] = utemp_data[perm[i]]; k1 = u_end[i] ; k2 = U_diag_i[i + 1]; for (j = k1 ; j < k2 ; j ++) { col = U_diag_j[j]; ftemp_data[perm[i]] -= U_diag_data[j] * utemp_data[perm[col]]; } } for (i = 0 ; i < nLU ; i ++) { utemp_data[perm[i]] = ftemp_data[perm[i]]; } } /* 5th need to solve UBi*ui = zi */ /* put result in u_temp upper */ for (i = nLU - 1 ; i >= 0 ; i --) { k1 = U_diag_i[i] ; k2 = u_end[i]; for (j = k1 ; j < k2 ; j ++) { col = U_diag_j[j]; utemp_data[perm[i]] -= U_diag_data[j] * utemp_data[perm[col]]; } utemp_data[perm[i]] *= D[i]; } /* done, now everything are in u_temp, update solution */ hypre_ParVectorAxpy(beta, utemp, u); return hypre_error_flag; } /* Incomplete LU solve * L, D and U factors only have local scope (no off-diagonal processor terms) * so apart from the residual calculation (which uses A), the solves with the * L and U factors are local. */ HYPRE_Int hypre_ILUSolveLU(hypre_ParCSRMatrix *A, hypre_ParVector *f, hypre_ParVector *u, HYPRE_Int *perm, HYPRE_Int nLU, hypre_ParCSRMatrix *L, HYPRE_Real* D, hypre_ParCSRMatrix *U, hypre_ParVector *ftemp, hypre_ParVector *utemp) { hypre_CSRMatrix *L_diag = hypre_ParCSRMatrixDiag(L); HYPRE_Real *L_diag_data = hypre_CSRMatrixData(L_diag); HYPRE_Int *L_diag_i = hypre_CSRMatrixI(L_diag); HYPRE_Int *L_diag_j = hypre_CSRMatrixJ(L_diag); hypre_CSRMatrix *U_diag = hypre_ParCSRMatrixDiag(U); HYPRE_Real *U_diag_data = hypre_CSRMatrixData(U_diag); HYPRE_Int *U_diag_i = hypre_CSRMatrixI(U_diag); HYPRE_Int *U_diag_j = hypre_CSRMatrixJ(U_diag); hypre_Vector *utemp_local = hypre_ParVectorLocalVector(utemp); HYPRE_Real *utemp_data = hypre_VectorData(utemp_local); hypre_Vector *ftemp_local = hypre_ParVectorLocalVector(ftemp); HYPRE_Real *ftemp_data = hypre_VectorData(ftemp_local); HYPRE_Real alpha; HYPRE_Real beta; HYPRE_Int i, j, k1, k2; /* begin */ alpha = -1.0; beta = 1.0; /* Initialize Utemp to zero. * This is necessary for correctness, when we use optimized * vector operations in the case where sizeof(L, D or U) < sizeof(A) */ //hypre_ParVectorSetConstantValues( utemp, 0.); /* compute residual */ hypre_ParCSRMatrixMatvecOutOfPlace(alpha, A, u, beta, f, ftemp); /* L solve - Forward solve */ /* copy rhs to account for diagonal of L (which is identity) */ for ( i = 0; i < nLU; i++ ) { utemp_data[perm[i]] = ftemp_data[perm[i]]; } /* update with remaining (off-diagonal) entries of L */ for ( i = 0; i < nLU; i++ ) { k1 = L_diag_i[i] ; k2 = L_diag_i[i + 1]; for (j = k1; j < k2; j++) { utemp_data[perm[i]] -= L_diag_data[j] * utemp_data[perm[L_diag_j[j]]]; } } /*-------------------- U solve - Backward substitution */ for ( i = nLU - 1; i >= 0; i-- ) { /* first update with the remaining (off-diagonal) entries of U */ k1 = U_diag_i[i] ; k2 = U_diag_i[i + 1]; for (j = k1; j < k2; j++) { utemp_data[perm[i]] -= U_diag_data[j] * utemp_data[perm[U_diag_j[j]]]; } /* diagonal scaling (contribution from D. Note: D is stored as its inverse) */ utemp_data[perm[i]] *= D[i]; } /* Update solution */ hypre_ParVectorAxpy(beta, utemp, u); return hypre_error_flag; } /* Incomplete LU solve RAS * L, D and U factors only have local scope (no off-diagonal processor terms) * so apart from the residual calculation (which uses A), the solves with the * L and U factors are local. * fext and uext are tempory arrays for external data */ HYPRE_Int hypre_ILUSolveLURAS(hypre_ParCSRMatrix *A, hypre_ParVector *f, hypre_ParVector *u, HYPRE_Int *perm, hypre_ParCSRMatrix *L, HYPRE_Real* D, hypre_ParCSRMatrix *U, hypre_ParVector *ftemp, hypre_ParVector *utemp, HYPRE_Real *fext, HYPRE_Real *uext) { hypre_ParCSRCommPkg *comm_pkg; hypre_ParCSRCommHandle *comm_handle; HYPRE_Int num_sends, begin, end; hypre_CSRMatrix *L_diag = hypre_ParCSRMatrixDiag(L); HYPRE_Real *L_diag_data = hypre_CSRMatrixData(L_diag); HYPRE_Int *L_diag_i = hypre_CSRMatrixI(L_diag); HYPRE_Int *L_diag_j = hypre_CSRMatrixJ(L_diag); hypre_CSRMatrix *U_diag = hypre_ParCSRMatrixDiag(U); HYPRE_Real *U_diag_data = hypre_CSRMatrixData(U_diag); HYPRE_Int *U_diag_i = hypre_CSRMatrixI(U_diag); HYPRE_Int *U_diag_j = hypre_CSRMatrixJ(U_diag); HYPRE_Int n = hypre_CSRMatrixNumCols(hypre_ParCSRMatrixDiag(A)); HYPRE_Int m = hypre_CSRMatrixNumCols(hypre_ParCSRMatrixOffd(A)); // HYPRE_Int buffer_size; HYPRE_Int n_total = m + n; HYPRE_Int idx; HYPRE_Int jcol; HYPRE_Int col; hypre_Vector *utemp_local = hypre_ParVectorLocalVector(utemp); HYPRE_Real *utemp_data = hypre_VectorData(utemp_local); hypre_Vector *ftemp_local = hypre_ParVectorLocalVector(ftemp); HYPRE_Real *ftemp_data = hypre_VectorData(ftemp_local); HYPRE_Real alpha; HYPRE_Real beta; HYPRE_Int i, j, k1, k2; /* begin */ alpha = -1.0; beta = 1.0; /* prepare for communication */ comm_pkg = hypre_ParCSRMatrixCommPkg(A); /* setup if not yet built */ if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } /* Initialize Utemp to zero. * This is necessary for correctness, when we use optimized * vector operations in the case where sizeof(L, D or U) < sizeof(A) */ //hypre_ParVectorSetConstantValues( utemp, 0.); /* compute residual */ hypre_ParCSRMatrixMatvecOutOfPlace(alpha, A, u, beta, f, ftemp); /* communication to get external data */ /* get total num of send */ num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); begin = hypre_ParCSRCommPkgSendMapStart(comm_pkg, 0); end = hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends); /* copy new index into send_buf */ for (i = begin ; i < end ; i ++) { /* all we need is just send out data, we don't need to worry about the * permutation of offd part, actually we don't need to worry about * permutation at all * borrow uext as send buffer . */ uext[i - begin] = ftemp_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, i)]; } /* main communication */ comm_handle = hypre_ParCSRCommHandleCreate(1, comm_pkg, uext, fext); hypre_ParCSRCommHandleDestroy(comm_handle); /* L solve - Forward solve */ for ( i = 0 ; i < n_total ; i ++) { k1 = L_diag_i[i] ; k2 = L_diag_i[i + 1]; if ( i < n ) { /* diag part */ utemp_data[perm[i]] = ftemp_data[perm[i]]; for (j = k1; j < k2; j++) { col = L_diag_j[j]; if ( col < n ) { utemp_data[perm[i]] -= L_diag_data[j] * utemp_data[perm[col]]; } else { jcol = col - n; utemp_data[perm[i]] -= L_diag_data[j] * uext[jcol]; } } } else { /* offd part */ idx = i - n; uext[idx] = fext[idx]; for (j = k1; j < k2; j++) { col = L_diag_j[j]; if (col < n) { uext[idx] -= L_diag_data[j] * utemp_data[perm[col]]; } else { jcol = col - n; uext[idx] -= L_diag_data[j] * uext[jcol]; } } } } /*-------------------- U solve - Backward substitution */ for ( i = n_total - 1; i >= 0; i-- ) { /* first update with the remaining (off-diagonal) entries of U */ k1 = U_diag_i[i] ; k2 = U_diag_i[i + 1]; if ( i < n ) { /* diag part */ for (j = k1; j < k2; j++) { col = U_diag_j[j]; if ( col < n ) { utemp_data[perm[i]] -= U_diag_data[j] * utemp_data[perm[col]]; } else { jcol = col - n; utemp_data[perm[i]] -= U_diag_data[j] * uext[jcol]; } } /* diagonal scaling (contribution from D. Note: D is stored as its inverse) */ utemp_data[perm[i]] *= D[i]; } else { /* 2nd part of offd */ idx = i - n; for (j = k1; j < k2; j++) { col = U_diag_j[j]; if ( col < n ) { uext[idx] -= U_diag_data[j] * utemp_data[perm[col]]; } else { jcol = col - n; uext[idx] -= U_diag_data[j] * uext[jcol]; } } /* diagonal scaling (contribution from D. Note: D is stored as its inverse) */ uext[idx] *= D[i]; } } /* Update solution */ hypre_ParVectorAxpy(beta, utemp, u); return hypre_error_flag; } #ifdef HYPRE_USING_CUDA /* Permutation function (for GPU version, can just call thrust) * option 00: perm integer array * option 01: rperm integer array * option 10: perm real array * option 11: rperm real array * */ HYPRE_Int hypre_ILUSeqVectorPerm(void *vectori, void *vectoro, HYPRE_Int size, HYPRE_Int *perm, HYPRE_Int option) { cudaDeviceSynchronize(); HYPRE_Int i; switch (option) { case 00: { HYPRE_Int *ivectori = (HYPRE_Int *) vectori; HYPRE_Int *ivectoro = (HYPRE_Int *) vectoro; for (i = 0 ; i < size ; i ++) { ivectoro[i] = ivectori[perm[i]]; } break; } case 01: { HYPRE_Int *ivectori = (HYPRE_Int *) vectori; HYPRE_Int *ivectoro = (HYPRE_Int *) vectoro; for (i = 0 ; i < size ; i ++) { ivectoro[perm[i]] = ivectori[i]; } break; } case 10: { HYPRE_Real *dvectori = (HYPRE_Real *) vectori; HYPRE_Real *dvectoro = (HYPRE_Real *) vectoro; for (i = 0 ; i < size ; i ++) { dvectoro[i] = dvectori[perm[i]]; } break; } case 11: { HYPRE_Real *dvectori = (HYPRE_Real *) vectori; HYPRE_Real *dvectoro = (HYPRE_Real *) vectoro; for (i = 0 ; i < size ; i ++) { dvectoro[perm[i]] = dvectori[i]; } break; } default: { printf("Error option in ILUSeqVectorPerm"); hypre_assert(1 == 0); } } return hypre_error_flag; } /* Incomplete LU solve (GPU) * L, D and U factors only have local scope (no off-diagonal processor terms) * so apart from the residual calculation (which uses A), the solves with the * L and U factors are local. */ HYPRE_Int hypre_ILUSolveCusparseLU(hypre_ParCSRMatrix *A, cusparseMatDescr_t matL_des, cusparseMatDescr_t matU_des, csrsv2Info_t matL_info, csrsv2Info_t matU_info, hypre_CSRMatrix *matLU_d, cusparseSolvePolicy_t ilu_solve_policy, void *ilu_solve_buffer, hypre_ParVector *f, hypre_ParVector *u, HYPRE_Int *perm, HYPRE_Int n, hypre_ParVector *ftemp, hypre_ParVector *utemp) { /* Only solve when we have stuffs to be solved */ if (n == 0) { return hypre_error_flag; } /* ILU data */ HYPRE_Real *LU_data = hypre_CSRMatrixData(matLU_d); HYPRE_Int *LU_i = hypre_CSRMatrixI(matLU_d); HYPRE_Int *LU_j = hypre_CSRMatrixJ(matLU_d); HYPRE_Int nnz = LU_i[n]; hypre_Vector *utemp_local = hypre_ParVectorLocalVector(utemp); HYPRE_Real *utemp_data = hypre_VectorData(utemp_local); hypre_Vector *ftemp_local = hypre_ParVectorLocalVector(ftemp); HYPRE_Real *ftemp_data = hypre_VectorData(ftemp_local); HYPRE_Real alpha; HYPRE_Real beta; //HYPRE_Int i, j, k1, k2; HYPRE_Int isDoublePrecision = sizeof(HYPRE_Complex) == sizeof(hypre_double); HYPRE_Int isSinglePrecision = sizeof(HYPRE_Complex) == sizeof(hypre_double) / 2; hypre_assert(isDoublePrecision || isSinglePrecision); /* begin */ alpha = -1.0; beta = 1.0; cusparseHandle_t handle = hypre_HandleCusparseHandle(hypre_handle()); /* Initialize Utemp to zero. * This is necessary for correctness, when we use optimized * vector operations in the case where sizeof(L, D or U) < sizeof(A) */ //hypre_ParVectorSetConstantValues( utemp, 0.); /* compute residual */ hypre_ParCSRMatrixMatvecOutOfPlace(alpha, A, u, beta, f, ftemp); /* apply permutation */ HYPRE_THRUST_CALL(gather, perm, perm + n, ftemp_data, utemp_data); if (isDoublePrecision) { /* L solve - Forward solve */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, n, nnz, (hypre_double *) &beta, matL_des, (hypre_double *) LU_data, LU_i, LU_j, matL_info, (hypre_double *) utemp_data, (hypre_double *) ftemp_data, ilu_solve_policy, ilu_solve_buffer)); /* U solve - Backward substitution */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, n, nnz, (hypre_double *) &beta, matU_des, (hypre_double *) LU_data, LU_i, LU_j, matU_info, (hypre_double *) ftemp_data, (hypre_double *) utemp_data, ilu_solve_policy, ilu_solve_buffer)); } else if (isSinglePrecision) { /* L solve - Forward solve */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, n, nnz, (float *) &beta, matL_des, (float *) LU_data, LU_i, LU_j, matL_info, (float *) utemp_data, (float *) ftemp_data, ilu_solve_policy, ilu_solve_buffer)); /* U solve - Backward substitution */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, n, nnz, (float *) &beta, matU_des, (float *) LU_data, LU_i, LU_j, matU_info, (float *) ftemp_data, (float *) utemp_data, ilu_solve_policy, ilu_solve_buffer)); } /* apply reverse permutation */ HYPRE_THRUST_CALL(scatter, utemp_data, utemp_data + n, perm, ftemp_data); /* Update solution */ hypre_ParVectorAxpy(beta, ftemp, u); return hypre_error_flag; } /* Schur Complement solve with GMRES on schur complement * ParCSRMatrix S is already built in ilu data sturcture, here directly use S * L, D and U factors only have local scope (no off-diagonal processor terms) * so apart from the residual calculation (which uses A), the solves with the * L and U factors are local. * S is the global Schur complement * schur_solver is a GMRES solver * schur_precond is the ILU preconditioner for GMRES * rhs and x are helper vector for solving Schur system */ HYPRE_Int hypre_ILUSolveCusparseSchurGMRES(hypre_ParCSRMatrix *A, hypre_ParVector *f, hypre_ParVector *u, HYPRE_Int *perm, HYPRE_Int nLU, hypre_ParCSRMatrix *S, hypre_ParVector *ftemp, hypre_ParVector *utemp, HYPRE_Solver schur_solver, HYPRE_Solver schur_precond, hypre_ParVector *rhs, hypre_ParVector *x, HYPRE_Int *u_end, cusparseMatDescr_t matL_des, cusparseMatDescr_t matU_des, csrsv2Info_t matBL_info, csrsv2Info_t matBU_info, csrsv2Info_t matSL_info, csrsv2Info_t matSU_info, hypre_CSRMatrix *matBLU_d, hypre_CSRMatrix *matE_d, hypre_CSRMatrix *matF_d, cusparseSolvePolicy_t ilu_solve_policy, void *ilu_solve_buffer) { /* If we don't have S block, just do one L solve and one U solve */ if (!S) { /* Just call BJ cusparse and return */ return hypre_ILUSolveCusparseLU(A, matL_des, matU_des, matBL_info, matBU_info, matBLU_d, ilu_solve_policy, ilu_solve_buffer, f, u, perm, nLU, ftemp, utemp); } /* data objects for communication */ // MPI_Comm comm = hypre_ParCSRMatrixComm(A); /* data objects for temp vector */ hypre_Vector *utemp_local = hypre_ParVectorLocalVector(utemp); HYPRE_Real *utemp_data = hypre_VectorData(utemp_local); hypre_Vector *ftemp_local = hypre_ParVectorLocalVector(ftemp); HYPRE_Real *ftemp_data = hypre_VectorData(ftemp_local); hypre_Vector *rhs_local = hypre_ParVectorLocalVector(rhs); HYPRE_Real *rhs_data = hypre_VectorData(rhs_local); hypre_Vector *x_local = hypre_ParVectorLocalVector(x); HYPRE_Real *x_data = hypre_VectorData(x_local); HYPRE_Real alpha; HYPRE_Real beta; //HYPRE_Real gamma; //HYPRE_Int i, j, k1, k2, col; /* problem size */ HYPRE_Int *BLU_i = NULL; HYPRE_Int *BLU_j = NULL; HYPRE_Real *BLU_data = NULL; HYPRE_Int BLU_nnz = 0; hypre_CSRMatrix *matSLU_d = hypre_ParCSRMatrixDiag(S); HYPRE_Int *SLU_i = hypre_CSRMatrixI(matSLU_d); HYPRE_Int *SLU_j = hypre_CSRMatrixJ(matSLU_d); HYPRE_Real *SLU_data = hypre_CSRMatrixData(matSLU_d); HYPRE_Int m = hypre_CSRMatrixNumRows(matSLU_d); HYPRE_Int n = nLU + m; HYPRE_Int SLU_nnz = SLU_i[m]; hypre_Vector *ftemp_upper = hypre_SeqVectorCreate(nLU); hypre_Vector *utemp_lower = hypre_SeqVectorCreate(m); hypre_VectorOwnsData(ftemp_upper) = 0; hypre_VectorOwnsData(utemp_lower) = 0; hypre_VectorData(ftemp_upper) = ftemp_data; hypre_VectorData(utemp_lower) = utemp_data + nLU; hypre_SeqVectorInitialize(ftemp_upper); hypre_SeqVectorInitialize(utemp_lower); if ( nLU > 0) { BLU_i = hypre_CSRMatrixI(matBLU_d); BLU_j = hypre_CSRMatrixJ(matBLU_d); BLU_data = hypre_CSRMatrixData(matBLU_d); BLU_nnz = BLU_i[nLU]; } /* begin */ beta = 1.0; alpha = -1.0; //gamma = 0.0; HYPRE_Int isDoublePrecision = sizeof(HYPRE_Complex) == sizeof(hypre_double); HYPRE_Int isSinglePrecision = sizeof(HYPRE_Complex) == sizeof(hypre_double) / 2; hypre_assert(isDoublePrecision || isSinglePrecision); cusparseHandle_t handle = hypre_HandleCusparseHandle(hypre_handle()); /* compute residual */ hypre_ParCSRMatrixMatvecOutOfPlace(alpha, A, u, beta, f, ftemp); /* 1st need to solve LBi*xi = fi * L solve, solve xi put in u_temp upper */ /* apply permutation before we can start our solve */ HYPRE_THRUST_CALL(gather, perm, perm + n, ftemp_data, utemp_data); if (nLU > 0) { /* This solve won't touch data in utemp, thus, gi is still in utemp_lower */ if (isDoublePrecision) { /* L solve - Forward solve */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, nLU, BLU_nnz, (hypre_double *) &beta, matL_des, (hypre_double *) BLU_data, BLU_i, BLU_j, matBL_info, (hypre_double *) utemp_data, (hypre_double *) ftemp_data, ilu_solve_policy, ilu_solve_buffer)); } else if (isSinglePrecision) { /* L solve - Forward solve */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, nLU, BLU_nnz, (float *) &beta, matL_des, (float *) BLU_data, BLU_i, BLU_j, matBL_info, (float *) utemp_data, (float *) ftemp_data, ilu_solve_policy, ilu_solve_buffer)); } /* 2nd need to compute g'i = gi - Ei*UBi^{-1}*xi * Ei*UBi^{-1} is exactly the matE_d here * Now: LBi^{-1}f_i is in ftemp_upper * gi' is in utemp_lower */ hypre_CSRMatrixMatvec(alpha, matE_d, ftemp_upper, beta, utemp_lower); } /* 3rd need to solve global Schur Complement M^{-1}Sy = M^{-1}g' * for now only solve the local system * solve y put in u_temp lower * only solve whe S is not NULL */ /* setup vectors for solve * rhs = M^{-1}g' */ if (m > 0) { if (isDoublePrecision) { /* L solve */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, m, SLU_nnz, (hypre_double *) &beta, matL_des, (hypre_double *) SLU_data, SLU_i, SLU_j, matSL_info, (hypre_double *) utemp_data + nLU, (hypre_double *) ftemp_data + nLU, ilu_solve_policy, ilu_solve_buffer)); /* U solve */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, m, SLU_nnz, (hypre_double *) &beta, matU_des, (hypre_double *) SLU_data, SLU_i, SLU_j, matSU_info, (hypre_double *) ftemp_data + nLU, (hypre_double *) rhs_data, ilu_solve_policy, ilu_solve_buffer)); } else if (isSinglePrecision) { /* L solve */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, m, SLU_nnz, (float *) &beta, matL_des, (float *) SLU_data, SLU_i, SLU_j, matSL_info, (float *) utemp_data + nLU, (float *) ftemp_data + nLU, ilu_solve_policy, ilu_solve_buffer)); /* U solve */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, m, SLU_nnz, (float *) &beta, matU_des, (float *) SLU_data, SLU_i, SLU_j, matSU_info, (float *) ftemp_data + nLU, (float *) rhs_data, ilu_solve_policy, ilu_solve_buffer)); } } /* solve */ /* with tricky initial guess */ //hypre_Vector *tv = hypre_ParVectorLocalVector(x); //HYPRE_Real *tz = hypre_VectorData(tv); HYPRE_GMRESSolve(schur_solver, (HYPRE_Matrix)schur_precond, (HYPRE_Vector)rhs, (HYPRE_Vector)x); /* 4th need to compute zi = xi - LBi^-1*yi * put zi in f_temp upper * only do this computation when nLU < n * U is unsorted, search is expensive when unnecessary */ if (nLU > 0) { hypre_CSRMatrixMatvec(alpha, matF_d, x_local, beta, ftemp_upper); /* 5th need to solve UBi*ui = zi */ /* put result in u_temp upper */ if (isDoublePrecision) { /* U solve - Forward solve */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, nLU, BLU_nnz, (hypre_double *) &beta, matU_des, (hypre_double *) BLU_data, BLU_i, BLU_j, matBU_info, (hypre_double *) ftemp_data, (hypre_double *) utemp_data, ilu_solve_policy, ilu_solve_buffer)); } else if (isSinglePrecision) { /* U solve - Forward solve */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, nLU, BLU_nnz, (float *) &beta, matU_des, (float *) BLU_data, BLU_i, BLU_j, matBU_info, (float *) ftemp_data, (float *) utemp_data, ilu_solve_policy, ilu_solve_buffer)); } } /* copy lower part solution into u_temp as well */ hypre_TMemcpy(utemp_data + nLU, x_data, HYPRE_Real, m, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE); /* perm back */ HYPRE_THRUST_CALL(scatter, utemp_data, utemp_data + n, perm, ftemp_data); /* done, now everything are in u_temp, update solution */ hypre_ParVectorAxpy(beta, ftemp, u); hypre_SeqVectorDestroy(ftemp_upper); hypre_SeqVectorDestroy(utemp_lower); return hypre_error_flag; } /* Schur Complement solve with GMRES on schur complement, RAP style * ParCSRMatrix S is already built in ilu data sturcture, here directly use S * L, D and U factors only have local scope (no off-diagonal processor terms) * so apart from the residual calculation (which uses A), the solves with the * L and U factors are local. * S is the global Schur complement * schur_solver is a GMRES solver * schur_precond is the ILU preconditioner for GMRES * rhs and x are helper vector for solving Schur system */ HYPRE_Int hypre_ILUSolveRAPGMRES(hypre_ParCSRMatrix *A, hypre_ParVector *f, hypre_ParVector *u, HYPRE_Int *perm, HYPRE_Int nLU, hypre_ParCSRMatrix *S, hypre_ParVector *ftemp, hypre_ParVector *utemp, hypre_ParVector *xtemp, hypre_ParVector *ytemp, HYPRE_Solver schur_solver, HYPRE_Solver schur_precond, hypre_ParVector *rhs, hypre_ParVector *x, HYPRE_Int *u_end, cusparseMatDescr_t matL_des, cusparseMatDescr_t matU_des, csrsv2Info_t matAL_info, csrsv2Info_t matAU_info, csrsv2Info_t matBL_info, csrsv2Info_t matBU_info, csrsv2Info_t matSL_info, csrsv2Info_t matSU_info, hypre_ParCSRMatrix *Aperm, hypre_CSRMatrix *matALU_d, hypre_CSRMatrix *matBLU_d, hypre_CSRMatrix *matE_d, hypre_CSRMatrix *matF_d, cusparseSolvePolicy_t ilu_solve_policy, void *ilu_solve_buffer, HYPRE_Int test_opt) { /* data objects for communication */ // MPI_Comm comm = hypre_ParCSRMatrixComm(A); /* data objects for temp vector */ hypre_Vector *utemp_local = hypre_ParVectorLocalVector(utemp); HYPRE_Real *utemp_data = hypre_VectorData(utemp_local); hypre_Vector *ftemp_local = hypre_ParVectorLocalVector(ftemp); HYPRE_Real *ftemp_data = hypre_VectorData(ftemp_local); hypre_Vector *xtemp_local = hypre_ParVectorLocalVector(xtemp); HYPRE_Real *xtemp_data = hypre_VectorData(xtemp_local); //hypre_Vector *ytemp_local = hypre_ParVectorLocalVector(ytemp); //HYPRE_Real *ytemp_data = hypre_VectorData(ytemp_local); hypre_Vector *rhs_local = hypre_ParVectorLocalVector(rhs); HYPRE_Real *rhs_data = hypre_VectorData(rhs_local); hypre_Vector *x_local = hypre_ParVectorLocalVector(x); HYPRE_Real *x_data = hypre_VectorData(x_local); //HYPRE_Int i, j, k1, k2, col; /* problem size */ HYPRE_Int *ALU_i = hypre_CSRMatrixI(matALU_d); HYPRE_Int *ALU_j = hypre_CSRMatrixJ(matALU_d); HYPRE_Real *ALU_data = hypre_CSRMatrixData(matALU_d); HYPRE_Int *BLU_i = hypre_CSRMatrixI(matBLU_d); HYPRE_Int *BLU_j = hypre_CSRMatrixJ(matBLU_d); HYPRE_Real *BLU_data = hypre_CSRMatrixData(matBLU_d); HYPRE_Int BLU_nnz = BLU_i[nLU]; hypre_CSRMatrix *matSLU_d = hypre_ParCSRMatrixDiag(S); HYPRE_Int *SLU_i = hypre_CSRMatrixI(matSLU_d); HYPRE_Int *SLU_j = hypre_CSRMatrixJ(matSLU_d); HYPRE_Real *SLU_data = hypre_CSRMatrixData(matSLU_d); HYPRE_Int m = hypre_CSRMatrixNumRows(matSLU_d); HYPRE_Int n = nLU + m; HYPRE_Int SLU_nnz = SLU_i[m]; HYPRE_Int ALU_nnz = ALU_i[n]; hypre_Vector *ftemp_upper = hypre_SeqVectorCreate(nLU); hypre_Vector *utemp_lower = hypre_SeqVectorCreate(m); hypre_VectorOwnsData(ftemp_upper) = 0; hypre_VectorOwnsData(utemp_lower) = 0; hypre_VectorData(ftemp_upper) = ftemp_data; hypre_VectorData(utemp_lower) = utemp_data + nLU; hypre_SeqVectorInitialize(ftemp_upper); hypre_SeqVectorInitialize(utemp_lower); /* begin */ HYPRE_Real one = 1.0; HYPRE_Real mone = -1.0; HYPRE_Real zero = 0.0; HYPRE_Int isDoublePrecision = sizeof(HYPRE_Complex) == sizeof(hypre_double); HYPRE_Int isSinglePrecision = sizeof(HYPRE_Complex) == sizeof(hypre_double) / 2; hypre_assert(isDoublePrecision || isSinglePrecision); cusparseHandle_t handle = hypre_HandleCusparseHandle(hypre_handle()); switch (test_opt) { case 1: case 3: { /* E and F */ /* compute residual */ hypre_ParCSRMatrixMatvecOutOfPlace(mone, A, u, one, f, utemp); /* apply permutation before we can start our solve * Au=f -> (PAQ)Q'u=Pf */ HYPRE_THRUST_CALL(gather, perm, perm + n, utemp_data, ftemp_data); /* A-smoothing * x = [UA\(LA\(P*f_u))] fill to xtemp */ if (n > 0) { if (isDoublePrecision) { /* L solve - Forward solve */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, n, ALU_nnz, (hypre_double *) &one, matL_des, (hypre_double *) ALU_data, ALU_i, ALU_j, matAL_info, (hypre_double *) ftemp_data, (hypre_double *) utemp_data, ilu_solve_policy, ilu_solve_buffer)); /* U solve - Forward solve */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, n, ALU_nnz, (hypre_double *) &one, matU_des, (hypre_double *) ALU_data, ALU_i, ALU_j, matAU_info, (hypre_double *) utemp_data, (hypre_double *) xtemp_data, ilu_solve_policy, ilu_solve_buffer)); } else if (isSinglePrecision) { /* L solve - Forward solve */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, n, ALU_nnz, (float *) &one, matL_des, (float *) ALU_data, ALU_i, ALU_j, matAL_info, (float *) ftemp_data, (float *) utemp_data, ilu_solve_policy, ilu_solve_buffer)); /* U solve - Forward solve */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, n, ALU_nnz, (float *) &one, matU_des, (float *) ALU_data, ALU_i, ALU_j, matAU_info, (float *) utemp_data, (float *) xtemp_data, ilu_solve_policy, ilu_solve_buffer)); } } /* residual, we should not touch xtemp for now * r = R*(f-PAQx) */ hypre_ParCSRMatrixMatvec(mone, Aperm, xtemp, one, ftemp); /* with R is complex */ /* copy partial data in */ hypre_TMemcpy( rhs_data, ftemp_data + nLU, HYPRE_Real, m, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE); /* solve L^{-1} */ if (nLU > 0) { if (isDoublePrecision) { /* L solve */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, nLU, BLU_nnz, (hypre_double *) &one, matL_des, (hypre_double *) BLU_data, BLU_i, BLU_j, matBL_info, (hypre_double *) ftemp_data, (hypre_double *) utemp_data, ilu_solve_policy, ilu_solve_buffer)); } else if (isSinglePrecision) { /* L solve */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, nLU, BLU_nnz, (float *) &one, matL_des, (float *) BLU_data, BLU_i, BLU_j, matBL_info, (float *) ftemp_data, (float *) utemp_data, ilu_solve_policy, ilu_solve_buffer)); } /* -U^{-1}L^{-1} */ if (isDoublePrecision) { /* U solve */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, nLU, BLU_nnz, (hypre_double *) &one, matU_des, (hypre_double *) BLU_data, BLU_i, BLU_j, matBU_info, (hypre_double *) utemp_data, (hypre_double *) ftemp_data, ilu_solve_policy, ilu_solve_buffer)); } else if (isSinglePrecision) { /* U solve */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, nLU, BLU_nnz, (float *) &one, matU_des, (float *) BLU_data, BLU_i, BLU_j, matBU_info, (float *) utemp_data, (float *) ftemp_data, ilu_solve_policy, ilu_solve_buffer)); } } /* -EU^{-1}L^{-1} */ hypre_CSRMatrixMatvec(mone, matE_d, ftemp_upper, one, rhs_local); /* now solve S */ if (S) { /* if we have a schur complement */ hypre_ParVectorSetConstantValues(x, 0.0); HYPRE_GMRESSolve(schur_solver, (HYPRE_Matrix)schur_precond, (HYPRE_Vector)rhs, (HYPRE_Vector)x); /* u = xtemp + P*x */ /* -Fx */ hypre_CSRMatrixMatvec(mone, matF_d, x_local, zero, ftemp_upper); /* -L^{-1}Fx */ if (nLU > 0) { if (isDoublePrecision) { /* L solve */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, nLU, BLU_nnz, (hypre_double *) &one, matL_des, (hypre_double *) BLU_data, BLU_i, BLU_j, matBL_info, (hypre_double *) ftemp_data, (hypre_double *) utemp_data, ilu_solve_policy, ilu_solve_buffer)); } else if (isSinglePrecision) { /* L solve */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, nLU, BLU_nnz, (float *) &one, matL_des, (float *) BLU_data, BLU_i, BLU_j, matBL_info, (float *) ftemp_data, (float *) utemp_data, ilu_solve_policy, ilu_solve_buffer)); } /* -U{-1}L^{-1}Fx */ if (isDoublePrecision) { /* U solve */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, nLU, BLU_nnz, (hypre_double *) &one, matU_des, (hypre_double *) BLU_data, BLU_i, BLU_j, matBU_info, (hypre_double *) utemp_data, (hypre_double *) ftemp_data, ilu_solve_policy, ilu_solve_buffer)); } else if (isSinglePrecision) { /* U solve */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, nLU, BLU_nnz, (float *) &one, matU_des, (float *) BLU_data, BLU_i, BLU_j, matBU_info, (float *) utemp_data, (float *) ftemp_data, ilu_solve_policy, ilu_solve_buffer)); } } /* now copy data to y_lower */ hypre_TMemcpy( ftemp_data + nLU, x_data, HYPRE_Real, m, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE); /* correction to the residual */ hypre_ParVectorAxpy(one, ftemp, xtemp); } else { /* otherwise just apply triangular solves */ if (m > 0) { if (isDoublePrecision) { /* L solve - Forward solve */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, m, SLU_nnz, (hypre_double *) &one, matL_des, (hypre_double *) SLU_data, SLU_i, SLU_j, matSL_info, (hypre_double *) rhs_data, (hypre_double *) x_data, ilu_solve_policy, ilu_solve_buffer)); } else if (isSinglePrecision) { /* L solve - Forward solve */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, m, SLU_nnz, (float *) &one, matL_des, (float *) SLU_data, SLU_i, SLU_j, matSL_info, (float *) rhs_data, (float *) x_data, ilu_solve_policy, ilu_solve_buffer)); } if (isDoublePrecision) { /* U solve - Forward solve */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, m, SLU_nnz, (hypre_double *) &one, matU_des, (hypre_double *) SLU_data, SLU_i, SLU_j, matSU_info, (hypre_double *) x_data, (hypre_double *) rhs_data, ilu_solve_policy, ilu_solve_buffer)); } else if (isSinglePrecision) { /* U solve - Forward solve */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, m, SLU_nnz, (float *) &one, matU_des, (float *) SLU_data, SLU_i, SLU_j, matSU_info, (float *) x_data, (float *) rhs_data, ilu_solve_policy, ilu_solve_buffer)); } } /* u = xtemp + P*x */ /* -Fx */ hypre_CSRMatrixMatvec(mone, matF_d, rhs_local, zero, ftemp_upper); /* -L^{-1}Fx */ if (nLU > 0) { if (isDoublePrecision) { /* L solve */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, nLU, BLU_nnz, (hypre_double *) &one, matL_des, (hypre_double *) BLU_data, BLU_i, BLU_j, matBL_info, (hypre_double *) ftemp_data, (hypre_double *) utemp_data, ilu_solve_policy, ilu_solve_buffer)); } else if (isSinglePrecision) { /* L solve */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, nLU, BLU_nnz, (float *) &one, matL_des, (float *) BLU_data, BLU_i, BLU_j, matBL_info, (float *) ftemp_data, (float *) utemp_data, ilu_solve_policy, ilu_solve_buffer)); } /* -U{-1}L^{-1}Fx */ if (isDoublePrecision) { /* U solve */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, nLU, BLU_nnz, (hypre_double *) &one, matU_des, (hypre_double *) BLU_data, BLU_i, BLU_j, matBU_info, (hypre_double *) utemp_data, (hypre_double *) ftemp_data, ilu_solve_policy, ilu_solve_buffer)); } else if (isSinglePrecision) { /* U solve */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, nLU, BLU_nnz, (float *) &one, matU_des, (float *) BLU_data, BLU_i, BLU_j, matBU_info, (float *) utemp_data, (float *) ftemp_data, ilu_solve_policy, ilu_solve_buffer)); } } /* now copy data to y_lower */ hypre_TMemcpy( ftemp_data + nLU, rhs_data, HYPRE_Real, m, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE); hypre_ParVectorAxpy(one, ftemp, xtemp); } /* perm back */ HYPRE_THRUST_CALL(scatter, xtemp_data, xtemp_data + n, perm, ftemp_data); /* done, now everything are in u_temp, update solution */ hypre_ParVectorAxpy(one, ftemp, u); } break; case 0: case 2: default: { /* EU^{-1} and L^{-1}F */ /* compute residual */ hypre_ParCSRMatrixMatvecOutOfPlace(mone, A, u, one, f, ftemp); /* apply permutation before we can start our solve * Au=f -> (PAQ)Q'u=Pf */ HYPRE_THRUST_CALL(gather, perm, perm + n, ftemp_data, utemp_data); /* A-smoothing * x = [UA\(LA\(P*f_u))] fill to xtemp */ if (n > 0) { if (isDoublePrecision) { /* L solve - Forward solve */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, n, ALU_nnz, (hypre_double *) &one, matL_des, (hypre_double *) ALU_data, ALU_i, ALU_j, matAL_info, (hypre_double *) utemp_data, (hypre_double *) ftemp_data, ilu_solve_policy, ilu_solve_buffer)); /* U solve - Forward solve */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, n, ALU_nnz, (hypre_double *) &one, matU_des, (hypre_double *) ALU_data, ALU_i, ALU_j, matAU_info, (hypre_double *) ftemp_data, (hypre_double *) xtemp_data, ilu_solve_policy, ilu_solve_buffer)); } else if (isSinglePrecision) { /* L solve - Forward solve */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, n, ALU_nnz, (float *) &one, matL_des, (float *) ALU_data, ALU_i, ALU_j, matAL_info, (float *) utemp_data, (float *) ftemp_data, ilu_solve_policy, ilu_solve_buffer)); /* U solve - Forward solve */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, n, ALU_nnz, (float *) &one, matU_des, (float *) ALU_data, ALU_i, ALU_j, matAU_info, (float *) ftemp_data, (float *) xtemp_data, ilu_solve_policy, ilu_solve_buffer)); } } /* residual, we should not touch xtemp for now * r = R*(f-PAQx) */ hypre_ParCSRMatrixMatvec(mone, Aperm, xtemp, one, utemp); /* with R is complex */ /* copy partial data in */ hypre_TMemcpy( rhs_data, utemp_data + nLU, HYPRE_Real, m, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE); /* solve L^{-1} */ if (nLU > 0) { if (isDoublePrecision) { /* L solve */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, nLU, BLU_nnz, (hypre_double *) &one, matL_des, (hypre_double *) BLU_data, BLU_i, BLU_j, matBL_info, (hypre_double *) utemp_data, (hypre_double *) ftemp_data, ilu_solve_policy, ilu_solve_buffer)); } else if (isSinglePrecision) { /* L solve */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, nLU, BLU_nnz, (float *) &one, matL_des, (float *) BLU_data, BLU_i, BLU_j, matBL_info, (float *) utemp_data, (float *) ftemp_data, ilu_solve_policy, ilu_solve_buffer)); } } /* -EU^{-1}L^{-1} */ hypre_CSRMatrixMatvec(mone, matE_d, ftemp_upper, one, rhs_local); /* now solve S */ if (S) { /* if we have a schur complement */ hypre_ParVectorSetConstantValues(x, 0.0); HYPRE_GMRESSolve(schur_solver, (HYPRE_Matrix)schur_precond, (HYPRE_Vector)rhs, (HYPRE_Vector)x); /* u = xtemp + P*x */ /* -L^{-1}Fx */ hypre_CSRMatrixMatvec(mone, matF_d, x_local, zero, ftemp_upper); /* -U{-1}L^{-1}Fx */ if (nLU > 0) { if (isDoublePrecision) { /* U solve */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, nLU, BLU_nnz, (hypre_double *) &one, matU_des, (hypre_double *) BLU_data, BLU_i, BLU_j, matBU_info, (hypre_double *) ftemp_data, (hypre_double *) utemp_data, ilu_solve_policy, ilu_solve_buffer)); } else if (isSinglePrecision) { /* U solve */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, nLU, BLU_nnz, (float *) &one, matU_des, (float *) BLU_data, BLU_i, BLU_j, matBU_info, (float *) ftemp_data, (float *) utemp_data, ilu_solve_policy, ilu_solve_buffer)); } } /* now copy data to y_lower */ hypre_TMemcpy( utemp_data + nLU, x_data, HYPRE_Real, m, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE); hypre_ParVectorAxpy(one, utemp, xtemp); } else { /* otherwise just apply triangular solves */ if (m > 0) { if (isDoublePrecision) { /* L solve - Forward solve */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, m, SLU_nnz, (hypre_double *) &one, matL_des, (hypre_double *) SLU_data, SLU_i, SLU_j, matSL_info, (hypre_double *) rhs_data, (hypre_double *) x_data, ilu_solve_policy, ilu_solve_buffer)); } else if (isSinglePrecision) { /* L solve - Forward solve */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, m, SLU_nnz, (float *) &one, matL_des, (float *) SLU_data, SLU_i, SLU_j, matSL_info, (float *) rhs_data, (float *) x_data, ilu_solve_policy, ilu_solve_buffer)); } if (isDoublePrecision) { /* U solve - Forward solve */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, m, SLU_nnz, (hypre_double *) &one, matU_des, (hypre_double *) SLU_data, SLU_i, SLU_j, matSU_info, (hypre_double *) x_data, (hypre_double *) rhs_data, ilu_solve_policy, ilu_solve_buffer)); } else if (isSinglePrecision) { /* U solve - Forward solve */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, m, SLU_nnz, (float *) &one, matU_des, (float *) SLU_data, SLU_i, SLU_j, matSU_info, (float *) x_data, (float *) rhs_data, ilu_solve_policy, ilu_solve_buffer)); } } /* u = xtemp + P*x */ /* -L^{-1}Fx */ hypre_CSRMatrixMatvec(mone, matF_d, rhs_local, zero, ftemp_upper); /* -U{-1}L^{-1}Fx */ if (nLU > 0) { if (isDoublePrecision) { /* U solve */ HYPRE_CUSPARSE_CALL(cusparseDcsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, nLU, BLU_nnz, (hypre_double *) &one, matU_des, (hypre_double *) BLU_data, BLU_i, BLU_j, matBU_info, (hypre_double *) ftemp_data, (hypre_double *) utemp_data, ilu_solve_policy, ilu_solve_buffer)); } else if (isSinglePrecision) { /* U solve */ HYPRE_CUSPARSE_CALL(cusparseScsrsv2_solve(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, nLU, BLU_nnz, (float *) &one, matU_des, (float *) BLU_data, BLU_i, BLU_j, matBU_info, (float *) ftemp_data, (float *) utemp_data, ilu_solve_policy, ilu_solve_buffer)); } } /* now copy data to y_lower */ hypre_TMemcpy( utemp_data + nLU, rhs_data, HYPRE_Real, m, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE); hypre_ParVectorAxpy(one, utemp, xtemp); } /* perm back */ HYPRE_THRUST_CALL(scatter, xtemp_data, xtemp_data + n, perm, ftemp_data); /* done, now everything are in u_temp, update solution */ hypre_ParVectorAxpy(one, ftemp, u); } break; } return hypre_error_flag; } #endif HYPRE_Int hypre_ILUSolveRAPGMRESHOST(hypre_ParCSRMatrix *A, hypre_ParVector *f, hypre_ParVector *u, HYPRE_Int *perm, HYPRE_Int nLU, hypre_ParCSRMatrix *L, HYPRE_Real *D, hypre_ParCSRMatrix *U, hypre_ParCSRMatrix *mL, HYPRE_Real *mD, hypre_ParCSRMatrix *mU, hypre_ParVector *ftemp, hypre_ParVector *utemp, hypre_ParVector *xtemp, hypre_ParVector *ytemp, HYPRE_Solver schur_solver, HYPRE_Solver schur_precond, hypre_ParVector *rhs, hypre_ParVector *x, HYPRE_Int *u_end) { //#pragma omp parallel // printf("threads %d\n",omp_get_num_threads()); /* data objects for communication */ // MPI_Comm comm = hypre_ParCSRMatrixComm(A); /* data objects for L and U */ hypre_CSRMatrix *L_diag = hypre_ParCSRMatrixDiag(L); HYPRE_Real *L_diag_data = hypre_CSRMatrixData(L_diag); HYPRE_Int *L_diag_i = hypre_CSRMatrixI(L_diag); HYPRE_Int *L_diag_j = hypre_CSRMatrixJ(L_diag); hypre_CSRMatrix *U_diag = hypre_ParCSRMatrixDiag(U); HYPRE_Real *U_diag_data = hypre_CSRMatrixData(U_diag); HYPRE_Int *U_diag_i = hypre_CSRMatrixI(U_diag); HYPRE_Int *U_diag_j = hypre_CSRMatrixJ(U_diag); hypre_CSRMatrix *mL_diag = hypre_ParCSRMatrixDiag(mL); HYPRE_Real *mL_diag_data = hypre_CSRMatrixData(mL_diag); HYPRE_Int *mL_diag_i = hypre_CSRMatrixI(mL_diag); HYPRE_Int *mL_diag_j = hypre_CSRMatrixJ(mL_diag); hypre_CSRMatrix *mU_diag = hypre_ParCSRMatrixDiag(mU); HYPRE_Real *mU_diag_data = hypre_CSRMatrixData(mU_diag); HYPRE_Int *mU_diag_i = hypre_CSRMatrixI(mU_diag); HYPRE_Int *mU_diag_j = hypre_CSRMatrixJ(mU_diag); hypre_Vector *utemp_local = hypre_ParVectorLocalVector(utemp); HYPRE_Real *utemp_data = hypre_VectorData(utemp_local); hypre_Vector *ftemp_local = hypre_ParVectorLocalVector(ftemp); HYPRE_Real *ftemp_data = hypre_VectorData(ftemp_local); hypre_Vector *xtemp_local = NULL; HYPRE_Real *xtemp_data = NULL; hypre_Vector *ytemp_local = NULL; HYPRE_Real *ytemp_data = NULL; if (xtemp) { /* xtemp might be null when we have no Schur complement */ xtemp_local = hypre_ParVectorLocalVector(xtemp); xtemp_data = hypre_VectorData(xtemp_local); ytemp_local = hypre_ParVectorLocalVector(ytemp); ytemp_data = hypre_VectorData(ytemp_local); } HYPRE_Real alpha; HYPRE_Real beta; HYPRE_Int i, j, k1, k2, col; /* problem size */ HYPRE_Int n = hypre_CSRMatrixNumRows(L_diag); HYPRE_Int m = n - nLU; /* other data objects for computation */ //hypre_Vector *f_local; //HYPRE_Real *f_data; hypre_Vector *rhs_local; HYPRE_Real *rhs_data; hypre_Vector *x_local; HYPRE_Real *x_data; /* begin */ beta = 1.0; alpha = -1.0; if (m > 0) { /* setup vectors for solve */ rhs_local = hypre_ParVectorLocalVector(rhs); rhs_data = hypre_VectorData(rhs_local); x_local = hypre_ParVectorLocalVector(x); x_data = hypre_VectorData(x_local); } /* only support RAP with partial factorized W and Z */ /* compute residual */ hypre_ParCSRMatrixMatvecOutOfPlace(alpha, A, u, beta, f, ftemp); /* A-smoothing f_temp = [UA \ LA \ (f_temp[perm])] */ /* permuted L solve */ for (i = 0 ; i < n ; i ++) { utemp_data[i] = ftemp_data[perm[i]]; k1 = L_diag_i[i] ; k2 = L_diag_i[i + 1]; for (j = k1 ; j < k2 ; j ++) { col = L_diag_j[j]; utemp_data[i] -= L_diag_data[j] * utemp_data[col]; } } if (!xtemp) { /* in this case, we don't have a Schur complement */ /* U solve */ for (i = n - 1 ; i >= 0 ; i --) { ftemp_data[perm[i]] = utemp_data[i]; k1 = U_diag_i[i] ; k2 = U_diag_i[i + 1]; for (j = k1 ; j < k2 ; j ++) { col = U_diag_j[j]; ftemp_data[perm[i]] -= U_diag_data[j] * ftemp_data[perm[col]]; } ftemp_data[perm[i]] *= D[i]; } hypre_ParVectorAxpy(beta, ftemp, u); return hypre_error_flag; } /* U solve */ for (i = n - 1 ; i >= 0 ; i --) { xtemp_data[perm[i]] = utemp_data[i]; k1 = U_diag_i[i] ; k2 = U_diag_i[i + 1]; for (j = k1 ; j < k2 ; j ++) { col = U_diag_j[j]; xtemp_data[perm[i]] -= U_diag_data[j] * xtemp_data[perm[col]]; } xtemp_data[perm[i]] *= D[i]; } /* coarse-grid correction */ /* now f_temp is the result of A-smoothing * rhs = R*(b - Ax) * */ // utemp = (ftemp - A*xtemp) hypre_ParCSRMatrixMatvecOutOfPlace(alpha, A, xtemp, beta, ftemp, utemp); // R = [-L21 L\inv, I] if ( m > 0) { /* first is L solve */ for (i = 0 ; i < nLU ; i ++) { ytemp_data[i] = utemp_data[perm[i]]; k1 = mL_diag_i[i] ; k2 = mL_diag_i[i + 1]; for (j = k1 ; j < k2 ; j ++) { col = mL_diag_j[j]; ytemp_data[i] -= mL_diag_data[j] * ytemp_data[col]; } } /* apply -W * ytemp on this, and take care of the I part */ for (i = nLU ; i < n ; i ++) { rhs_data[i - nLU] = utemp_data[perm[i]]; k1 = mL_diag_i[i] ; k2 = u_end[i]; for (j = k1 ; j < k2 ; j ++) { col = mL_diag_j[j]; rhs_data[i - nLU] -= mL_diag_data[j] * ytemp_data[col]; } } } /* now the rhs is ready */ hypre_SeqVectorSetConstantValues(x_local, 0.0); HYPRE_GMRESSolve(schur_solver, (HYPRE_Matrix)schur_precond, (HYPRE_Vector)rhs, (HYPRE_Vector)x); if (m > 0) { /* for(i = 0 ; i < m ; i ++) { x_data[i] = rhs_data[i]; k1 = u_end[i+nLU] ; k2 = mL_diag_i[i+nLU+1]; for(j = k1 ; j < k2 ; j ++) { col = mL_diag_j[j]; x_data[i] -= mL_diag_data[j] * x_data[col-nLU]; } } for(i = m-1 ; i >= 0 ; i --) { rhs_data[i] = x_data[i]; k1 = mU_diag_i[i+nLU] ; k2 = mU_diag_i[i+1+nLU]; for(j = k1 ; j < k2 ; j ++) { col = mU_diag_j[j]; rhs_data[i] -= mU_diag_data[j] * rhs_data[col-nLU]; } rhs_data[i] *= mD[i]; } */ /* after solve, update x = x + Pv * that is, xtemp = xtemp + P*x */ /* first compute P*x * P = [ -U\inv U_12 ] * [ I ] */ /* matvec */ for (i = 0 ; i < nLU ; i ++) { ytemp_data[i] = 0.0; k1 = u_end[i] ; k2 = mU_diag_i[i + 1]; for (j = k1 ; j < k2 ; j ++) { col = mU_diag_j[j]; ytemp_data[i] -= mU_diag_data[j] * x_data[col - nLU]; } } /* U solve */ for (i = nLU - 1 ; i >= 0 ; i --) { ftemp_data[perm[i]] = ytemp_data[i]; k1 = mU_diag_i[i] ; k2 = u_end[i]; for (j = k1 ; j < k2 ; j ++) { col = mU_diag_j[j]; ftemp_data[perm[i]] -= mU_diag_data[j] * ftemp_data[perm[col]]; } ftemp_data[perm[i]] *= mD[i]; } /* update with I */ for (i = nLU ; i < n ; i ++) { ftemp_data[perm[i]] = x_data[i - nLU]; } hypre_ParVectorAxpy(beta, ftemp, u); } hypre_ParVectorAxpy(beta, xtemp, u); return hypre_error_flag; } /* solve functions for NSH */ /*-------------------------------------------------------------------- * hypre_NSHSolve *--------------------------------------------------------------------*/ HYPRE_Int hypre_NSHSolve( void *nsh_vdata, hypre_ParCSRMatrix *A, hypre_ParVector *f, hypre_ParVector *u ) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); // HYPRE_Int i; hypre_ParNSHData *nsh_data = (hypre_ParNSHData*) nsh_vdata; /* get matrices */ hypre_ParCSRMatrix *matA = hypre_ParNSHDataMatA(nsh_data); hypre_ParCSRMatrix *matM = hypre_ParNSHDataMatM(nsh_data); HYPRE_Int iter, num_procs, my_id; hypre_ParVector *F_array = hypre_ParNSHDataF(nsh_data); hypre_ParVector *U_array = hypre_ParNSHDataU(nsh_data); /* get settings */ HYPRE_Real tol = hypre_ParNSHDataTol(nsh_data); HYPRE_Int logging = hypre_ParNSHDataLogging(nsh_data); HYPRE_Int print_level = hypre_ParNSHDataPrintLevel(nsh_data); HYPRE_Int max_iter = hypre_ParNSHDataMaxIter(nsh_data); HYPRE_Real *norms = hypre_ParNSHDataRelResNorms(nsh_data); hypre_ParVector *Ftemp = hypre_ParNSHDataFTemp(nsh_data); hypre_ParVector *Utemp = hypre_ParNSHDataUTemp(nsh_data); hypre_ParVector *residual; HYPRE_Real alpha = -1.0; HYPRE_Real beta = 1.0; HYPRE_Real conv_factor = 0.0; HYPRE_Real resnorm = 1.0; HYPRE_Real init_resnorm = 0.0; HYPRE_Real rel_resnorm; HYPRE_Real rhs_norm = 0.0; HYPRE_Real old_resnorm; HYPRE_Real ieee_check = 0.; HYPRE_Real operat_cmplxty = hypre_ParNSHDataOperatorComplexity(nsh_data); HYPRE_Int Solve_err_flag; /* problem size */ // HYPRE_Int n = hypre_CSRMatrixNumRows(hypre_ParCSRMatrixDiag(A)); /* begin */ if (logging > 1) { residual = hypre_ParNSHDataResidual(nsh_data); } hypre_ParNSHDataNumIterations(nsh_data) = 0; hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); /*----------------------------------------------------------------------- * Write the solver parameters *-----------------------------------------------------------------------*/ if (my_id == 0 && print_level > 1) { hypre_NSHWriteSolverParams(nsh_data); } /*----------------------------------------------------------------------- * Initialize the solver error flag *-----------------------------------------------------------------------*/ Solve_err_flag = 0; /*----------------------------------------------------------------------- * write some initial info *-----------------------------------------------------------------------*/ if (my_id == 0 && print_level > 1 && tol > 0.) { hypre_printf("\n\n Newton–Schulz–Hotelling SOLVER SOLUTION INFO:\n"); } /*----------------------------------------------------------------------- * Compute initial residual and print *-----------------------------------------------------------------------*/ if (print_level > 1 || logging > 1 || tol > 0.) { if ( logging > 1 ) { hypre_ParVectorCopy(f, residual ); if (tol > 0.0) { hypre_ParCSRMatrixMatvec(alpha, A, u, beta, residual ); } resnorm = sqrt(hypre_ParVectorInnerProd( residual, residual )); } else { hypre_ParVectorCopy(f, Ftemp); if (tol > 0.0) { hypre_ParCSRMatrixMatvec(alpha, A, u, beta, Ftemp); } resnorm = sqrt(hypre_ParVectorInnerProd(Ftemp, Ftemp)); } /* Since it is does not diminish performance, attempt to return an error flag and notify users when they supply bad input. */ if (resnorm != 0.) { ieee_check = resnorm / resnorm; /* INF -> NaN conversion */ } if (ieee_check != ieee_check) { /* ...INFs or NaNs in input can make ieee_check a NaN. This test for ieee_check self-equality works on all IEEE-compliant compilers/ machines, c.f. page 8 of "Lecture Notes on the Status of IEEE 754" by W. Kahan, May 31, 1996. Currently (July 2002) this paper may be found at http://HTTP.CS.Berkeley.EDU/~wkahan/ieee754status/IEEE754.PDF */ if (print_level > 0) { hypre_printf("\n\nERROR detected by Hypre ... BEGIN\n"); hypre_printf("ERROR -- hypre_NSHSolve: INFs and/or NaNs detected in input.\n"); hypre_printf("User probably placed non-numerics in supplied A, x_0, or b.\n"); hypre_printf("ERROR detected by Hypre ... END\n\n\n"); } hypre_error(HYPRE_ERROR_GENERIC); return hypre_error_flag; } init_resnorm = resnorm; rhs_norm = sqrt(hypre_ParVectorInnerProd(f, f)); if (rhs_norm > HYPRE_REAL_EPSILON) { rel_resnorm = init_resnorm / rhs_norm; } else { /* rhs is zero, return a zero solution */ hypre_ParVectorSetConstantValues(U_array, 0.0); if (logging > 0) { rel_resnorm = 0.0; hypre_ParNSHDataFinalRelResidualNorm(nsh_data) = rel_resnorm; } return hypre_error_flag; } } else { rel_resnorm = 1.; } if (my_id == 0 && print_level > 1) { hypre_printf(" relative\n"); hypre_printf(" residual factor residual\n"); hypre_printf(" -------- ------ --------\n"); hypre_printf(" Initial %e %e\n", init_resnorm, rel_resnorm); } matA = A; U_array = u; F_array = f; /************** Main Solver Loop - always do 1 iteration ************/ iter = 0; while ((rel_resnorm >= tol || iter < 1) && iter < max_iter) { /* Do one solve on e = Mr */ hypre_NSHSolveInverse(matA, f, u, matM, Utemp, Ftemp); /*--------------------------------------------------------------- * Compute residual and residual norm *----------------------------------------------------------------*/ if (print_level > 1 || logging > 1 || tol > 0.) { old_resnorm = resnorm; if ( logging > 1 ) { hypre_ParVectorCopy(F_array, residual); hypre_ParCSRMatrixMatvec(alpha, matA, U_array, beta, residual ); resnorm = sqrt(hypre_ParVectorInnerProd( residual, residual )); } else { hypre_ParVectorCopy(F_array, Ftemp); hypre_ParCSRMatrixMatvec(alpha, matA, U_array, beta, Ftemp); resnorm = sqrt(hypre_ParVectorInnerProd(Ftemp, Ftemp)); } if (old_resnorm) { conv_factor = resnorm / old_resnorm; } else { conv_factor = resnorm; } if (rhs_norm > HYPRE_REAL_EPSILON) { rel_resnorm = resnorm / rhs_norm; } else { rel_resnorm = resnorm; } norms[iter] = rel_resnorm; } ++iter; hypre_ParNSHDataNumIterations(nsh_data) = iter; hypre_ParNSHDataFinalRelResidualNorm(nsh_data) = rel_resnorm; if (my_id == 0 && print_level > 1) { hypre_printf(" NSHSolve %2d %e %f %e \n", iter, resnorm, conv_factor, rel_resnorm); } } /* check convergence within max_iter */ if (iter == max_iter && tol > 0.) { Solve_err_flag = 1; hypre_error(HYPRE_ERROR_CONV); } /*----------------------------------------------------------------------- * Print closing statistics * Add operator and grid complexity stats *-----------------------------------------------------------------------*/ if (iter > 0 && init_resnorm) { conv_factor = pow((resnorm / init_resnorm), (1.0 / (HYPRE_Real) iter)); } else { conv_factor = 1.; } if (print_level > 1) { /*** compute operator and grid complexity (fill factor) here ?? ***/ if (my_id == 0) { if (Solve_err_flag == 1) { hypre_printf("\n\n=============================================="); hypre_printf("\n NOTE: Convergence tolerance was not achieved\n"); hypre_printf(" within the allowed %d iterations\n", max_iter); hypre_printf("=============================================="); } hypre_printf("\n\n Average Convergence Factor = %f \n", conv_factor); hypre_printf(" operator = %f\n", operat_cmplxty); } } return hypre_error_flag; } /* NSH solve * Simply a matvec on residual with approximate inverse * A: original matrix * f: rhs * u: solution * M: approximate inverse * ftemp, utemp: working vectors */ HYPRE_Int hypre_NSHSolveInverse(hypre_ParCSRMatrix *A, hypre_ParVector *f, hypre_ParVector *u, hypre_ParCSRMatrix *M, hypre_ParVector *ftemp, hypre_ParVector *utemp) { HYPRE_Real alpha; HYPRE_Real beta; /* begin */ alpha = -1.0; beta = 1.0; /* r = f-Au */ hypre_ParCSRMatrixMatvecOutOfPlace(alpha, A, u, beta, f, ftemp); /* e = Mr */ hypre_ParCSRMatrixMatvec(1.0, M, ftemp, 0.0, utemp); /* u = u + e */ hypre_ParVectorAxpy(beta, utemp, u); return hypre_error_flag; }
reduction-clause.c
#include <stdio.h> #include <stdlib.h> #ifdef _OPENMP #include <omp.h> #else #define omp_get_thread_num() 0 #endif main(int argc, char **argv) { int i, n=20, a[n],suma=0; if(argc < 2) { fprintf(stderr,"Falta iteraciones\n"); exit(-1); } n = atoi(argv[1]); if (n>20) { n=20; printf("n=%d",n); } for (i=0; i<n; i++) a[i] = i; #pragma omp parallel for reduction(+:suma) for (i=0; i<n; i++) suma += a[i]; printf("Tras 'parallel' suma=%d\n",suma); }
testing_dtrsm.c
/** * * @file testing_dtrsm.c * * PLASMA testing routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Mathieu Faverge * @date 2010-11-15 * @generated d Tue Jan 7 11:45:18 2014 * **/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <plasma.h> #include <cblas.h> #include <lapacke.h> #include <core_blas.h> #include "testing_dmain.h" #undef COMPLEX #define REAL static int check_solution(PLASMA_enum side, PLASMA_enum uplo, PLASMA_enum trans, PLASMA_enum diag, int M, int N, double alpha, double *A, int LDA, double *Bref, double *Bplasma, int LDB); int testing_dtrsm(int argc, char **argv) { /* Check for number of arguments*/ if ( argc != 5 ) { USAGE("TRSM", "alpha M N LDA LDB", " - alpha : alpha coefficient\n" " - M : number of rows of matrices B\n" " - N : number of columns of matrices B\n" " - LDA : leading dimension of matrix A\n" " - LDB : leading dimension of matrix B\n"); return -1; } double alpha = (double) atol(argv[0]); int M = atoi(argv[1]); int N = atoi(argv[2]); int LDA = atoi(argv[3]); int LDB = atoi(argv[4]); double eps; int info_solution; int s, u, t, d, i; int LDAxM = LDA*max(M,N); int LDBxN = LDB*max(M,N); double *A = (double *)malloc(LDAxM*sizeof(double)); #pragma omp register([LDAxM]A) double *B = (double *)malloc(LDBxN*sizeof(double)); #pragma omp register([LDBxN]B) double *Binit = (double *)malloc(LDBxN*sizeof(double)); #pragma omp register([LDBxN]Binit) double *Bfinal = (double *)malloc(LDBxN*sizeof(double)); #pragma omp register([LDBxN]Bfinal) /* Check if unable to allocate memory */ if ( (!A) || (!B) || (!Binit) || (!Bfinal)){ printf("Out of Memory \n "); return -2; } eps = LAPACKE_dlamch_work('e'); printf("\n"); printf("------ TESTS FOR PLASMA DTRSM ROUTINE ------- \n"); printf(" Size of the Matrix B : %d by %d\n", M, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n",eps); printf(" Computational tests pass if scaled residuals are less than 10.\n"); /*---------------------------------------------------------- * TESTING DTRSM */ /* Initialize A, B, C */ LAPACKE_dlarnv_work(IONE, ISEED, LDAxM, A); LAPACKE_dlarnv_work(IONE, ISEED, LDBxN, B); for(i=0;i<max(M,N);i++) A[LDA*i+i] = A[LDA*i+i] + 2.0; for (s=0; s<2; s++) { for (u=0; u<2; u++) { #ifdef COMPLEX for (t=0; t<3; t++) { #else for (t=0; t<2; t++) { #endif for (d=0; d<2; d++) { memcpy(Binit, B, LDBxN*sizeof(double)); memcpy(Bfinal, B, LDBxN*sizeof(double)); /* PLASMA DTRSM */ PLASMA_dtrsm(side[s], uplo[u], trans[t], diag[d], M, N, alpha, A, LDA, Bfinal, LDB); /* Check the solution */ info_solution = check_solution(side[s], uplo[u], trans[t], diag[d], M, N, alpha, A, LDA, Binit, Bfinal, LDB); printf("***************************************************\n"); if (info_solution == 0) { printf(" ---- TESTING DTRSM (%s, %s, %s, %s) ...... PASSED !\n", sidestr[s], uplostr[u], transstr[t], diagstr[d]); } else { printf(" ---- TESTING DTRSM (%s, %s, %s, %s) ... FAILED !\n", sidestr[s], uplostr[u], transstr[t], diagstr[d]); } printf("***************************************************\n"); } } } } free(A); free(B); free(Binit); free(Bfinal); return 0; } /*-------------------------------------------------------------- * Check the solution */ static int check_solution(PLASMA_enum side, PLASMA_enum uplo, PLASMA_enum trans, PLASMA_enum diag, int M, int N, double alpha, double *A, int LDA, double *Bref, double *Bplasma, int LDB) { int info_solution; double Anorm, Binitnorm, Bplasmanorm, Blapacknorm, Rnorm, result; double eps; double mzone = (double)-1.0; double *work = (double *)malloc(max(M, N)* sizeof(double)); int Am, An; if (side == PlasmaLeft) { Am = M; An = M; } else { Am = N; An = N; } Anorm = LAPACKE_dlantr_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), lapack_const(uplo), lapack_const(diag), Am, An, A, LDA, work); Binitnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Bref, LDB, work); Bplasmanorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Bplasma, LDB, work); cblas_dtrsm(CblasColMajor, (CBLAS_SIDE)side, (CBLAS_UPLO)uplo, (CBLAS_TRANSPOSE)trans, (CBLAS_DIAG)diag, M, N, (alpha), A, LDA, Bref, LDB); Blapacknorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Bref, LDB, work); cblas_daxpy(LDB * N, (mzone), Bplasma, 1, Bref, 1); Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Bref, LDB, work); eps = LAPACKE_dlamch_work('e'); printf("Rnorm %e, Anorm %e, Binitnorm %e, Bplasmanorm %e, Blapacknorm %e\n", Rnorm, Anorm, Binitnorm, Bplasmanorm, Blapacknorm); result = Rnorm / ((Anorm + Blapacknorm) * max(M,N) * eps); printf("============\n"); printf("Checking the norm of the difference against reference DTRSM \n"); printf("-- ||Cplasma - Clapack||_oo/((||A||_oo+||B||_oo).N.eps) = %e \n", result); if ( isinf(Blapacknorm) || isinf(Bplasmanorm) || isnan(result) || isinf(result) || (result > 10.0) ) { printf("-- The solution is suspicious ! \n"); info_solution = 1; } else { printf("-- The solution is CORRECT ! \n"); info_solution= 0 ; } free(work); return info_solution; }
a.35.4.c
/* { dg-do compile } */ void work (int, int); void wrong4 (int n) { #pragma omp parallel default(shared) { int i; #pragma omp for for (i = 0; i < n; i++) { work (i, 0); /* incorrect nesting of barrier region in a loop region */ #pragma omp barrier /* { dg-error "may not be closely nested" } */ work (i, 1); } } }
GB_unop__exp_fc32_fc32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__exp_fc32_fc32 // op(A') function: GB_unop_tran__exp_fc32_fc32 // C type: GxB_FC32_t // A type: GxB_FC32_t // cast: GxB_FC32_t cij = aij // unaryop: cij = cexpf (aij) #define GB_ATYPE \ GxB_FC32_t #define GB_CTYPE \ GxB_FC32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = cexpf (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC32_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC32_t z = aij ; \ Cx [pC] = cexpf (z) ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_EXP || GxB_NO_FC32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__exp_fc32_fc32 ( GxB_FC32_t *Cx, // Cx and Ax may be aliased const GxB_FC32_t *Ax, const int8_t *GB_RESTRICT Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC32_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC32_t aij = Ax [p] ; GxB_FC32_t z = aij ; Cx [p] = cexpf (z) ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC32_t aij = Ax [p] ; GxB_FC32_t z = aij ; Cx [p] = cexpf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__exp_fc32_fc32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
AVX2search.c
#include "charSubmat.h" #include "AVX2search.h" #include "utils.h" // search using AVX2 instructions and Score Profile technique void search_avx2_sp (char * query_sequences, unsigned short int * query_sequences_lengths, unsigned long int query_sequences_count, unsigned int * query_disp, char * vect_sequences_db, unsigned short int * vect_sequences_db_lengths, unsigned short int * vect_sequences_db_blocks, unsigned long int vect_sequences_db_count, unsigned long int * vect_sequences_db_disp, char * submat, int open_gap, int extend_gap, int n_threads, int block_size, int * scores, double * workTime){ long int i, j, k; double tick; char *a, * b; unsigned int * a_disp; unsigned long int * b_disp = NULL; unsigned short int * m, *n, *nbbs, sequences_db_max_length, query_sequences_max_length; a = query_sequences; m = query_sequences_lengths; a_disp = query_disp; query_sequences_max_length = query_sequences_lengths[query_sequences_count-1]; sequences_db_max_length = vect_sequences_db_lengths[vect_sequences_db_count-1]; b = vect_sequences_db; n = vect_sequences_db_lengths; nbbs = vect_sequences_db_blocks; b_disp = vect_sequences_db_disp; tick = dwalltime(); #pragma omp parallel default(none) shared(block_size, a, b, n, nbbs, m, a_disp, b_disp, submat, scores, query_sequences_count, vect_sequences_db_count, open_gap, extend_gap, sequences_db_max_length, query_sequences_max_length) num_threads(n_threads) { __m256i *row1, *row2, *tmp_row, *maxCol, *maxRow, *lastCol, * ptr_scores; __m256i *ptr_scoreProfile1, *ptr_scoreProfile2, *ptr_scoreProfile3, *ptr_scoreProfile4; __m128i *tmp; char * ptr_a, * ptr_b, * scoreProfile; __declspec(align(MEMALIGN)) __m256i score, auxLastCol, b_values, blosum_lo, blosum_hi; __declspec(align(MEMALIGN)) __m256i current1, current2, current3, current4, previous2, previous3, previous4; __declspec(align(MEMALIGN)) __m256i aux0, aux1, aux2, aux3, aux4, aux5, aux6, aux7, aux8; __declspec(align(MEMALIGN)) __m256i vextend_gap_epi8 = _mm256_set1_epi8(extend_gap), vopen_extend_gap_epi8 = _mm256_set1_epi8(open_gap+extend_gap); __declspec(align(MEMALIGN)) __m256i vextend_gap_epi16 = _mm256_set1_epi16(extend_gap), vopen_extend_gap_epi16 = _mm256_set1_epi16(open_gap+extend_gap); __declspec(align(MEMALIGN)) __m256i vextend_gap_epi32 = _mm256_set1_epi32(extend_gap), vopen_extend_gap_epi32 = _mm256_set1_epi32(open_gap+extend_gap); __declspec(align(MEMALIGN)) __m256i vzero_epi8 = _mm256_set1_epi8(0), vzero_epi16 = _mm256_set1_epi16(0), vzero_epi32 = _mm256_set1_epi32(0); // SP __declspec(align(MEMALIGN)) __m256i v15 = _mm256_set1_epi8(15), vneg32 = _mm256_set1_epi8(-32), v16 = _mm256_set1_epi8(16); // overflow detection __declspec(align(MEMALIGN)) __m256i v127 = _mm256_set1_epi8(127), v32767 = _mm256_set1_epi16(32767); // bias __declspec(align(MEMALIGN)) __m256i v128 = _mm256_set1_epi32(128), v32768 = _mm256_set1_epi32(32768); // aux __declspec(align(MEMALIGN)) __m128i aux, auxBlosum[2]; unsigned int i, j, ii, jj, k, disp_1, disp_2, disp_3, disp_4, dim1, dim2, nbb; unsigned long int t, s, q; int overflow_flag, bb1, bb2, bb1_start, bb1_end, bb2_start, bb2_end; // allocate memory for auxiliary buffers row1 = (__m256i *) _mm_malloc((block_size+1)*sizeof(__m256i), MEMALIGN); row2 = (__m256i *) _mm_malloc((block_size+1)*sizeof(__m256i), MEMALIGN); maxCol = (__m256i *) _mm_malloc((block_size+1)*sizeof(__m256i), MEMALIGN); maxRow = (__m256i *) _mm_malloc((query_sequences_max_length)*sizeof(__m256i), MEMALIGN); lastCol = (__m256i *) _mm_malloc((query_sequences_max_length)*sizeof(__m256i), MEMALIGN); scoreProfile = (char *) _mm_malloc((SUBMAT_ROWS_x_AVX2_INT8_VECTOR_LENGTH*block_size)*sizeof(char), MEMALIGN); // calculate alignment score #pragma omp for schedule(dynamic) nowait for (t=0; t< query_sequences_count*vect_sequences_db_count; t++) { q = (query_sequences_count-1) - (t % query_sequences_count); s = (vect_sequences_db_count-1) - (t / query_sequences_count); ptr_a = a + a_disp[q]; ptr_b = b + b_disp[s]; ptr_scores = (__m256i *) (scores + (q*vect_sequences_db_count+s)*AVX2_INT8_VECTOR_LENGTH); // calculate number of blocks nbb = nbbs[s]; // init buffers #pragma unroll(AVX2_UNROLL_COUNT) for (i=0; i<m[q] ; i++ ) maxRow[i] = _mm256_set1_epi8(-128); #pragma unroll(AVX2_UNROLL_COUNT) for (i=0; i<m[q] ; i++ ) lastCol[i] = _mm256_set1_epi8(-128); // set score to 0 score = _mm256_set1_epi8(-128); for (k=0; k < nbb; k++){ // calculate dim1 disp_4 = k*block_size; dim1 = n[s]-disp_4; dim1 = (block_size < dim1 ? block_size : dim1); // calculate dim2 dim2 = dim1 / DB_SEQ_LEN_MULT; // calculate SP sub-block length disp_1 = dim1*AVX2_INT8_VECTOR_LENGTH; // init buffers #pragma unroll(AVX2_UNROLL_COUNT) for (i=0; i<dim1+1 ; i++ ) maxCol[i] = _mm256_set1_epi8(-128); #pragma unroll(AVX2_UNROLL_COUNT) for (i=0; i<dim1+1 ; i++ ) row1[i] = _mm256_set1_epi8(-128); auxLastCol = _mm256_set1_epi8(-128); // build score profile for (i=0; i< dim1 ;i++ ) { // indexes b_values = _mm256_loadu_si256((__m256i *) (ptr_b + (disp_4+i)*AVX2_INT8_VECTOR_LENGTH)); // indexes >= 16 aux1 = _mm256_sub_epi8(b_values, v16); // indexes < 16 aux2 = _mm256_cmpgt_epi8(b_values,v15); aux3 = _mm256_and_si256(aux2,vneg32); aux4 = _mm256_add_epi8(b_values,aux3); ptr_scoreProfile1 = (__m256i *)(scoreProfile) + i; #pragma unroll for (j=0; j< SUBMAT_ROWS-1; j++) { tmp = (__m128i*) (submat + j*SUBMAT_COLS); auxBlosum[0] = _mm_load_si128(tmp); auxBlosum[1] = _mm_load_si128(tmp+1); blosum_lo = _mm256_loadu2_m128i(&auxBlosum[0], &auxBlosum[0]); blosum_hi = _mm256_loadu2_m128i(&auxBlosum[1], &auxBlosum[1]); aux5 = _mm256_shuffle_epi8(blosum_lo,aux4); aux6 = _mm256_shuffle_epi8(blosum_hi,aux1); _mm256_store_si256(ptr_scoreProfile1+j*dim1,_mm256_or_si256(aux5,aux6)); } _mm256_store_si256(ptr_scoreProfile1+(SUBMAT_ROWS-1)*dim1, vzero_epi8); } for( i = 0; i < m[q]; i+=QUERY_SEQ_LEN_MULT){ // update row[0] with lastCol[i-1] row1[0] = lastCol[i]; previous2 = lastCol[i+1]; previous3 = lastCol[i+2]; previous4 = lastCol[i+3]; // calculate score profile displacement ptr_scoreProfile1 = (__m256i*)(scoreProfile+((unsigned int)(ptr_a[i]))*disp_1); ptr_scoreProfile2 = (__m256i*)(scoreProfile+((unsigned int)(ptr_a[i+1]))*disp_1); ptr_scoreProfile3 = (__m256i*)(scoreProfile+((unsigned int)(ptr_a[i+2]))*disp_1); ptr_scoreProfile4 = (__m256i*)(scoreProfile+((unsigned int)(ptr_a[i+3]))*disp_1); // store maxRow in auxiliars aux1 = maxRow[i]; aux2 = maxRow[i+1]; aux3 = maxRow[i+2]; aux4 = maxRow[i+3]; for (ii=0; ii<dim2 ; ii++) { #pragma unroll(DB_SEQ_LEN_MULT) for( j=ii*DB_SEQ_LEN_MULT+1, jj=0; jj < DB_SEQ_LEN_MULT; jj++, j++) { //calcuate the diagonal value current1 = _mm256_adds_epi8(row1[j-1], _mm256_load_si256(ptr_scoreProfile1+(j-1))); // calculate current1 max value current1 = _mm256_max_epi8(current1, aux1); current1 = _mm256_max_epi8(current1, maxCol[j]); //current1 = _mm256_max_epi8(current1, vzero_epi8); // update maxRow and maxCol aux1 = _mm256_subs_epi8(aux1, vextend_gap_epi8); maxCol[j] = _mm256_subs_epi8(maxCol[j], vextend_gap_epi8); aux0 = _mm256_subs_epi8(current1, vopen_extend_gap_epi8); aux1 = _mm256_max_epi8(aux1, aux0); maxCol[j] = _mm256_max_epi8(maxCol[j], aux0); // update max score score = _mm256_max_epi8(score,current1); //calcuate the diagonal value current2 = _mm256_adds_epi8(previous2, _mm256_load_si256(ptr_scoreProfile2+(j-1))); // update previous previous2 = current1; // calculate current2 max value current2 = _mm256_max_epi8(current2, aux2); current2 = _mm256_max_epi8(current2, maxCol[j]); //current2 = _mm256_max_epi8(current2, vzero_epi8); // update maxRow and maxCol aux2 = _mm256_subs_epi8(aux2, vextend_gap_epi8); maxCol[j] = _mm256_subs_epi8(maxCol[j], vextend_gap_epi8); aux0 = _mm256_subs_epi8(current2, vopen_extend_gap_epi8); aux2 = _mm256_max_epi8(aux2, aux0); maxCol[j] = _mm256_max_epi8(maxCol[j], aux0); // update max score score = _mm256_max_epi8(score,current2); //calcuate the diagonal value current3 = _mm256_adds_epi8(previous3, _mm256_load_si256(ptr_scoreProfile3+(j-1))); // update previous previous3 = current2; // calculate current3 max value current3 = _mm256_max_epi8(current3, aux3); current3 = _mm256_max_epi8(current3, maxCol[j]); //current3 = _mm256_max_epi8(current3, vzero_epi8); // update maxRow and maxCol aux3 = _mm256_subs_epi8(aux3, vextend_gap_epi8); maxCol[j] = _mm256_subs_epi8(maxCol[j], vextend_gap_epi8); aux0 = _mm256_subs_epi8(current3, vopen_extend_gap_epi8); aux3 = _mm256_max_epi8(aux3, aux0); maxCol[j] = _mm256_max_epi8(maxCol[j], aux0); // update max score score = _mm256_max_epi8(score,current3); //calcuate the diagonal value current4 = _mm256_adds_epi8(previous4, _mm256_load_si256(ptr_scoreProfile4+(j-1))); // update previous previous4 = current3; // calculate current4 max value current4 = _mm256_max_epi8(current4, aux4); current4 = _mm256_max_epi8(current4, maxCol[j]); //current4 = _mm256_max_epi8(current4, vzero_epi8); // update maxRow and maxCol aux4 = _mm256_subs_epi8(aux4, vextend_gap_epi8); maxCol[j] = _mm256_subs_epi8(maxCol[j], vextend_gap_epi8); aux0 = _mm256_subs_epi8(current4, vopen_extend_gap_epi8); aux4 = _mm256_max_epi8(aux4, aux0); maxCol[j] = _mm256_max_epi8(maxCol[j], aux0); // update row buffer row2[j] = current4; // update max score score = _mm256_max_epi8(score,current4); } } // update maxRow maxRow[i] = aux1; maxRow[i+1] = aux2; maxRow[i+2] = aux3; maxRow[i+3] = aux4; // update lastCol lastCol[i] = auxLastCol; lastCol[i+1] = current1; lastCol[i+2] = current2; lastCol[i+3] = current3; auxLastCol = current4; // swap buffers tmp_row = row1; row1 = row2; row2 = tmp_row; } } // store max value aux = _mm256_extracti128_si256 (score,0); aux1 = _mm256_add_epi32(_mm256_cvtepi8_epi32(aux),v128); _mm256_store_si256 (ptr_scores,aux1); aux1 = _mm256_add_epi32(_mm256_cvtepi8_epi32(_mm_srli_si128(aux,8)),v128); _mm256_store_si256 (ptr_scores+1,aux1); aux = _mm256_extracti128_si256 (score,1); aux1 = _mm256_add_epi32(_mm256_cvtepi8_epi32(aux),v128); _mm256_store_si256 (ptr_scores+2,aux1); aux1 = _mm256_add_epi32(_mm256_cvtepi8_epi32(_mm_srli_si128(aux,8)),v128); _mm256_store_si256 (ptr_scores+3,aux1); // overflow detection aux1 = _mm256_cmpeq_epi8(score,v127); overflow_flag = _mm256_testz_si256(aux1,v127); // if overflow if (overflow_flag == 0){ // check overflow in low 16 bits aux1 = _mm256_cmpeq_epi8(_mm256_inserti128_si256(vzero_epi8,_mm256_extracti128_si256(score,0),0),v127); bb1_start = _mm256_testz_si256(aux1,v127); // check overflow in high 16 bits aux1 = _mm256_cmpeq_epi8(_mm256_inserti128_si256(vzero_epi8,_mm256_extracti128_si256(score,1),0),v127); bb1_end = 2 - _mm256_testz_si256(aux1,v127); // recalculate using 16-bit signed integer precision for (bb1=bb1_start; bb1<bb1_end ; bb1++){ // init buffers #pragma unroll(AVX2_UNROLL_COUNT) for (i=0; i<m[q] ; i++ ) maxRow[i] = _mm256_set1_epi16(-32768); #pragma unroll(AVX2_UNROLL_COUNT) for (i=0; i<m[q] ; i++ ) lastCol[i] = _mm256_set1_epi16(-32768); // set score to 0 score = _mm256_set1_epi16(-32768); disp_2 = bb1*AVX2_INT16_VECTOR_LENGTH; for (k=0; k < nbb; k++){ // calculate dim1 disp_4 = k*block_size; dim1 = n[s]-disp_4; dim1 = (block_size < dim1 ? block_size : dim1); // calculate dim2 dim2 = dim1 / DB_SEQ_LEN_MULT; // calculate SP sub-block length disp_1 = dim1*AVX2_INT8_VECTOR_LENGTH; // init buffers #pragma unroll(AVX2_UNROLL_COUNT) for (i=0; i<dim1+1 ; i++ ) maxCol[i] = _mm256_set1_epi16(-32768); #pragma unroll(AVX2_UNROLL_COUNT) for (i=0; i<dim1+1 ; i++ ) row1[i] = _mm256_set1_epi16(-32768); auxLastCol = _mm256_set1_epi16(-32768); // build score profile for (i=0; i< dim1 ;i++ ) { // indexes b_values = _mm256_loadu_si256((__m256i *) (ptr_b + (disp_4+i)*AVX2_INT8_VECTOR_LENGTH)); // indexes >= 16 aux1 = _mm256_sub_epi8(b_values, v16); // indexes < 16 aux2 = _mm256_cmpgt_epi8(b_values,v15); aux3 = _mm256_and_si256(aux2,vneg32); aux4 = _mm256_add_epi8(b_values,aux3); ptr_scoreProfile1 = (__m256i *)(scoreProfile) + i; #pragma unroll for (j=0; j< SUBMAT_ROWS-1; j++) { tmp = (__m128i*) (submat + j*SUBMAT_COLS); auxBlosum[0] = _mm_load_si128(tmp); auxBlosum[1] = _mm_load_si128(tmp+1); blosum_lo = _mm256_loadu2_m128i(&auxBlosum[0], &auxBlosum[0]); blosum_hi = _mm256_loadu2_m128i(&auxBlosum[1], &auxBlosum[1]); aux5 = _mm256_shuffle_epi8(blosum_lo,aux4); aux6 = _mm256_shuffle_epi8(blosum_hi,aux1); _mm256_store_si256(ptr_scoreProfile1+j*dim1,_mm256_or_si256(aux5,aux6)); } _mm256_store_si256(ptr_scoreProfile1+(SUBMAT_ROWS-1)*dim1, vzero_epi16); } for( i = 0; i < m[q]; i+=QUERY_SEQ_LEN_MULT){ // update row[0] with lastCol[i-1] row1[0] = lastCol[i]; previous2 = lastCol[i+1]; previous3 = lastCol[i+2]; previous4 = lastCol[i+3]; // calculate score profile displacement ptr_scoreProfile1 = (__m256i *)(scoreProfile+((int)(ptr_a[i]))*disp_1+disp_2); ptr_scoreProfile2 = (__m256i *)(scoreProfile+((int)(ptr_a[i+1]))*disp_1+disp_2); ptr_scoreProfile3 = (__m256i *)(scoreProfile+((int)(ptr_a[i+2]))*disp_1+disp_2); ptr_scoreProfile4 = (__m256i *)(scoreProfile+((int)(ptr_a[i+3]))*disp_1+disp_2); // store maxRow in auxiliars aux1 = maxRow[i]; aux2 = maxRow[i+1]; aux3 = maxRow[i+2]; aux4 = maxRow[i+3]; for (ii=0; ii<dim2 ; ii++) { #pragma unroll(DB_SEQ_LEN_MULT) for( j=ii*DB_SEQ_LEN_MULT+1, jj=0; jj < DB_SEQ_LEN_MULT; jj++, j++) { //calcuate the diagonal value current1 = _mm256_adds_epi16(row1[j-1], _mm256_cvtepi8_epi16(_mm_loadu_si128((__m128i *) (ptr_scoreProfile1+(j-1))))); // calculate current1 max value current1 = _mm256_max_epi16(current1, aux1); current1 = _mm256_max_epi16(current1, maxCol[j]); //current1 = _mm256_max_epi16(current1, vzero_epi16); // update maxRow and maxCol aux1 = _mm256_subs_epi16(aux1, vextend_gap_epi16); maxCol[j] = _mm256_subs_epi16(maxCol[j], vextend_gap_epi16); aux0 = _mm256_subs_epi16(current1, vopen_extend_gap_epi16); aux1 = _mm256_max_epi16(aux1, aux0); maxCol[j] = _mm256_max_epi16(maxCol[j], aux0); // update max score score = _mm256_max_epi16(score,current1); //calcuate the diagonal value current2 = _mm256_adds_epi16(previous2, _mm256_cvtepi8_epi16(_mm_loadu_si128((__m128i *) (ptr_scoreProfile2+(j-1))))); // update previous previous2 = current1; // calculate current2 max value current2 = _mm256_max_epi16(current2, aux2); current2 = _mm256_max_epi16(current2, maxCol[j]); //current2 = _mm256_max_epi16(current2, vzero_epi16); // update maxRow and maxCol aux2 = _mm256_subs_epi16(aux2, vextend_gap_epi16); maxCol[j] = _mm256_subs_epi16(maxCol[j], vextend_gap_epi16); aux0 = _mm256_subs_epi16(current2, vopen_extend_gap_epi16); aux2 = _mm256_max_epi16(aux2, aux0); maxCol[j] = _mm256_max_epi16(maxCol[j], aux0); // update max score score = _mm256_max_epi16(score,current2); //calcuate the diagonal value current3 = _mm256_adds_epi16(previous3, _mm256_cvtepi8_epi16(_mm_loadu_si128((__m128i *) (ptr_scoreProfile3+(j-1))))); // update previous previous3 = current2; // calculate current3 max value current3 = _mm256_max_epi16(current3, aux3); current3 = _mm256_max_epi16(current3, maxCol[j]); //current3 = _mm256_max_epi16(current3, vzero_epi16); // update maxRow and maxCol aux3 = _mm256_subs_epi16(aux3, vextend_gap_epi16); maxCol[j] = _mm256_subs_epi16(maxCol[j], vextend_gap_epi16); aux0 = _mm256_subs_epi16(current3, vopen_extend_gap_epi16); aux3 = _mm256_max_epi16(aux3, aux0); maxCol[j] = _mm256_max_epi16(maxCol[j], aux0); // update max score score = _mm256_max_epi16(score,current3); //calcuate the diagonal value current4 = _mm256_adds_epi16(previous4, _mm256_cvtepi8_epi16(_mm_loadu_si128((__m128i *) (ptr_scoreProfile4+(j-1))))); // update previous previous4 = current3; // calculate current4 max value current4 = _mm256_max_epi16(current4, aux4); current4 = _mm256_max_epi16(current4, maxCol[j]); //current4 = _mm256_max_epi16(current4, vzero_epi16); // update maxRow and maxCol aux4 = _mm256_subs_epi16(aux4, vextend_gap_epi16); maxCol[j] = _mm256_subs_epi16(maxCol[j], vextend_gap_epi16); aux0 = _mm256_subs_epi16(current4, vopen_extend_gap_epi16); aux4 = _mm256_max_epi16(aux4, aux0); maxCol[j] = _mm256_max_epi16(maxCol[j], aux0); // update row buffer row2[j] = current4; // update max score score = _mm256_max_epi16(score,current4); } } // update maxRow maxRow[i] = aux1; maxRow[i+1] = aux2; maxRow[i+2] = aux3; maxRow[i+3] = aux4; // update lastCol lastCol[i] = auxLastCol; lastCol[i+1] = current1; lastCol[i+2] = current2; lastCol[i+3] = current3; auxLastCol = current4; // swap buffers tmp_row = row1; row1 = row2; row2 = tmp_row; } } // store max value aux = _mm256_extracti128_si256 (score,0); aux1 = _mm256_add_epi32(_mm256_cvtepi16_epi32(aux),v32768); _mm256_store_si256 (ptr_scores+bb1*2,aux1); aux = _mm256_extracti128_si256 (score,1); aux1 = _mm256_add_epi32(_mm256_cvtepi16_epi32(aux),v32768); _mm256_store_si256 (ptr_scores+bb1*2+1,aux1); // overflow detection aux1 = _mm256_cmpeq_epi16(score,v32767); overflow_flag = _mm256_testz_si256(aux1,v32767); // if overflow if (overflow_flag == 0){ // check overflow in low 16 bits aux1 = _mm256_cmpeq_epi16(_mm256_inserti128_si256(vzero_epi16,_mm256_extracti128_si256(score,0),0),v32767); bb2_start = _mm256_testz_si256(aux1,v32767); // check overflow in high 16 bits aux1 = _mm256_cmpeq_epi16(_mm256_inserti128_si256(vzero_epi16,_mm256_extracti128_si256(score,1),0),v32767); bb2_end = 2 - _mm256_testz_si256(aux1,v32767); // recalculate using 32-bit signed integer precision for (bb2=bb2_start; bb2<bb2_end ; bb2++){ // init buffers #pragma unroll(AVX2_UNROLL_COUNT) for (i=0; i<m[q] ; i++ ) maxRow[i] = _mm256_set1_epi32(0); #pragma unroll(AVX2_UNROLL_COUNT) for (i=0; i<m[q] ; i++ ) lastCol[i] = _mm256_set1_epi32(0); // set score to 0 score = _mm256_set1_epi32(0); disp_3 = disp_2 + bb2*AVX2_INT32_VECTOR_LENGTH; for (k=0; k < nbb; k++){ // calculate dim1 disp_4 = k*block_size; dim1 = n[s]-disp_4; dim1 = (block_size < dim1 ? block_size : dim1); // calculate dim2 dim2 = dim1 / DB_SEQ_LEN_MULT; // calculate SP sub-block length disp_1 = dim1*AVX2_INT8_VECTOR_LENGTH; // init buffers #pragma unroll(AVX2_UNROLL_COUNT) for (i=0; i<dim1+1 ; i++ ) maxCol[i] = _mm256_set1_epi32(0); #pragma unroll(AVX2_UNROLL_COUNT) for (i=0; i<dim1+1 ; i++ ) row1[i] = _mm256_set1_epi32(0); auxLastCol = _mm256_set1_epi32(0); // build score profile for (i=0; i< dim1 ;i++ ) { // indexes b_values = _mm256_loadu_si256((__m256i *) (ptr_b + (disp_4+i)*AVX2_INT8_VECTOR_LENGTH)); // indexes >= 16 aux1 = _mm256_sub_epi8(b_values, v16); // indexes < 16 aux2 = _mm256_cmpgt_epi8(b_values,v15); aux3 = _mm256_and_si256(aux2,vneg32); aux4 = _mm256_add_epi8(b_values,aux3); ptr_scoreProfile1 = (__m256i *)(scoreProfile) + i; #pragma unroll for (j=0; j< SUBMAT_ROWS-1; j++) { tmp = (__m128i*) (submat + j*SUBMAT_COLS); auxBlosum[0] = _mm_load_si128(tmp); auxBlosum[1] = _mm_load_si128(tmp+1); blosum_lo = _mm256_loadu2_m128i(&auxBlosum[0], &auxBlosum[0]); blosum_hi = _mm256_loadu2_m128i(&auxBlosum[1], &auxBlosum[1]); aux5 = _mm256_shuffle_epi8(blosum_lo,aux4); aux6 = _mm256_shuffle_epi8(blosum_hi,aux1); _mm256_store_si256(ptr_scoreProfile1+j*dim1,_mm256_or_si256(aux5,aux6)); } _mm256_store_si256(ptr_scoreProfile1+(SUBMAT_ROWS-1)*dim1, vzero_epi8); } for( i = 0; i < m[q]; i+=QUERY_SEQ_LEN_MULT){ // update row[0] with lastCol[i-1] row1[0] = lastCol[i]; previous2 = lastCol[i+1]; previous3 = lastCol[i+2]; previous4 = lastCol[i+3]; // calculate score profile displacement ptr_scoreProfile1 = (__m256i *)(scoreProfile+((unsigned int)(ptr_a[i]))*disp_1+disp_3); ptr_scoreProfile2 = (__m256i *)(scoreProfile+((unsigned int)(ptr_a[i+1]))*disp_1+disp_3); ptr_scoreProfile3 = (__m256i *)(scoreProfile+((unsigned int)(ptr_a[i+2]))*disp_1+disp_3); ptr_scoreProfile4 = (__m256i *)(scoreProfile+((unsigned int)(ptr_a[i+3]))*disp_1+disp_3); // store maxRow in auxiliars aux1 = maxRow[i]; aux2 = maxRow[i+1]; aux3 = maxRow[i+2]; aux4 = maxRow[i+3]; for (ii=0; ii<dim2 ; ii++) { #pragma unroll(DB_SEQ_LEN_MULT) for( j=ii*DB_SEQ_LEN_MULT+1, jj=0; jj < DB_SEQ_LEN_MULT; jj++, j++) { //calcuate the diagonal value current1 = _mm256_add_epi32(row1[j-1], _mm256_cvtepi8_epi32(_mm_loadu_si128((__m128i *) (ptr_scoreProfile1+(j-1))))); // calculate current1 max value current1 = _mm256_max_epi32(current1, aux1); current1 = _mm256_max_epi32(current1, maxCol[j]); current1 = _mm256_max_epi32(current1, vzero_epi32); // update maxRow and maxCol aux1 = _mm256_sub_epi32(aux1, vextend_gap_epi32); maxCol[j] = _mm256_sub_epi32(maxCol[j], vextend_gap_epi32); aux0 = _mm256_sub_epi32(current1, vopen_extend_gap_epi32); aux1 = _mm256_max_epi32(aux1, aux0); maxCol[j] = _mm256_max_epi32(maxCol[j], aux0); // update max score score = _mm256_max_epi32(score,current1); //calcuate the diagonal value current2 = _mm256_add_epi32(previous2, _mm256_cvtepi8_epi32(_mm_loadu_si128((__m128i *) (ptr_scoreProfile2+(j-1))))); // update previous previous2 = current1; // calculate current2 max value current2 = _mm256_max_epi32(current2, aux2); current2 = _mm256_max_epi32(current2, maxCol[j]); current2 = _mm256_max_epi32(current2, vzero_epi32); // update maxRow and maxCol aux2 = _mm256_sub_epi32(aux2, vextend_gap_epi32); maxCol[j] = _mm256_sub_epi32(maxCol[j], vextend_gap_epi32); aux0 = _mm256_sub_epi32(current2, vopen_extend_gap_epi32); aux2 = _mm256_max_epi32(aux2, aux0); maxCol[j] = _mm256_max_epi32(maxCol[j], aux0); // update max score score = _mm256_max_epi32(score,current2); //calcuate the diagonal value current3 = _mm256_add_epi32(previous3, _mm256_cvtepi8_epi32(_mm_loadu_si128((__m128i *) (ptr_scoreProfile3+(j-1))))); // update previous previous3 = current2; // calculate current3 max value current3 = _mm256_max_epi32(current3, aux3); current3 = _mm256_max_epi32(current3, maxCol[j]); current3 = _mm256_max_epi32(current3, vzero_epi32); // update maxRow and maxCol aux3 = _mm256_sub_epi32(aux3, vextend_gap_epi32); maxCol[j] = _mm256_sub_epi32(maxCol[j], vextend_gap_epi32); aux0 = _mm256_sub_epi32(current3, vopen_extend_gap_epi32); aux3 = _mm256_max_epi32(aux3, aux0); maxCol[j] = _mm256_max_epi32(maxCol[j], aux0); // update max score score = _mm256_max_epi32(score,current3); //calcuate the diagonal value current4 = _mm256_add_epi32(previous4, _mm256_cvtepi8_epi32(_mm_loadu_si128((__m128i *) (ptr_scoreProfile4+(j-1))))); // update previous previous4 = current3; // calculate current4 max value current4 = _mm256_max_epi32(current4, aux4); current4 = _mm256_max_epi32(current4, maxCol[j]); current4 = _mm256_max_epi32(current4, vzero_epi32); // update maxRow and maxCol aux4 = _mm256_sub_epi32(aux4, vextend_gap_epi32); maxCol[j] = _mm256_sub_epi32(maxCol[j], vextend_gap_epi32); aux0 = _mm256_sub_epi32(current4, vopen_extend_gap_epi32); aux4 = _mm256_max_epi32(aux4, aux0); maxCol[j] = _mm256_max_epi32(maxCol[j], aux0); // update row buffer row2[j] = current4; // update max score score = _mm256_max_epi32(score,current4); } } // update maxRow maxRow[i] = aux1; maxRow[i+1] = aux2; maxRow[i+2] = aux3; maxRow[i+3] = aux4; // update lastCol lastCol[i] = auxLastCol; lastCol[i+1] = current1; lastCol[i+2] = current2; lastCol[i+3] = current3; auxLastCol = current4; // swap buffers tmp_row = row1; row1 = row2; row2 = tmp_row; } } // store max value _mm256_store_si256 (ptr_scores+bb1*2+bb2,score); } } } } } _mm_free(row1); _mm_free(row2); _mm_free(maxCol); _mm_free(maxRow); _mm_free(lastCol); _mm_free(scoreProfile); } *workTime = dwalltime()-tick; }
memory.h
/****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Header file for memory management utilities * * The abstract memory model has a Host (think CPU) and a Device (think GPU) and * three basic types of memory management utilities: * * 1. Malloc(..., location) * location=LOCATION_DEVICE - malloc memory on the device * location=LOCATION_HOST - malloc memory on the host * 2. MemCopy(..., method) * method=HOST_TO_DEVICE - copy from host to device * method=DEVICE_TO_HOST - copy from device to host * method=DEVICE_TO_DEVICE - copy from device to device * 3. SetExecutionMode * location=LOCATION_DEVICE - execute on the device * location=LOCATION_HOST - execute on the host * * Although the abstract model does not explicitly reflect a managed memory * model (i.e., unified memory), it can support it. Here is a summary of how * the abstract model would be mapped to specific hardware scenarios: * * Not using a device, not using managed memory * Malloc(..., location) * location=LOCATION_DEVICE - host malloc e.g., malloc * location=LOCATION_HOST - host malloc e.g., malloc * MemoryCopy(..., locTo,locFrom) * locTo=LOCATION_HOST, locFrom=LOCATION_DEVICE - copy from host to host e.g., memcpy * locTo=LOCATION_DEVICE, locFrom=LOCATION_HOST - copy from host to host e.g., memcpy * locTo=LOCATION_DEVICE, locFrom=LOCATION_DEVICE - copy from host to host e.g., memcpy * SetExecutionMode * location=LOCATION_DEVICE - execute on the host * location=LOCATION_HOST - execute on the host * * Using a device, not using managed memory * Malloc(..., location) * location=LOCATION_DEVICE - device malloc e.g., cudaMalloc * location=LOCATION_HOST - host malloc e.g., malloc * MemoryCopy(..., locTo,locFrom) * locTo=LOCATION_HOST, locFrom=LOCATION_DEVICE - copy from device to host e.g., cudaMemcpy * locTo=LOCATION_DEVICE, locFrom=LOCATION_HOST - copy from host to device e.g., cudaMemcpy * locTo=LOCATION_DEVICE, locFrom=LOCATION_DEVICE - copy from device to device e.g., cudaMemcpy * SetExecutionMode * location=LOCATION_DEVICE - execute on the device * location=LOCATION_HOST - execute on the host * * Using a device, using managed memory * Malloc(..., location) * location=LOCATION_DEVICE - managed malloc e.g., cudaMallocManaged * location=LOCATION_HOST - host malloc e.g., malloc * MemoryCopy(..., locTo,locFrom) * locTo=LOCATION_HOST, locFrom=LOCATION_DEVICE - copy from device to host e.g., cudaMallocManaged * locTo=LOCATION_DEVICE, locFrom=LOCATION_HOST - copy from host to device e.g., cudaMallocManaged * locTo=LOCATION_DEVICE, locFrom=LOCATION_DEVICE - copy from device to device e.g., cudaMallocManaged * SetExecutionMode * location=LOCATION_DEVICE - execute on the device * location=LOCATION_HOST - execute on the host * *****************************************************************************/ #ifndef hypre_MEMORY_HEADER #define hypre_MEMORY_HEADER #include <stdio.h> #include <stdlib.h> #if defined(HYPRE_USING_UNIFIED_MEMORY) && defined(HYPRE_USING_DEVICE_OPENMP) //#pragma omp requires unified_shared_memory #endif #if defined(HYPRE_USING_UMPIRE) #include "umpire/interface/umpire.h" #define HYPRE_UMPIRE_POOL_NAME_MAX_LEN 1024 #endif /* stringification: * _Pragma(string-literal), so we need to cast argument to a string * The three dots as last argument of the macro tells compiler that this is a variadic macro. * I.e. this is a macro that receives variable number of arguments. */ #define HYPRE_STR(...) #__VA_ARGS__ #define HYPRE_XSTR(...) HYPRE_STR(__VA_ARGS__) #ifdef __cplusplus extern "C" { #endif typedef enum _hypre_MemoryLocation { hypre_MEMORY_UNDEFINED = -1, hypre_MEMORY_HOST, hypre_MEMORY_HOST_PINNED, hypre_MEMORY_DEVICE, hypre_MEMORY_UNIFIED } hypre_MemoryLocation; /*------------------------------------------------------- * hypre_GetActualMemLocation * return actual location based on the selected memory model *-------------------------------------------------------*/ static inline hypre_MemoryLocation hypre_GetActualMemLocation(HYPRE_MemoryLocation location) { if (location == HYPRE_MEMORY_HOST) { return hypre_MEMORY_HOST; } if (location == HYPRE_MEMORY_DEVICE) { #if defined(HYPRE_USING_HOST_MEMORY) return hypre_MEMORY_HOST; #elif defined(HYPRE_USING_DEVICE_MEMORY) return hypre_MEMORY_DEVICE; #elif defined(HYPRE_USING_UNIFIED_MEMORY) return hypre_MEMORY_UNIFIED; #else #error Wrong HYPRE memory setting. #endif } return hypre_MEMORY_UNDEFINED; } #ifdef HYPRE_USING_MEMORY_TRACKER typedef struct { char _action[16]; void *_ptr; size_t _nbytes; hypre_MemoryLocation _memory_location; char _filename[256]; char _function[256]; HYPRE_Int _line; size_t _pair; } hypre_MemoryTrackerEntry; typedef struct { size_t actual_size; size_t alloced_size; size_t prev_end; hypre_MemoryTrackerEntry *data; } hypre_MemoryTracker; /* These Allocs are with memory tracker, for debug */ #define hypre_TAlloc(type, count, location) \ ( \ { \ void *ptr = hypre_MAlloc((size_t)(sizeof(type) * (count)), location); \ hypre_MemoryTrackerInsert("malloc", ptr, sizeof(type)*(count), hypre_GetActualMemLocation(location), __FILE__, __func__, __LINE__);\ (type *) ptr; \ } \ ) #define _hypre_TAlloc(type, count, location) \ ( \ { \ void *ptr = _hypre_MAlloc((size_t)(sizeof(type) * (count)), location); \ hypre_MemoryTrackerInsert("malloc", ptr, sizeof(type)*(count), location, __FILE__, __func__, __LINE__); \ (type *) ptr; \ } \ ) #define hypre_CTAlloc(type, count, location) \ ( \ { \ void *ptr = hypre_CAlloc((size_t)(count), (size_t)sizeof(type), location); \ hypre_MemoryTrackerInsert("calloc", ptr, sizeof(type)*(count), hypre_GetActualMemLocation(location), __FILE__, __func__, __LINE__);\ (type *) ptr; \ } \ ) #define hypre_TReAlloc(ptr, type, count, location) \ ( \ { \ hypre_MemoryTrackerInsert("rfree", ptr, (size_t) -1, hypre_GetActualMemLocation(location), __FILE__, __func__, __LINE__); \ void *new_ptr = hypre_ReAlloc((char *)ptr, (size_t)(sizeof(type) * (count)), location); \ hypre_MemoryTrackerInsert("rmalloc", new_ptr, sizeof(type)*(count), hypre_GetActualMemLocation(location), __FILE__, __func__, __LINE__);\ (type *) new_ptr; \ } \ ) #define hypre_TReAlloc_v2(ptr, old_type, old_count, new_type, new_count, location) \ ( \ { \ hypre_MemoryTrackerInsert("rfree", ptr, sizeof(old_type)*(old_count), hypre_GetActualMemLocation(location), __FILE__, __func__, __LINE__); \ void *new_ptr = hypre_ReAlloc_v2((char *)ptr, (size_t)(sizeof(old_type)*(old_count)), (size_t)(sizeof(new_type)*(new_count)), location); \ hypre_MemoryTrackerInsert("rmalloc", new_ptr, sizeof(new_type)*(new_count), hypre_GetActualMemLocation(location), __FILE__, __func__, __LINE__);\ (new_type *) new_ptr; \ } \ ) #define hypre_TMemcpy(dst, src, type, count, locdst, locsrc) \ ( \ { \ hypre_Memcpy((void *)(dst), (void *)(src), (size_t)(sizeof(type) * (count)), locdst, locsrc); \ } \ ) #define hypre_TFree(ptr, location) \ ( \ { \ hypre_MemoryTrackerInsert("free", ptr, (size_t) -1, hypre_GetActualMemLocation(location), __FILE__, __func__, __LINE__); \ hypre_Free((void *)ptr, location); \ ptr = NULL; \ } \ ) #define _hypre_TFree(ptr, location) \ ( \ { \ hypre_MemoryTrackerInsert("free", ptr, (size_t) -1, location, __FILE__, __func__, __LINE__); \ _hypre_Free((void *)ptr, location); \ ptr = NULL; \ } \ ) #else /* #ifdef HYPRE_USING_MEMORY_TRACKER */ #define hypre_TAlloc(type, count, location) \ ( (type *) hypre_MAlloc((size_t)(sizeof(type) * (count)), location) ) #define _hypre_TAlloc(type, count, location) \ ( (type *) _hypre_MAlloc((size_t)(sizeof(type) * (count)), location) ) #define hypre_CTAlloc(type, count, location) \ ( (type *) hypre_CAlloc((size_t)(count), (size_t)sizeof(type), location) ) #define hypre_TReAlloc(ptr, type, count, location) \ ( (type *) hypre_ReAlloc((char *)ptr, (size_t)(sizeof(type) * (count)), location) ) #define hypre_TReAlloc_v2(ptr, old_type, old_count, new_type, new_count, location) \ ( (new_type *) hypre_ReAlloc_v2((char *)ptr, (size_t)(sizeof(old_type)*(old_count)), (size_t)(sizeof(new_type)*(new_count)), location) ) #define hypre_TMemcpy(dst, src, type, count, locdst, locsrc) \ (hypre_Memcpy((void *)(dst), (void *)(src), (size_t)(sizeof(type) * (count)), locdst, locsrc)) #define hypre_TFree(ptr, location) \ ( hypre_Free((void *)ptr, location), ptr = NULL ) #define _hypre_TFree(ptr, location) \ ( _hypre_Free((void *)ptr, location), ptr = NULL ) #endif /* #ifdef HYPRE_USING_MEMORY_TRACKER */ /*-------------------------------------------------------------------------- * Prototypes *--------------------------------------------------------------------------*/ /* memory.c */ void * hypre_Memset(void *ptr, HYPRE_Int value, size_t num, HYPRE_MemoryLocation location); void hypre_MemPrefetch(void *ptr, size_t size, HYPRE_MemoryLocation location); void * hypre_MAlloc(size_t size, HYPRE_MemoryLocation location); void * hypre_CAlloc( size_t count, size_t elt_size, HYPRE_MemoryLocation location); void hypre_Free(void *ptr, HYPRE_MemoryLocation location); void hypre_Memcpy(void *dst, void *src, size_t size, HYPRE_MemoryLocation loc_dst, HYPRE_MemoryLocation loc_src); void * hypre_ReAlloc(void *ptr, size_t size, HYPRE_MemoryLocation location); void * hypre_ReAlloc_v2(void *ptr, size_t old_size, size_t new_size, HYPRE_MemoryLocation location); void * _hypre_MAlloc(size_t size, hypre_MemoryLocation location); void _hypre_Free(void *ptr, hypre_MemoryLocation location); HYPRE_ExecutionPolicy hypre_GetExecPolicy1(HYPRE_MemoryLocation location); HYPRE_ExecutionPolicy hypre_GetExecPolicy2(HYPRE_MemoryLocation location1, HYPRE_MemoryLocation location2); HYPRE_Int hypre_GetPointerLocation(const void *ptr, hypre_MemoryLocation *memory_location); HYPRE_Int hypre_PrintMemoryTracker(); HYPRE_Int hypre_SetCubMemPoolSize( hypre_uint bin_growth, hypre_uint min_bin, hypre_uint max_bin, size_t max_cached_bytes ); HYPRE_Int hypre_umpire_host_pooled_allocate(void **ptr, size_t nbytes); HYPRE_Int hypre_umpire_host_pooled_free(void *ptr); void *hypre_umpire_host_pooled_realloc(void *ptr, size_t size); HYPRE_Int hypre_umpire_device_pooled_allocate(void **ptr, size_t nbytes); HYPRE_Int hypre_umpire_device_pooled_free(void *ptr); HYPRE_Int hypre_umpire_um_pooled_allocate(void **ptr, size_t nbytes); HYPRE_Int hypre_umpire_um_pooled_free(void *ptr); HYPRE_Int hypre_umpire_pinned_pooled_allocate(void **ptr, size_t nbytes); HYPRE_Int hypre_umpire_pinned_pooled_free(void *ptr); #ifdef HYPRE_USING_MEMORY_TRACKER hypre_MemoryTracker * hypre_MemoryTrackerCreate(); void hypre_MemoryTrackerDestroy(hypre_MemoryTracker *tracker); void hypre_MemoryTrackerInsert(const char *action, void *ptr, size_t nbytes, hypre_MemoryLocation memory_location, const char *filename, const char *function, HYPRE_Int line); HYPRE_Int hypre_PrintMemoryTracker(); #endif /* memory_dmalloc.c */ HYPRE_Int hypre_InitMemoryDebugDML( HYPRE_Int id ); HYPRE_Int hypre_FinalizeMemoryDebugDML( void ); char *hypre_MAllocDML( HYPRE_Int size, char *file, HYPRE_Int line ); char *hypre_CAllocDML( HYPRE_Int count, HYPRE_Int elt_size, char *file, HYPRE_Int line ); char *hypre_ReAllocDML( char *ptr, HYPRE_Int size, char *file, HYPRE_Int line ); void hypre_FreeDML( char *ptr, char *file, HYPRE_Int line ); /* GPU malloc prototype */ typedef void (*GPUMallocFunc)(void **, size_t); typedef void (*GPUMfreeFunc)(void *); #ifdef __cplusplus } #endif #endif
GB_unop__acos_fc32_fc32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__acos_fc32_fc32) // op(A') function: GB (_unop_tran__acos_fc32_fc32) // C type: GxB_FC32_t // A type: GxB_FC32_t // cast: GxB_FC32_t cij = aij // unaryop: cij = cacosf (aij) #define GB_ATYPE \ GxB_FC32_t #define GB_CTYPE \ GxB_FC32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = cacosf (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC32_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC32_t z = aij ; \ Cx [pC] = cacosf (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ACOS || GxB_NO_FC32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__acos_fc32_fc32) ( GxB_FC32_t *Cx, // Cx and Ax may be aliased const GxB_FC32_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC32_t aij = Ax [p] ; GxB_FC32_t z = aij ; Cx [p] = cacosf (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC32_t aij = Ax [p] ; GxB_FC32_t z = aij ; Cx [p] = cacosf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__acos_fc32_fc32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
pathtracer.h
#ifndef CPPPT_PATHTRACER #define CPPPT_PATHTRACER #include <renderer/renderer.h> #include <math/math.h> #include <camera/camera.h> #include <image/rgb_image.h> #include <primitive/ray.h> #include <shape/intersection.h> #include <scene.h> #include <math/sampler.h> #include <omp.h> #include <iostream> namespace cpppt{ class Pathtracer : public Renderer{ int samples; Vec3 render_sky(const Ray& r) const { return Vec3(0.0); } static float russian_roulette(const Vec3& col){ //LOL this is not LAB ahahahah return (col.x*0.2 + col.y*0.5 +col.z*0.3)*0.5 + 0.4; } Vec3 integrate(const Scene& scene, const Vec2& coords, Sampler& sampler) const { Ray ray = scene.camera->get_ray(coords); Intersection intersection; Vec3 col(0.0); Vec3 mul(1.0); for(int i = 0; i<32; i++){ bool intersected = scene.primitive->intersect(ray,&intersection); if(!intersected){ col = col + mul*render_sky(ray); break; } else { col = col + mul* intersection.material->emit(ray.d*(-1.0),intersection); Vec3 sample_direction; float p = intersection.material->sample(sampler, ray.d*(-1.0), intersection, &sample_direction); if(p<=0.0){ break; } Vec3 eval = intersection.material->eval(ray.d*(-1.0), sample_direction, intersection); if(i>2){ float rr = russian_roulette(eval); if(sampler.sample() > rr) { break; } p = p*rr; } mul = mul*eval/p; ray = Ray(intersection.hitpoint, sample_direction); } } return col; } public: Pathtracer(int samples): samples(samples) {} void render(Scene& sc, std::string filename) const { RgbImage* image= &(sc.camera->get_image()); Vec2i res = image->res; #pragma omp parallel for for(int i = 0; i<res.x; i++){ RandomSampler s(i); if(i%50==0) std::cout<<"rendering line "<<i<<std::endl; for(int j = 0; j<res.y; j++){ Vec3 acc(0.0); for(int k = 0; k<samples; k++){ for(int l = 0; l<samples; l++){ float r1 = s.sample(); float r2 = s.sample(); Vector2<float> coords( ((float(i)+float(k+r1)/samples)/float(res.x))*2.0-1.0, -(((float(j)+float(l+r2)/samples)/float(res.y))*2.0-1.0)); acc = acc +integrate(sc, coords, s); } } acc = acc/(float(samples*samples)); acc = Vec3(linear2srgb(acc.x),linear2srgb(acc.y),linear2srgb(acc.z)); image->put_pixel(i,j,acc); } } image->save(filename); } }; } #endif
matrix_mul_openmp.c
#include <stdio.h> #include <stdlib.h> #include <omp.h> #include <time.h> #define MAX_COL 2048 #define MAX_ROW 2048 #define TILE_SIZE 16 #define TRUE 1 #define FALSE 0 struct timezone { int tz_minuteswest; /* minutes west of Greenwich */ int tz_dsttime; /* type of DST correction */ }; int ** create_matrix(int arraySizeX, int arraySizeY); int ** initialize(int ** M, int value); int ** transpose(int ** M); int ** multiply(int ** A, int ** B); int ** t_transp_multiply(int ** A, int ** B); int ** t_openmp_seq_mutlitply(int ** A, int ** B); int ** t_openmp_transp_mutlitply(int ** A, int ** B); int ** t_tiling_multiply(int **A, int **B,int width, int height, int tile_size); int ** t_openmp_tiling_multiply(int **A, int **B,int width, int height, int tile_size); int ** t_tiling_transpose_multiply(int **A, int **B,int width, int height, int tile_size); int ** tiling_3D(int ** A, int ** B,int width, int height,int tile_size); int ** tiling_transpose_3D(int ** A, int ** B,int width, int height,int tile_size); int gettimeofday(struct timeval *tv, struct timezone *tz); static double rtclock(); int are_equal(int ** A, int ** B); int main(int arg, char ** args){ double begin, end; int ** A = NULL; int ** B = NULL; int ** product = NULL; int ** product_init = NULL; A = create_matrix(MAX_ROW, MAX_COL); B = create_matrix(MAX_ROW, MAX_COL); A = initialize(A, 1); B = initialize(B, 1); printf("Sequential multiplication :\n"); begin = rtclock(); product = multiply(A, B); product_init=product; end = rtclock(); printf("Multiplication ended, time elapsed : %.2f sec\n", (float)(end - begin) / CLOCKS_PER_SEC); printf("\nTransposition multiplication :\n"); begin = rtclock(); product = t_transp_multiply(A, B); end = rtclock(); printf("Multiplication ended, time elapsed : %.2f sec\n", (float)(end - begin) / CLOCKS_PER_SEC); printf("Got the same result ? "); if (are_equal(product_init, product)) printf(" YES.\n"); else printf(" NO.\n"); printf("\nOpenMP sequential optimization multiplication :\n"); begin = rtclock(); product = t_openmp_seq_mutlitply(A, B); end = rtclock(); printf("Multiplication ended, time elapsed : %.2f sec\n", (float)(end - begin) / CLOCKS_PER_SEC); printf("Got the same result ? "); if (are_equal(product_init, product)) printf(" YES.\n"); else printf(" NO.\n"); printf("\nOpenMP transposition optimization multiplication :\n"); begin = rtclock(); product = t_openmp_transp_mutlitply(A,B); end = rtclock(); printf("Multiplication ended, time elapsed : %.2f sec\n", (float)(end - begin) / CLOCKS_PER_SEC); printf("Got the same result ? "); if (are_equal(product_init, product)) printf(" YES.\n"); else printf(" NO.\n"); printf("\nTiling multiplication :\n"); begin = rtclock(); product = t_tiling_multiply(A,B,MAX_COL, MAX_ROW,TILE_SIZE); end = rtclock(); printf("Multiplication ended, time elapsed : %.2f sec\n", (float)(end - begin) / CLOCKS_PER_SEC); printf("Got the same result ? "); if (are_equal(product_init, product)) printf(" YES.\n"); else printf(" NO.\n"); printf("\nOpenMP tiling multiplication :\n"); begin = rtclock(); product = t_openmp_tiling_multiply(A, B,MAX_COL, MAX_ROW,TILE_SIZE); end = rtclock(); printf("Multiplication ended, time elapsed : %.2f sec\n", (float)(end - begin) / CLOCKS_PER_SEC); printf("Got the same result ? "); if (are_equal(product_init, product)) printf(" YES.\n"); else printf(" NO.\n"); printf("\nTiling transpose multiplication :\n"); begin = rtclock(); product = t_tiling_transpose_multiply(A, B,MAX_COL, MAX_ROW,TILE_SIZE); end = rtclock(); printf("Multiplication ended, time elapsed : %.2f sec\n", (float)(end - begin) / CLOCKS_PER_SEC); printf("Got the same result ? "); if (are_equal(product_init, product)) printf(" YES.\n"); else printf(" NO.\n"); printf("\nTiling 3D multiplication :\n"); begin = rtclock(); product = tiling_3D(A, B,MAX_COL, MAX_ROW,TILE_SIZE); end = rtclock(); printf("Multiplication ended, time elapsed : %.2f sec\n", (float)(end - begin) / CLOCKS_PER_SEC); printf("Got the same result ? "); if (are_equal(product_init, product)) printf(" YES.\n"); else printf(" NO.\n"); printf("\nTiling transpose 3D multiplication :\n"); begin = rtclock(); product = tiling_transpose_3D(A, B,MAX_COL, MAX_ROW,TILE_SIZE); end = rtclock(); printf("Multiplication ended, time elapsed : %.2f sec\n", (float)(end - begin) / CLOCKS_PER_SEC); printf("Got the same result ? "); if (are_equal(product_init, product)) printf(" YES.\n"); else printf(" NO.\n"); return 0; } int** create_matrix(int arraySizeX, int arraySizeY) { int** array; array = (int**) malloc(arraySizeX*sizeof(int*)); int i; for (i = 0; i < arraySizeX; i++) { array[i] = (int*) malloc(arraySizeY*sizeof(int)); } return array; } int ** initialize(int ** M, int value){ int i,j; for (i = 0; i < MAX_ROW; i++) for ( j = 0; j < MAX_ROW; j++) { M[i][j] = value; } return M; } int ** multiply(int ** A, int ** B) { int ** C = create_matrix(MAX_ROW, MAX_COL); C = initialize(C, 0); int i,j,k; for (i = 0; i < MAX_COL; i++) for (j = 0; j < MAX_ROW; j++) for (k = 0; k < MAX_ROW; k++) C[i][j] += A[i][k] * B[k][j]; return C; } int ** transpose(int ** M){ int ** T = create_matrix(MAX_ROW, MAX_COL); int i,j; for (i = 0; i < MAX_COL; i++) for (j = 0; j < MAX_ROW; j++) T[i][j] = M[j][i]; return T; } int ** t_transp_multiply(int ** A, int ** B){ int ** C = create_matrix(MAX_ROW, MAX_COL); C = initialize(C, 0); B = transpose(B); int i,j,k; for ( i = 0; i < MAX_COL; i++) for (j = 0; j < MAX_ROW; j++) for (k = 0; k < MAX_ROW; k++) C[i][j] += A[i][k] * B[j][k]; return C; } int ** t_openmp_seq_mutlitply(int ** A, int ** B) { int ** C = create_matrix(MAX_ROW, MAX_COL); C = initialize(C, 0); int i,j,k; #pragma omp parallel for private(i,j,k) for ( i = 0; i < MAX_ROW; i++) { for (j = 0; j < MAX_COL; j++) { for (k = 0; k < MAX_COL; k++) { C[i][j] += A[i][k] * B[k][j]; } } } return C; } int ** t_openmp_transp_mutlitply(int ** A, int ** B) { int ** C = create_matrix(MAX_ROW, MAX_COL); C = initialize(C, 0); B = transpose(B); int i,j,k; #pragma omp parallel for private(i,j,k) for ( i = 0; i < MAX_COL; i++) for (j = 0; j < MAX_ROW; j++) for (k = 0; k < MAX_ROW; k++) C[i][j] += A[i][k] * B[j][k]; return C; } /* int ** t_tiling_multiply(int **A, int **B,int width, int height, int tile_size) { int ** C = create_matrix(MAX_ROW, MAX_COL); C = initialize(C, 0); int i,j,k,x,y,z; for (int i = 0; i < height; i += tile_size) { for (int j = 0; j < width; j += tile_size) { for (int k = 0; k < width; k += tile_size){ for (int y = i; y < i + tile_size; y++) { // errors started from here since the condition for ceiling y is nbr_of_block*index + deplcaement for (int x = j; x < j + tile_size; x++) { for (int z = k; z < k + tile_size; z++) { C[y][x] += A[y][z] * B[z][x]; } } } } } } return C; } */ int ** t_tiling_multiply(int **A, int **B,int width, int height, int tile_size) { int ** C = create_matrix(height, width); int i,j,k,x,y; for (i=0; i < height/tile_size; i++){ for (j=0; j < height/tile_size; j++){ for (k=tile_size*i; k<tile_size*i+tile_size; k++){ for (x=tile_size*j; x<tile_size*j+tile_size; x++){ C[k][x] = 0; for (y = 0; y < height; y++){ C[k][x] += A[k][y] * B[y][x]; } } } } } return C; } int ** t_openmp_tiling_multiply(int **A, int **B,int width, int height, int tile_size) { int ** C = create_matrix(height, width); int i,j,k,x,y; #pragma omp parallel for private(i,j,k,x,y) for (i=0; i < height/tile_size; i++){ for (j=0; j < height/tile_size; j++){ for (k=tile_size*i; k<tile_size*i+tile_size; k++){ for (x=tile_size*j; x<tile_size*j+tile_size; x++){ C[k][x] = 0; for (y = 0; y < height; y++){ C[k][x] += A[k][y] * B[y][x]; } } } } } return C; } int ** t_tiling_transpose_multiply(int **A, int **B,int width, int height, int tile_size) { int ** C = create_matrix(height, width); B = transpose(B); int i,j,k,x,y; for (i=0; i < height/tile_size; i++){ for (j=0; j < height/tile_size; j++){ for (k=tile_size*i; k<tile_size*i+tile_size; k++){ for (x=tile_size*j; x<tile_size*j+tile_size; x++){ C[k][x] = 0; for (y = 0; y < height; y++ ){ C[k][x] += A[k][y] * B[x][y]; } } } } } return C; } int ** tiling_3D(int ** A, int ** B,int width, int height,int tile_size) { int ** C = create_matrix(height, width); int i,j,i0,j0,k0,i1,j1,k1, num = height/tile_size; C = initialize(C,0); for(i0=0; i0<num; i0++) { for(j0=0; j0<num; j0++) { for(k0=0; k0<num; k0++) { for(i1=tile_size*i0; i1<tile_size*i0 + tile_size; i1++) { for(j1=tile_size*j0; j1<tile_size*j0 + tile_size; j1++) { for(k1=tile_size*k0; k1<tile_size*k0 +tile_size; k1++) { C[i1][j1] += A[i1][k1] * B[k1][j1]; } } } } } } return C; } int ** tiling_transpose_3D(int ** A, int ** B,int width, int height,int tile_size) { int ** C = create_matrix(height, width); int i,j,i0,j0,k0,i1,j1,k1, num = height/tile_size; B = transpose(B); C = initialize(C,0); for(i0=0; i0<num; i0++) { for(j0=0; j0<num; j0++) { for(k0=0; k0<num; k0++) { for(i1=tile_size*i0; i1<tile_size*i0 + tile_size; i1++) { for(j1=tile_size*j0; j1<tile_size*j0 + tile_size; j1++) { for(k1=tile_size*k0; k1<tile_size*k0 +tile_size; k1++) { C[i1][j1] += A[i1][k1] * B[j1][k1]; } } } } } } return C; } static double rtclock() { struct timeval Tp; gettimeofday (&Tp, NULL); return (Tp.tv_sec * 1.e6 + Tp.tv_usec); } int are_equal(int ** A, int ** B){ for (int i = 0; i < MAX_COL; i++) for (int j = 0; j < MAX_ROW; j++) if (A[i][j] != B[i][j]) return FALSE; return TRUE; }
Grid.h
#ifndef EASI_COMPONENT_GRID_H_ #define EASI_COMPONENT_GRID_H_ #include "easi/component/Map.h" #include "easi/util/Matrix.h" #include "easi/util/Slice.h" #include <algorithm> #include <sstream> #include <stdexcept> namespace easi { template <typename Derived> class Grid : public Map { public: enum InterpolationType { Nearest, Linear }; virtual ~Grid() {} virtual Matrix<double> map(Matrix<double>& x); void setInterpolationType(std::string const& interpolationType); void setInterpolationType(enum InterpolationType interpolationType) { m_interpolationType = interpolationType; } void getNearestNeighbour(Slice<double> const& x, double* buffer) { static_cast<Derived*>(this)->getNearestNeighbour(x, buffer); } void getNeighbours(Slice<double> const& x, double* weights, double* buffer) { static_cast<Derived*>(this)->getNeighbours(x, weights, buffer); } unsigned permutation(unsigned index) const { return static_cast<Derived const*>(this)->permutation(index); } protected: virtual unsigned numberOfThreads() const = 0; private: enum InterpolationType m_interpolationType = Linear; }; template <typename GridImpl> Matrix<double> Grid<GridImpl>::map(Matrix<double>& x) { Matrix<double> y(x.rows(), dimCodomain()); #ifdef _OPENMP #pragma omp parallel num_threads(numberOfThreads()) shared(x, y) #endif { double* neighbours = new double[(1 << dimDomain()) * dimCodomain()]; double* weights = new double[dimDomain()]; #ifdef _OPENMP #pragma omp for #endif for (unsigned i = 0; i < x.rows(); ++i) { if (m_interpolationType == Linear) { getNeighbours(x.rowSlice(i), weights, neighbours); // linear interpolation for (int d = static_cast<int>(dimDomain()) - 1; d >= 0; --d) { for (int p = 0; p < (1 << d); ++p) { for (int v = 0; v < static_cast<int>(dimCodomain()); ++v) { neighbours[p * dimCodomain() + v] = neighbours[p * dimCodomain() + v] * (1.0 - weights[d]) + neighbours[((1 << d) + p) * dimCodomain() + v] * weights[d]; } } } } else { getNearestNeighbour(x.rowSlice(i), neighbours); } for (int v = 0; v < static_cast<int>(dimCodomain()); ++v) { y(i, permutation(v)) = neighbours[v]; } } delete[] weights; delete[] neighbours; } return y; } template <typename GridImpl> void Grid<GridImpl>::setInterpolationType(std::string const& interpolationType) { std::string iType = interpolationType; std::transform(iType.begin(), iType.end(), iType.begin(), ::tolower); if (iType == "nearest") { setInterpolationType(Nearest); } else if (iType == "linear") { setInterpolationType(Linear); } else { std::stringstream ss; ss << "Invalid interpolation type " << interpolationType << "."; throw std::invalid_argument(ss.str()); } } } // namespace easi #endif
mxnet_op.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /*! * \file mxnet_op.h * \brief * \author Junyuan Xie */ #ifndef MXNET_OPERATOR_MXNET_OP_H_ #define MXNET_OPERATOR_MXNET_OP_H_ #include <dmlc/omp.h> #include <mxnet/base.h> #include <mxnet/engine.h> #include <mxnet/op_attr_types.h> #include <algorithm> #ifdef __CUDACC__ #include "../common/cuda_utils.h" #endif // __CUDACC__ namespace mxnet { namespace op { namespace mxnet_op { using namespace mshadow; #ifdef __CUDA_ARCH__ __constant__ const float PI = 3.14159265358979323846; #else const float PI = 3.14159265358979323846; using std::isnan; #endif template<typename xpu> int get_num_threads(const int N); #ifdef __CUDACC__ #define CUDA_KERNEL_LOOP(i, n) \ for (int i = blockIdx.x * blockDim.x + threadIdx.x; \ i < (n); \ i += blockDim.x * gridDim.x) inline cudaDeviceProp cuda_get_device_prop() { int device; CUDA_CALL(cudaGetDevice(&device)); cudaDeviceProp deviceProp; CUDA_CALL(cudaGetDeviceProperties(&deviceProp, device)); return deviceProp; } /*! * \brief Get the number of blocks for cuda kernel given N */ inline int cuda_get_num_blocks(const int N) { using namespace mshadow::cuda; return std::min(kMaxGridNum, (N + kBaseThreadNum - 1) / kBaseThreadNum); } template<> inline int get_num_threads<gpu>(const int N) { using namespace mshadow::cuda; return kBaseThreadNum * cuda_get_num_blocks(N); } #endif // __CUDACC__ template<> inline int get_num_threads<cpu>(const int N) { return omp_get_max_threads(); } /*! \brief operator request type switch */ #define MXNET_ASSIGN_REQ_SWITCH(req, ReqType, ...) \ switch (req) { \ case kNullOp: \ break; \ case kWriteInplace: \ case kWriteTo: \ { \ const OpReqType ReqType = kWriteTo; \ {__VA_ARGS__} \ } \ break; \ case kAddTo: \ { \ const OpReqType ReqType = kAddTo; \ {__VA_ARGS__} \ } \ break; \ default: \ break; \ } /*! * \brief assign the val to out according * to request in Kernel::Launch * \param out the data to be assigned * \param req the assignment request * \param val the value to be assigned to out * \tparam OType output type * \tparam VType value type */ #define KERNEL_ASSIGN(out, req, val) \ { \ switch (req) { \ case kNullOp: \ break; \ case kWriteTo: \ case kWriteInplace: \ (out) = (val); \ break; \ case kAddTo: \ (out) += (val); \ break; \ default: \ break; \ } \ } /* \brief Compute flattened index given coordinates and shape. */ template<int ndim> MSHADOW_XINLINE int ravel(const Shape<ndim>& coord, const Shape<ndim>& shape) { int ret = 0; #pragma unroll for (int i = 0; i < ndim; ++i) { ret = ret * shape[i] + (shape[i] > coord[i]) * coord[i]; } return ret; } /* Compute coordinates from flattened index given shape */ template<int ndim> MSHADOW_XINLINE Shape<ndim> unravel(const int idx, const Shape<ndim>& shape) { Shape<ndim> ret; #pragma unroll for (int i = ndim-1, j = idx; i >=0; --i) { int tmp = j / shape[i]; ret[i] = j - tmp*shape[i]; j = tmp; } return ret; } /* Compute dot product of two vector */ template<int ndim> MSHADOW_XINLINE int dot(const Shape<ndim>& coord, const Shape<ndim>& stride) { int ret = 0; #pragma unroll for (int i = 0; i < ndim; ++i) ret += coord[i] * stride[i]; return ret; } /* Combining unravel and dot */ template<int ndim> MSHADOW_XINLINE int unravel_dot(const int idx, const Shape<ndim>& shape, const Shape<ndim>& stride) { int ret = 0; #pragma unroll for (int i = ndim-1, j = idx; i >=0; --i) { int tmp = j / shape[i]; ret += (j - tmp*shape[i])*stride[i]; j = tmp; } return ret; } /* Calculate stride of each dim from shape */ template<int ndim> MSHADOW_XINLINE Shape<ndim> calc_stride(const Shape<ndim>& shape) { Shape<ndim> stride; index_t cumprod = 1; #pragma unroll for (int i = ndim - 1; i >= 0; --i) { stride[i] = (shape[i] > 1) ? cumprod : 0; cumprod *= shape[i]; } return stride; } /*! * \brief Simple copy data from one blob to another * \param to Destination blob * \param from Source blob */ template <typename xpu> MSHADOW_CINLINE void copy(mshadow::Stream<xpu> *s, const TBlob& to, const TBlob& from) { CHECK_EQ(from.Size(), to.Size()); CHECK_EQ(from.dev_mask(), to.dev_mask()); MSHADOW_TYPE_SWITCH(to.type_flag_, DType, { if (to.type_flag_ == from.type_flag_) { mshadow::Copy(to.FlatTo1D<xpu, DType>(), from.FlatTo1D<xpu, DType>(), s); } else { MSHADOW_TYPE_SWITCH(from.type_flag_, SrcDType, { to.FlatTo1D<xpu, DType>(s) = mshadow::expr::tcast<DType>(from.FlatTo1D<xpu, SrcDType>(s)); }) } }) } /*! \brief Binary op backward gradient OP wrapper */ template<typename GRAD_OP> struct backward_grad { /* \brief Backward calc with grad * \param a - output grad * \param args... - data to grad calculation op (what this is -- input, output, etc. -- varies) * \return input grad */ template<typename DType, typename ...Args> MSHADOW_XINLINE static DType Map(DType a, Args... args) { return DType(a * GRAD_OP::Map(args...)); } }; /*! \brief Select assignment operation based upon the req value * Also useful for mapping mshadow Compute (F<OP>) to Kernel<OP>::Launch */ template<typename OP, int req> struct op_with_req { typedef OP Operation; /*! \brief input is one tensor */ template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *out, const DType *in) { KERNEL_ASSIGN(out[i], req, OP::Map(in[i])); } /*! \brief inputs are two tensors */ template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *out, const DType *lhs, const DType *rhs) { KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], rhs[i])); } /*! \brief input is tensor and a scalar value */ template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *out, const DType *in, const DType value) { KERNEL_ASSIGN(out[i], req, OP::Map(in[i], value)); } /*! \brief No inputs (ie fill to constant value) */ template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *out) { KERNEL_ASSIGN(out[i], req, OP::Map()); } /*! \brief input is single scalar value */ template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *out, const DType value) { KERNEL_ASSIGN(out[i], req, OP::Map(value)); } /*! \brief inputs are two tensors and a scalar value */ template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *out, const DType *input_1, const DType *input_2, const DType value) { KERNEL_ASSIGN(out[i], req, OP::Map(input_1[i], input_2[i], value)); } /*! \brief inputs are three tensors (ie backward grad with binary grad function) */ template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *out, const DType *input_1, const DType *input_2, const DType *input_3) { KERNEL_ASSIGN(out[i], req, OP::Map(input_1[i], input_2[i], input_3[i])); } }; /*! * \brief Set to immediate scalar value kernel * \tparam val Scalar immediate */ template<int val> struct set_to_int { // mxnet_op version (when used directly with Kernel<>::Launch()) */ template<typename DType> MSHADOW_XINLINE static void Map(int i, DType* out) { out[i] = DType(val); } // mshadow_op version (when used with op_with_req<>) MSHADOW_XINLINE static int Map() { return val; } }; /*! \brief Special-case kernel shortcut for setting to zero */ using set_zero = set_to_int<0>; template<typename OP, typename xpu> struct Kernel; template<typename OP> struct Kernel<OP, cpu> { template<typename ...Args> inline static void Launch(mshadow::Stream<cpu> *s, const int N, Args... args) { #ifdef _OPENMP const int omp_cores = Engine::Get()->num_omp_threads_per_worker(); if (omp_cores <= 1) { // Zero means not to use OMP, but don't interfere with external OMP behavior for (int i = 0; i < N; ++i) { OP::Map(i, args...); } } else { #pragma omp parallel for num_threads(omp_cores) for (int i = 0; i < N; ++i) { OP::Map(i, args...); } } #else for (int i = 0; i < N; ++i) { OP::Map(i, args...); } #endif } }; #ifdef __CUDACC__ template<typename OP, typename ...Args> __global__ void mxnet_generic_kernel(int N, Args... args) { for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < N; i += blockDim.x * gridDim.x) { OP::Map(i, args...); } } template<typename OP> struct Kernel<OP, gpu> { template<typename ...Args> inline static void Launch(mshadow::Stream<gpu> *s, int N, Args... args) { using namespace mshadow::cuda; int ngrid = std::min(kMaxGridNum, (N + kBaseThreadNum - 1) / kBaseThreadNum); mxnet_generic_kernel<OP, Args...> <<<ngrid, kBaseThreadNum, 0, mshadow::Stream<gpu>::GetStream(s)>>>( N, args...); } }; #endif // __CUDACC__ } // namespace mxnet_op } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_MXNET_OP_H_
GB_unaryop__minv_fp32_bool.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__minv_fp32_bool // op(A') function: GB_tran__minv_fp32_bool // C type: float // A type: bool // cast: float cij = (float) aij // unaryop: cij = (1.0F)/aij #define GB_ATYPE \ bool #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ bool aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = (1.0F)/x ; // casting #define GB_CASTING(z, x) \ float z = (float) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_FP32 || GxB_NO_BOOL) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_fp32_bool ( float *restrict Cx, const bool *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__minv_fp32_bool ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
WordEmbeddingsModel.h
/* * Copyright 2016 [See AUTHORS file for list of authors] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _WORDEMBEDDINGSMODEL_ #define _WORDEMBEDDINGSMODEL_ #include <sstream> #include "../DatapointPartitions/DatapointPartitions.h" #include "Model.h" DEFINE_int32(vec_length, 30, "Length of word embeddings vector in w2v."); class WordEmbeddingsModel : public Model { private: std::vector<double> model; std::vector<double> C; std::vector<double > c_sum_mult1, c_sum_mult2; int n_words; int w2v_length; void InitializePrivateModel() { for (int i = 0; i < n_words; i++) { for (int j = 0; j < w2v_length; j++) { model[i*w2v_length+j] = ((double)rand()/(double)RAND_MAX); } } } void Initialize(const std::string &input_line) { // Expected input_line format: n_words. std::stringstream input(input_line); input >> n_words; w2v_length = FLAGS_vec_length; // Allocate memory. model.resize(n_words * w2v_length); // Initialize C = 0. C.resize(1); C[0] = 0; // Initialize private model. InitializePrivateModel(); } public: WordEmbeddingsModel(const std::string &input_line) { Initialize(input_line); } ~WordEmbeddingsModel() { } double ComputeLoss(const std::vector<Datapoint *> &datapoints) override { double loss = 0; #pragma omp parallel for num_threads(FLAGS_n_threads) reduction(+:loss) for (int i = 0; i < datapoints.size(); i++) { Datapoint *datapoint = datapoints[i]; const std::vector<double> &labels = datapoint->GetWeights(); const std::vector<int> &coordinates = datapoint->GetCoordinates(); double weight = labels[0]; int x = coordinates[0]; int y = coordinates[1]; double cross_product = 0; for (int j = 0; j < w2v_length; j++) { cross_product += (model[x*w2v_length+j]+model[y*w2v_length+j]) * (model[y*w2v_length+j]+model[y*w2v_length+j]); } loss += weight * (log(weight) - cross_product - C[0]) * (log(weight) - cross_product - C[0]); } return loss / datapoints.size(); } int CoordinateSize() override { return w2v_length; } int NumParameters() override { return n_words; } std::vector<double> & ModelData() override { return model; } virtual std::vector<double> & ExtraData() override { return C; } void PrecomputeCoefficients(Datapoint *datapoint, Gradient *g, std::vector<double> &local_model) override { if (g->coeffs.size() != 1) g->coeffs.resize(1); const std::vector<double> &labels = datapoint->GetWeights(); const std::vector<int> &coordinates = datapoint->GetCoordinates(); int coord1 = coordinates[0]; int coord2 = coordinates[1]; double weight = labels[0]; double norm = 0; for (int i = 0; i < w2v_length; i++) { norm += (local_model[coord1*w2v_length+i] + local_model[coord2*w2v_length+i]) * (local_model[coord1*w2v_length+i] + local_model[coord2*w2v_length+i]); } g->coeffs[0] = 2 * weight * (log(weight) - norm - C[0]); } virtual void Lambda(int coordinate, double &out, std::vector<double> &local_model) override { } virtual void Kappa(int coordinate, std::vector<double> &out, std::vector<double> &local_model) override { } virtual void H_bar(int coordinate, std::vector<double> &out, Gradient *g, std::vector<double> &local_model) override { int c1 = g->datapoint->GetCoordinates()[0]; int c2 = g->datapoint->GetCoordinates()[1]; for (int i = 0; i < w2v_length; i++) { out[i] = -(2 * g->coeffs[0] * (local_model[c1*w2v_length+i] + local_model[c2*w2v_length+i])); } } }; #endif
GB_unaryop__abs_int16_int32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__abs_int16_int32 // op(A') function: GB_tran__abs_int16_int32 // C type: int16_t // A type: int32_t // cast: int16_t cij = (int16_t) aij // unaryop: cij = GB_IABS (aij) #define GB_ATYPE \ int32_t #define GB_CTYPE \ int16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_IABS (x) ; // casting #define GB_CASTING(z, aij) \ int16_t z = (int16_t) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_INT16 || GxB_NO_INT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_int16_int32 ( int16_t *Cx, // Cx and Ax may be aliased int32_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__abs_int16_int32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
image.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % IIIII M M AAA GGGG EEEEE % % I MM MM A A G E % % I M M M AAAAA G GG EEE % % I M M A A G G E % % IIIII M M A A GGGG EEEEE % % % % % % MagickCore Image Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % 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 declarations. */ #include "MagickCore/studio.h" #include "MagickCore/animate.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/client.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/compress.h" #include "MagickCore/constitute.h" #include "MagickCore/delegate.h" #include "MagickCore/display.h" #include "MagickCore/draw.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/histogram.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magic.h" #include "MagickCore/magick.h" #include "MagickCore/magick-private.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/paint.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantize.h" #include "MagickCore/random_.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/semaphore.h" #include "MagickCore/signature-private.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/timer.h" #include "MagickCore/token.h" #include "MagickCore/token-private.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/version.h" #include "MagickCore/xwindow-private.h" /* Constant declaration. */ const char BackgroundColor[] = "#ffffff", /* white */ BorderColor[] = "#dfdfdf", /* gray */ DefaultTileFrame[] = "15x15+3+3", DefaultTileGeometry[] = "120x120+4+3>", DefaultTileLabel[] = "%f\n%G\n%b", ForegroundColor[] = "#000", /* black */ LoadImageTag[] = "Load/Image", LoadImagesTag[] = "Load/Images", MatteColor[] = "#bdbdbd", /* gray */ PSDensityGeometry[] = "72.0x72.0", PSPageGeometry[] = "612x792", SaveImageTag[] = "Save/Image", SaveImagesTag[] = "Save/Images", TransparentColor[] = "#00000000"; /* transparent black */ const double DefaultResolution = 72.0; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireImage() returns a pointer to an image structure initialized to % default values. % % The format of the AcquireImage method is: % % Image *AcquireImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: Many of the image default values are set from this % structure. For example, filename, compression, depth, background color, % and others. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AcquireImage(const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; Image *image; MagickStatusType flags; /* Allocate image structure. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); image=(Image *) AcquireCriticalMemory(sizeof(*image)); (void) memset(image,0,sizeof(*image)); /* Initialize Image structure. */ (void) CopyMagickString(image->magick,"MIFF",MagickPathExtent); image->storage_class=DirectClass; image->depth=MAGICKCORE_QUANTUM_DEPTH; image->colorspace=sRGBColorspace; image->rendering_intent=PerceptualIntent; image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.red_primary.z=0.0300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.green_primary.z=0.1000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.blue_primary.z=0.7900f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; image->chromaticity.white_point.z=0.3583f; image->interlace=NoInterlace; image->ticks_per_second=UndefinedTicksPerSecond; image->compose=OverCompositeOp; (void) QueryColorCompliance(MatteColor,AllCompliance,&image->matte_color, exception); (void) QueryColorCompliance(BackgroundColor,AllCompliance, &image->background_color,exception); (void) QueryColorCompliance(BorderColor,AllCompliance,&image->border_color, exception); (void) QueryColorCompliance(TransparentColor,AllCompliance, &image->transparent_color,exception); GetTimerInfo(&image->timer); image->cache=AcquirePixelCache(0); image->channel_mask=DefaultChannels; image->channel_map=AcquirePixelChannelMap(); image->blob=CloneBlobInfo((BlobInfo *) NULL); image->timestamp=time((time_t *) NULL); image->debug=IsEventLogging(); image->reference_count=1; image->semaphore=AcquireSemaphoreInfo(); image->signature=MagickCoreSignature; if (image_info == (ImageInfo *) NULL) return(image); /* Transfer image info. */ SetBlobExempt(image,image_info->file != (FILE *) NULL ? MagickTrue : MagickFalse); (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick,image_info->magick,MagickPathExtent); if (image_info->size != (char *) NULL) { (void) ParseAbsoluteGeometry(image_info->size,&image->extract_info); image->columns=image->extract_info.width; image->rows=image->extract_info.height; image->offset=image->extract_info.x; image->extract_info.x=0; image->extract_info.y=0; } if (image_info->extract != (char *) NULL) { RectangleInfo geometry; (void) memset(&geometry,0,sizeof(geometry)); flags=ParseAbsoluteGeometry(image_info->extract,&geometry); if (((flags & XValue) != 0) || ((flags & YValue) != 0)) { image->extract_info=geometry; Swap(image->columns,image->extract_info.width); Swap(image->rows,image->extract_info.height); } } image->compression=image_info->compression; image->quality=image_info->quality; image->endian=image_info->endian; image->interlace=image_info->interlace; image->units=image_info->units; if (image_info->density != (char *) NULL) { GeometryInfo geometry_info; flags=ParseGeometry(image_info->density,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; } if (image_info->page != (char *) NULL) { char *geometry; image->page=image->extract_info; geometry=GetPageGeometry(image_info->page); (void) ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); } if (image_info->depth != 0) image->depth=image_info->depth; image->dither=image_info->dither; image->matte_color=image_info->matte_color; image->background_color=image_info->background_color; image->border_color=image_info->border_color; image->transparent_color=image_info->transparent_color; image->ping=image_info->ping; image->progress_monitor=image_info->progress_monitor; image->client_data=image_info->client_data; if (image_info->cache != (void *) NULL) ClonePixelCacheMethods(image->cache,image_info->cache); /* Set all global options that map to per-image settings. */ (void) SyncImageSettings(image_info,image,exception); /* Global options that are only set for new images. */ option=GetImageOption(image_info,"delay"); if (option != (const char *) NULL) { GeometryInfo geometry_info; flags=ParseGeometry(option,&geometry_info); if ((flags & GreaterValue) != 0) { if (image->delay > (size_t) floor(geometry_info.rho+0.5)) image->delay=(size_t) floor(geometry_info.rho+0.5); } else if ((flags & LessValue) != 0) { if (image->delay < (size_t) floor(geometry_info.rho+0.5)) image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5); } else image->delay=(size_t) floor(geometry_info.rho+0.5); if ((flags & SigmaValue) != 0) image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5); } option=GetImageOption(image_info,"dispose"); if (option != (const char *) NULL) image->dispose=(DisposeType) ParseCommandOption(MagickDisposeOptions, MagickFalse,option); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireImageInfo() allocates the ImageInfo structure. % % The format of the AcquireImageInfo method is: % % ImageInfo *AcquireImageInfo(void) % */ MagickExport ImageInfo *AcquireImageInfo(void) { ImageInfo *image_info; image_info=(ImageInfo *) AcquireCriticalMemory(sizeof(*image_info)); GetImageInfo(image_info); return(image_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e N e x t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireNextImage() initializes the next image in a sequence to % default values. The next member of image points to the newly allocated % image. If there is a memory shortage, next is assigned NULL. % % The format of the AcquireNextImage method is: % % void AcquireNextImage(const ImageInfo *image_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: Many of the image default values are set from this % structure. For example, filename, compression, depth, background color, % and others. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport void AcquireNextImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { /* Allocate image structure. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); image->next=AcquireImage(image_info,exception); if (GetNextImageInList(image) == (Image *) NULL) return; (void) CopyMagickString(GetNextImageInList(image)->filename,image->filename, MagickPathExtent); if (image_info != (ImageInfo *) NULL) (void) CopyMagickString(GetNextImageInList(image)->filename, image_info->filename,MagickPathExtent); DestroyBlob(GetNextImageInList(image)); image->next->blob=ReferenceBlob(image->blob); image->next->endian=image->endian; image->next->scene=image->scene+1; image->next->previous=image; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A p p e n d I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AppendImages() takes all images from the current image pointer to the end % of the image list and appends them to each other top-to-bottom if the % stack parameter is true, otherwise left-to-right. % % The current gravity setting effects how the image is justified in the % final image. % % The format of the AppendImages method is: % % Image *AppendImages(const Image *images,const MagickBooleanType stack, % ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o stack: A value other than 0 stacks the images top-to-bottom. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AppendImages(const Image *images, const MagickBooleanType stack,ExceptionInfo *exception) { #define AppendImageTag "Append/Image" CacheView *append_view; Image *append_image; MagickBooleanType homogeneous_colorspace, status; MagickOffsetType n; PixelTrait alpha_trait; RectangleInfo geometry; register const Image *next; size_t depth, height, number_images, width; ssize_t x_offset, y, y_offset; /* Compute maximum area of appended area. */ assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); alpha_trait=images->alpha_trait; number_images=1; width=images->columns; height=images->rows; depth=images->depth; homogeneous_colorspace=MagickTrue; next=GetNextImageInList(images); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { if (next->depth > depth) depth=next->depth; if (next->colorspace != images->colorspace) homogeneous_colorspace=MagickFalse; if (next->alpha_trait != UndefinedPixelTrait) alpha_trait=BlendPixelTrait; number_images++; if (stack != MagickFalse) { if (next->columns > width) width=next->columns; height+=next->rows; continue; } width+=next->columns; if (next->rows > height) height=next->rows; } /* Append images. */ append_image=CloneImage(images,width,height,MagickTrue,exception); if (append_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(append_image,DirectClass,exception) == MagickFalse) { append_image=DestroyImage(append_image); return((Image *) NULL); } if (homogeneous_colorspace == MagickFalse) (void) SetImageColorspace(append_image,sRGBColorspace,exception); append_image->depth=depth; append_image->alpha_trait=alpha_trait; append_image->page=images->page; (void) SetImageBackgroundColor(append_image,exception); status=MagickTrue; x_offset=0; y_offset=0; next=images; append_view=AcquireAuthenticCacheView(append_image,exception); for (n=0; n < (MagickOffsetType) number_images; n++) { CacheView *image_view; MagickBooleanType proceed; SetGeometry(append_image,&geometry); GravityAdjustGeometry(next->columns,next->rows,next->gravity,&geometry); if (stack != MagickFalse) x_offset-=geometry.x; else y_offset-=geometry.y; image_view=AcquireVirtualCacheView(next,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(next,next,next->rows,1) #endif for (y=0; y < (ssize_t) next->rows; y++) { MagickBooleanType sync; PixelInfo pixel; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,next->columns,1,exception); q=QueueCacheViewAuthenticPixels(append_view,x_offset,y+y_offset, next->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } GetPixelInfo(next,&pixel); for (x=0; x < (ssize_t) next->columns; x++) { GetPixelInfoPixel(next,p,&pixel); SetPixelViaPixelInfo(append_image,&pixel,q); p+=GetPixelChannels(next); q+=GetPixelChannels(append_image); } sync=SyncCacheViewAuthenticPixels(append_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (stack == MagickFalse) { x_offset+=(ssize_t) next->columns; y_offset=0; } else { x_offset=0; y_offset+=(ssize_t) next->rows; } proceed=SetImageProgress(append_image,AppendImageTag,n,number_images); if (proceed == MagickFalse) break; next=GetNextImageInList(next); } append_view=DestroyCacheView(append_view); if (status == MagickFalse) append_image=DestroyImage(append_image); return(append_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C a t c h I m a g e E x c e p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CatchImageException() returns if no exceptions are found in the image % sequence, otherwise it determines the most severe exception and reports % it as a warning or error depending on the severity. % % The format of the CatchImageException method is: % % ExceptionType CatchImageException(Image *image) % % A description of each parameter follows: % % o image: An image sequence. % */ MagickExport ExceptionType CatchImageException(Image *image) { ExceptionInfo *exception; ExceptionType severity; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); exception=AcquireExceptionInfo(); CatchException(exception); severity=exception->severity; exception=DestroyExceptionInfo(exception); return(severity); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l i p I m a g e P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClipImagePath() sets the image clip mask based any clipping path information % if it exists. % % The format of the ClipImagePath method is: % % MagickBooleanType ClipImagePath(Image *image,const char *pathname, % const MagickBooleanType inside,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o pathname: name of clipping path resource. If name is preceded by #, use % clipping path numbered by name. % % o inside: if non-zero, later operations take effect inside clipping path. % Otherwise later operations take effect outside clipping path. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ClipImage(Image *image,ExceptionInfo *exception) { return(ClipImagePath(image,"#1",MagickTrue,exception)); } MagickExport MagickBooleanType ClipImagePath(Image *image,const char *pathname, const MagickBooleanType inside,ExceptionInfo *exception) { #define ClipImagePathTag "ClipPath/Image" char *property; const char *value; Image *clip_mask; ImageInfo *image_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pathname != NULL); property=AcquireString(pathname); (void) FormatLocaleString(property,MagickPathExtent,"8BIM:1999,2998:%s", pathname); value=GetImageProperty(image,property,exception); property=DestroyString(property); if (value == (const char *) NULL) { ThrowFileException(exception,OptionError,"NoClipPathDefined", image->filename); return(MagickFalse); } image_info=AcquireImageInfo(); (void) CopyMagickString(image_info->filename,image->filename, MagickPathExtent); (void) ConcatenateMagickString(image_info->filename,pathname, MagickPathExtent); clip_mask=BlobToImage(image_info,value,strlen(value),exception); image_info=DestroyImageInfo(image_info); if (clip_mask == (Image *) NULL) return(MagickFalse); if (clip_mask->storage_class == PseudoClass) { (void) SyncImage(clip_mask,exception); if (SetImageStorageClass(clip_mask,DirectClass,exception) == MagickFalse) return(MagickFalse); } if (inside == MagickFalse) (void) NegateImage(clip_mask,MagickFalse,exception); (void) FormatLocaleString(clip_mask->magick_filename,MagickPathExtent, "8BIM:1999,2998:%s\nPS",pathname); (void) SetImageMask(image,WritePixelMask,clip_mask,exception); clip_mask=DestroyImage(clip_mask); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImage() copies an image and returns the copy as a new image object. % % If the specified columns and rows is 0, an exact copy of the image is % returned, otherwise the pixel data is undefined and must be initialized % with the QueueAuthenticPixels() and SyncAuthenticPixels() methods. On % failure, a NULL image is returned and exception describes the reason for the % failure. % % The format of the CloneImage method is: % % Image *CloneImage(const Image *image,const size_t columns, % const size_t rows,const MagickBooleanType orphan, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the cloned image. % % o rows: the number of rows in the cloned image. % % o detach: With a value other than 0, the cloned image is detached from % its parent I/O stream. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CloneImage(const Image *image,const size_t columns, const size_t rows,const MagickBooleanType detach,ExceptionInfo *exception) { Image *clone_image; double scale; size_t length; /* Clone the image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((image->columns == 0) || (image->rows == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "NegativeOrZeroImageSize","`%s'",image->filename); return((Image *) NULL); } clone_image=(Image *) AcquireCriticalMemory(sizeof(*clone_image)); (void) memset(clone_image,0,sizeof(*clone_image)); clone_image->signature=MagickCoreSignature; clone_image->storage_class=image->storage_class; clone_image->number_channels=image->number_channels; clone_image->number_meta_channels=image->number_meta_channels; clone_image->metacontent_extent=image->metacontent_extent; clone_image->colorspace=image->colorspace; clone_image->alpha_trait=image->alpha_trait; clone_image->channels=image->channels; clone_image->mask_trait=image->mask_trait; clone_image->columns=image->columns; clone_image->rows=image->rows; clone_image->dither=image->dither; clone_image->image_info=CloneImageInfo(image->image_info); (void) CloneImageProfiles(clone_image,image); (void) CloneImageProperties(clone_image,image); (void) CloneImageArtifacts(clone_image,image); GetTimerInfo(&clone_image->timer); if (image->ascii85 != (void *) NULL) Ascii85Initialize(clone_image); clone_image->magick_columns=image->magick_columns; clone_image->magick_rows=image->magick_rows; clone_image->type=image->type; clone_image->channel_mask=image->channel_mask; clone_image->channel_map=ClonePixelChannelMap(image->channel_map); (void) CopyMagickString(clone_image->magick_filename,image->magick_filename, MagickPathExtent); (void) CopyMagickString(clone_image->magick,image->magick,MagickPathExtent); (void) CopyMagickString(clone_image->filename,image->filename, MagickPathExtent); clone_image->progress_monitor=image->progress_monitor; clone_image->client_data=image->client_data; clone_image->reference_count=1; clone_image->next=image->next; clone_image->previous=image->previous; clone_image->list=NewImageList(); if (detach == MagickFalse) clone_image->blob=ReferenceBlob(image->blob); else { clone_image->next=NewImageList(); clone_image->previous=NewImageList(); clone_image->blob=CloneBlobInfo((BlobInfo *) NULL); } clone_image->ping=image->ping; clone_image->debug=IsEventLogging(); clone_image->semaphore=AcquireSemaphoreInfo(); if (image->colormap != (PixelInfo *) NULL) { /* Allocate and copy the image colormap. */ clone_image->colors=image->colors; length=(size_t) image->colors; clone_image->colormap=(PixelInfo *) AcquireQuantumMemory(length+1, sizeof(*clone_image->colormap)); if (clone_image->colormap == (PixelInfo *) NULL) { clone_image=DestroyImage(clone_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } (void) memcpy(clone_image->colormap,image->colormap,length* sizeof(*clone_image->colormap)); } if ((columns == 0) || (rows == 0)) { if (image->montage != (char *) NULL) (void) CloneString(&clone_image->montage,image->montage); if (image->directory != (char *) NULL) (void) CloneString(&clone_image->directory,image->directory); clone_image->cache=ReferencePixelCache(image->cache); return(clone_image); } scale=1.0; if (image->columns != 0) scale=(double) columns/(double) image->columns; clone_image->page.width=(size_t) floor(scale*image->page.width+0.5); clone_image->page.x=(ssize_t) ceil(scale*image->page.x-0.5); clone_image->tile_offset.x=(ssize_t) ceil(scale*image->tile_offset.x-0.5); scale=1.0; if (image->rows != 0) scale=(double) rows/(double) image->rows; clone_image->page.height=(size_t) floor(scale*image->page.height+0.5); clone_image->page.y=(ssize_t) ceil(scale*image->page.y-0.5); clone_image->tile_offset.y=(ssize_t) ceil(scale*image->tile_offset.y-0.5); clone_image->cache=ClonePixelCache(image->cache); if (SetImageExtent(clone_image,columns,rows,exception) == MagickFalse) clone_image=DestroyImage(clone_image); return(clone_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImageInfo() makes a copy of the given image info structure. If % NULL is specified, a new image info structure is created initialized to % default values. % % The format of the CloneImageInfo method is: % % ImageInfo *CloneImageInfo(const ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport ImageInfo *CloneImageInfo(const ImageInfo *image_info) { ImageInfo *clone_info; clone_info=AcquireImageInfo(); if (image_info == (ImageInfo *) NULL) return(clone_info); clone_info->compression=image_info->compression; clone_info->temporary=image_info->temporary; clone_info->adjoin=image_info->adjoin; clone_info->antialias=image_info->antialias; clone_info->scene=image_info->scene; clone_info->number_scenes=image_info->number_scenes; clone_info->depth=image_info->depth; if (image_info->size != (char *) NULL) (void) CloneString(&clone_info->size,image_info->size); if (image_info->extract != (char *) NULL) (void) CloneString(&clone_info->extract,image_info->extract); if (image_info->scenes != (char *) NULL) (void) CloneString(&clone_info->scenes,image_info->scenes); if (image_info->page != (char *) NULL) (void) CloneString(&clone_info->page,image_info->page); clone_info->interlace=image_info->interlace; clone_info->endian=image_info->endian; clone_info->units=image_info->units; clone_info->quality=image_info->quality; if (image_info->sampling_factor != (char *) NULL) (void) CloneString(&clone_info->sampling_factor, image_info->sampling_factor); if (image_info->server_name != (char *) NULL) (void) CloneString(&clone_info->server_name,image_info->server_name); if (image_info->font != (char *) NULL) (void) CloneString(&clone_info->font,image_info->font); if (image_info->texture != (char *) NULL) (void) CloneString(&clone_info->texture,image_info->texture); if (image_info->density != (char *) NULL) (void) CloneString(&clone_info->density,image_info->density); clone_info->pointsize=image_info->pointsize; clone_info->fuzz=image_info->fuzz; clone_info->matte_color=image_info->matte_color; clone_info->background_color=image_info->background_color; clone_info->border_color=image_info->border_color; clone_info->transparent_color=image_info->transparent_color; clone_info->dither=image_info->dither; clone_info->monochrome=image_info->monochrome; clone_info->colorspace=image_info->colorspace; clone_info->type=image_info->type; clone_info->orientation=image_info->orientation; clone_info->ping=image_info->ping; clone_info->verbose=image_info->verbose; clone_info->progress_monitor=image_info->progress_monitor; clone_info->client_data=image_info->client_data; clone_info->cache=image_info->cache; if (image_info->cache != (void *) NULL) clone_info->cache=ReferencePixelCache(image_info->cache); if (image_info->profile != (void *) NULL) clone_info->profile=(void *) CloneStringInfo((StringInfo *) image_info->profile); SetImageInfoFile(clone_info,image_info->file); SetImageInfoBlob(clone_info,image_info->blob,image_info->length); clone_info->stream=image_info->stream; clone_info->custom_stream=image_info->custom_stream; (void) CopyMagickString(clone_info->magick,image_info->magick, MagickPathExtent); (void) CopyMagickString(clone_info->unique,image_info->unique, MagickPathExtent); (void) CopyMagickString(clone_info->filename,image_info->filename, MagickPathExtent); clone_info->channel=image_info->channel; (void) CloneImageOptions(clone_info,image_info); clone_info->debug=IsEventLogging(); clone_info->signature=image_info->signature; return(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o p y I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CopyImagePixels() copies pixels from the source image as defined by the % geometry the destination image at the specified offset. % % The format of the CopyImagePixels method is: % % MagickBooleanType CopyImagePixels(Image *image,const Image *source_image, % const RectangleInfo *geometry,const OffsetInfo *offset, % ExceptionInfo *exception); % % A description of each parameter follows: % % o image: the destination image. % % o source_image: the source image. % % o geometry: define the dimensions of the source pixel rectangle. % % o offset: define the offset in the destination image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType CopyImagePixels(Image *image, const Image *source_image,const RectangleInfo *geometry, const OffsetInfo *offset,ExceptionInfo *exception) { #define CopyImageTag "Copy/Image" CacheView *image_view, *source_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(source_image != (Image *) NULL); assert(geometry != (RectangleInfo *) NULL); assert(offset != (OffsetInfo *) NULL); if ((offset->x < 0) || (offset->y < 0) || ((ssize_t) (offset->x+geometry->width) > (ssize_t) image->columns) || ((ssize_t) (offset->y+geometry->height) > (ssize_t) image->rows)) ThrowBinaryException(OptionError,"GeometryDoesNotContainImage", image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); /* Copy image pixels. */ status=MagickTrue; progress=0; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,source_image,geometry->height,1) #endif for (y=0; y < (ssize_t) geometry->height; y++) { MagickBooleanType sync; register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(source_view,geometry->x,y+geometry->y, geometry->width,1,exception); q=QueueCacheViewAuthenticPixels(image_view,offset->x,y+offset->y, geometry->width,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) geometry->width; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image,channel); if ((traits == UndefinedPixelTrait) || ((traits & UpdatePixelTrait) == 0) || (source_traits == UndefinedPixelTrait)) continue; SetPixelChannel(image,channel,p[i],q); } p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_CopyImage) #endif proceed=SetImageProgress(image,CopyImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImage() dereferences an image, deallocating memory associated with % the image if the reference count becomes zero. % % The format of the DestroyImage method is: % % Image *DestroyImage(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport Image *DestroyImage(Image *image) { MagickBooleanType destroy; /* Dereference image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); destroy=MagickFalse; LockSemaphoreInfo(image->semaphore); image->reference_count--; if (image->reference_count == 0) destroy=MagickTrue; UnlockSemaphoreInfo(image->semaphore); if (destroy == MagickFalse) return((Image *) NULL); /* Destroy image. */ DestroyImagePixels(image); image->channel_map=DestroyPixelChannelMap(image->channel_map); if (image->montage != (char *) NULL) image->montage=DestroyString(image->montage); if (image->directory != (char *) NULL) image->directory=DestroyString(image->directory); if (image->colormap != (PixelInfo *) NULL) image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap); if (image->geometry != (char *) NULL) image->geometry=DestroyString(image->geometry); DestroyImageProfiles(image); DestroyImageProperties(image); DestroyImageArtifacts(image); if (image->ascii85 != (Ascii85Info *) NULL) image->ascii85=(Ascii85Info *) RelinquishMagickMemory(image->ascii85); if (image->image_info != (ImageInfo *) NULL) image->image_info=DestroyImageInfo(image->image_info); DestroyBlob(image); if (image->semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&image->semaphore); image->signature=(~MagickCoreSignature); image=(Image *) RelinquishMagickMemory(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImageInfo() deallocates memory associated with an ImageInfo % structure. % % The format of the DestroyImageInfo method is: % % ImageInfo *DestroyImageInfo(ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport ImageInfo *DestroyImageInfo(ImageInfo *image_info) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); if (image_info->size != (char *) NULL) image_info->size=DestroyString(image_info->size); if (image_info->extract != (char *) NULL) image_info->extract=DestroyString(image_info->extract); if (image_info->scenes != (char *) NULL) image_info->scenes=DestroyString(image_info->scenes); if (image_info->page != (char *) NULL) image_info->page=DestroyString(image_info->page); if (image_info->sampling_factor != (char *) NULL) image_info->sampling_factor=DestroyString( image_info->sampling_factor); if (image_info->server_name != (char *) NULL) image_info->server_name=DestroyString( image_info->server_name); if (image_info->font != (char *) NULL) image_info->font=DestroyString(image_info->font); if (image_info->texture != (char *) NULL) image_info->texture=DestroyString(image_info->texture); if (image_info->density != (char *) NULL) image_info->density=DestroyString(image_info->density); if (image_info->cache != (void *) NULL) image_info->cache=DestroyPixelCache(image_info->cache); if (image_info->profile != (StringInfo *) NULL) image_info->profile=(void *) DestroyStringInfo((StringInfo *) image_info->profile); DestroyImageOptions(image_info); image_info->signature=(~MagickCoreSignature); image_info=(ImageInfo *) RelinquishMagickMemory(image_info); return(image_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D i s a s s o c i a t e I m a g e S t r e a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DisassociateImageStream() disassociates the image stream. It checks if the % blob of the specified image is referenced by other images. If the reference % count is higher then 1 a new blob is assigned to the specified image. % % The format of the DisassociateImageStream method is: % % void DisassociateImageStream(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DisassociateImageStream(Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); DisassociateBlob(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageInfo() initializes image_info to default values. % % The format of the GetImageInfo method is: % % void GetImageInfo(ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport void GetImageInfo(ImageInfo *image_info) { char *synchronize; ExceptionInfo *exception; /* File and image dimension members. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image_info != (ImageInfo *) NULL); (void) memset(image_info,0,sizeof(*image_info)); image_info->adjoin=MagickTrue; image_info->interlace=NoInterlace; image_info->channel=DefaultChannels; image_info->quality=UndefinedCompressionQuality; image_info->antialias=MagickTrue; image_info->dither=MagickTrue; synchronize=GetEnvironmentValue("MAGICK_SYNCHRONIZE"); if (synchronize != (const char *) NULL) { image_info->synchronize=IsStringTrue(synchronize); synchronize=DestroyString(synchronize); } exception=AcquireExceptionInfo(); (void) QueryColorCompliance(BackgroundColor,AllCompliance, &image_info->background_color,exception); (void) QueryColorCompliance(BorderColor,AllCompliance, &image_info->border_color,exception); (void) QueryColorCompliance(MatteColor,AllCompliance,&image_info->matte_color, exception); (void) QueryColorCompliance(TransparentColor,AllCompliance, &image_info->transparent_color,exception); exception=DestroyExceptionInfo(exception); image_info->debug=IsEventLogging(); image_info->signature=MagickCoreSignature; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e I n f o F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageInfoFile() returns the image info file member. % % The format of the GetImageInfoFile method is: % % FILE *GetImageInfoFile(const ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport FILE *GetImageInfoFile(const ImageInfo *image_info) { return(image_info->file); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageMask() returns the mask associated with the image. % % The format of the GetImageMask method is: % % Image *GetImageMask(const Image *image,const PixelMask type, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the mask type, ReadPixelMask or WritePixelMask. % */ MagickExport Image *GetImageMask(const Image *image,const PixelMask type, ExceptionInfo *exception) { CacheView *mask_view, *image_view; Image *mask_image; MagickBooleanType status; ssize_t y; /* Get image mask. */ assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); mask_image=AcquireImage((ImageInfo *) NULL,exception); status=SetImageExtent(mask_image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImage(mask_image)); status=MagickTrue; mask_image->alpha_trait=UndefinedPixelTrait; (void) SetImageColorspace(mask_image,GRAYColorspace,exception); image_view=AcquireVirtualCacheView(image,exception); mask_view=AcquireAuthenticCacheView(mask_image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(mask_view,0,y,mask_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { switch (type) { case ReadPixelMask: { SetPixelGray(mask_image,GetPixelReadMask(image,p),q); break; } case WritePixelMask: { SetPixelGray(mask_image,GetPixelWriteMask(image,p),q); break; } default: { SetPixelGray(mask_image,GetPixelCompositeMask(image,p),q); break; } } p+=GetPixelChannels(image); q+=GetPixelChannels(mask_image); } if (SyncCacheViewAuthenticPixels(mask_view,exception) == MagickFalse) status=MagickFalse; } mask_view=DestroyCacheView(mask_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) mask_image=DestroyImage(mask_image); return(mask_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e R e f e r e n c e C o u n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageReferenceCount() returns the image reference count. % % The format of the GetReferenceCount method is: % % ssize_t GetImageReferenceCount(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport ssize_t GetImageReferenceCount(Image *image) { ssize_t reference_count; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); LockSemaphoreInfo(image->semaphore); reference_count=image->reference_count; UnlockSemaphoreInfo(image->semaphore); return(reference_count); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i r t u a l P i x e l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageVirtualPixelMethod() gets the "virtual pixels" method for the % image. A virtual pixel is any pixel access that is outside the boundaries % of the image cache. % % The format of the GetImageVirtualPixelMethod() method is: % % VirtualPixelMethod GetImageVirtualPixelMethod(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport VirtualPixelMethod GetImageVirtualPixelMethod(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); return(GetPixelCacheVirtualMethod(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e r p r e t I m a g e F i l e n a m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpretImageFilename() interprets embedded characters in an image filename. % The filename length is returned. % % The format of the InterpretImageFilename method is: % % size_t InterpretImageFilename(const ImageInfo *image_info,Image *image, % const char *format,int value,char *filename,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info.. % % o image: the image. % % o format: A filename describing the format to use to write the numeric % argument. Only the first numeric format identifier is replaced. % % o value: Numeric value to substitute into format filename. % % o filename: return the formatted filename in this character buffer. % % o exception: return any errors or warnings in this structure. % */ MagickExport size_t InterpretImageFilename(const ImageInfo *image_info, Image *image,const char *format,int value,char *filename, ExceptionInfo *exception) { char *q; int c; MagickBooleanType canonical; register const char *p; ssize_t field_width, offset; canonical=MagickFalse; offset=0; (void) CopyMagickString(filename,format,MagickPathExtent); for (p=strchr(format,'%'); p != (char *) NULL; p=strchr(p+1,'%')) { q=(char *) p+1; if (*q == '%') { p=q+1; continue; } field_width=0; if (*q == '0') field_width=(ssize_t) strtol(q,&q,10); switch (*q) { case 'd': case 'o': case 'x': { q++; c=(*q); *q='\0'; (void) FormatLocaleString(filename+(p-format-offset),(size_t) (MagickPathExtent-(p-format-offset)),p,value); offset+=(4-field_width); *q=c; (void) ConcatenateMagickString(filename,q,MagickPathExtent); canonical=MagickTrue; if (*(q-1) != '%') break; p++; break; } case '[': { char pattern[MagickPathExtent]; const char *option; register char *r; register ssize_t i; ssize_t depth; /* Image option. */ if (strchr(p,']') == (char *) NULL) break; depth=1; r=q+1; for (i=0; (i < (MagickPathExtent-1L)) && (*r != '\0'); i++) { if (*r == '[') depth++; if (*r == ']') depth--; if (depth <= 0) break; pattern[i]=(*r++); } pattern[i]='\0'; if (LocaleNCompare(pattern,"filename:",9) != 0) break; option=(const char *) NULL; if (image != (Image *) NULL) option=GetImageProperty(image,pattern,exception); if ((option == (const char *) NULL) && (image != (Image *) NULL)) option=GetImageArtifact(image,pattern); if ((option == (const char *) NULL) && (image_info != (ImageInfo *) NULL)) option=GetImageOption(image_info,pattern); if (option == (const char *) NULL) break; q--; c=(*q); *q='\0'; (void) CopyMagickString(filename+(p-format-offset),option,(size_t) (MagickPathExtent-(p-format-offset))); offset+=strlen(pattern)-4; *q=c; (void) ConcatenateMagickString(filename,r+1,MagickPathExtent); canonical=MagickTrue; if (*(q-1) != '%') break; p++; break; } default: break; } } for (q=filename; *q != '\0'; q++) if ((*q == '%') && (*(q+1) == '%')) { (void) CopyMagickString(q,q+1,(size_t) (MagickPathExtent-(q-filename))); canonical=MagickTrue; } if (canonical == MagickFalse) (void) CopyMagickString(filename,format,MagickPathExtent); return(strlen(filename)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s H i g h D y n a m i c R a n g e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsHighDynamicRangeImage() returns MagickTrue if any pixel component is % non-integer or exceeds the bounds of the quantum depth (e.g. for Q16 % 0..65535. % % The format of the IsHighDynamicRangeImage method is: % % MagickBooleanType IsHighDynamicRangeImage(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType IsHighDynamicRangeImage(const Image *image, ExceptionInfo *exception) { #if !defined(MAGICKCORE_HDRI_SUPPORT) (void) image; (void) exception; return(MagickFalse); #else CacheView *image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double pixel; PixelTrait traits; traits=GetPixelChannelTraits(image,(PixelChannel) i); if (traits == UndefinedPixelTrait) continue; pixel=(double) p[i]; if ((pixel < 0.0) || (pixel > QuantumRange) || (pixel != (double) ((QuantumAny) pixel))) break; } p+=GetPixelChannels(image); if (i < (ssize_t) GetPixelChannels(image)) status=MagickFalse; } if (x < (ssize_t) image->columns) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status != MagickFalse ? MagickFalse : MagickTrue); #endif } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s I m a g e O b j e c t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsImageObject() returns MagickTrue if the image sequence contains a valid % set of image objects. % % The format of the IsImageObject method is: % % MagickBooleanType IsImageObject(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickBooleanType IsImageObject(const Image *image) { register const Image *p; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) if (p->signature != MagickCoreSignature) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s T a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsTaintImage() returns MagickTrue any pixel in the image has been altered % since it was first constituted. % % The format of the IsTaintImage method is: % % MagickBooleanType IsTaintImage(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickBooleanType IsTaintImage(const Image *image) { char magick[MagickPathExtent], filename[MagickPathExtent]; register const Image *p; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); (void) CopyMagickString(magick,image->magick,MagickPathExtent); (void) CopyMagickString(filename,image->filename,MagickPathExtent); for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) { if (p->taint != MagickFalse) return(MagickTrue); if (LocaleCompare(p->magick,magick) != 0) return(MagickTrue); if (LocaleCompare(p->filename,filename) != 0) return(MagickTrue); } return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o d i f y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ModifyImage() ensures that there is only a single reference to the image % to be modified, updating the provided image pointer to point to a clone of % the original image if necessary. % % The format of the ModifyImage method is: % % MagickBooleanType ModifyImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ModifyImage(Image **image, ExceptionInfo *exception) { Image *clone_image; assert(image != (Image **) NULL); assert(*image != (Image *) NULL); assert((*image)->signature == MagickCoreSignature); if ((*image)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*image)->filename); if (GetImageReferenceCount(*image) <= 1) return(MagickTrue); clone_image=CloneImage(*image,0,0,MagickTrue,exception); LockSemaphoreInfo((*image)->semaphore); (*image)->reference_count--; UnlockSemaphoreInfo((*image)->semaphore); *image=clone_image; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e w M a g i c k I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NewMagickImage() creates a blank image canvas of the specified size and % background color. % % The format of the NewMagickImage method is: % % Image *NewMagickImage(const ImageInfo *image_info,const size_t width, % const size_t height,const PixelInfo *background, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the image width. % % o height: the image height. % % o background: the image color. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *NewMagickImage(const ImageInfo *image_info, const size_t width,const size_t height,const PixelInfo *background, ExceptionInfo *exception) { CacheView *image_view; Image *image; MagickBooleanType status; ssize_t y; assert(image_info != (const ImageInfo *) NULL); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image_info->signature == MagickCoreSignature); assert(background != (const PixelInfo *) NULL); image=AcquireImage(image_info,exception); image->columns=width; image->rows=height; image->colorspace=background->colorspace; image->alpha_trait=background->alpha_trait; image->fuzz=background->fuzz; image->depth=background->depth; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelViaPixelInfo(image,background,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (status == MagickFalse) image=DestroyImage(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e f e r e n c e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReferenceImage() increments the reference count associated with an image % returning a pointer to the image. % % The format of the ReferenceImage method is: % % Image *ReferenceImage(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport Image *ReferenceImage(Image *image) { assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); LockSemaphoreInfo(image->semaphore); image->reference_count++; UnlockSemaphoreInfo(image->semaphore); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t I m a g e P a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetImagePage() resets the image page canvas and position. % % The format of the ResetImagePage method is: % % MagickBooleanType ResetImagePage(Image *image,const char *page) % % A description of each parameter follows: % % o image: the image. % % o page: the relative page specification. % */ MagickExport MagickBooleanType ResetImagePage(Image *image,const char *page) { MagickStatusType flags; RectangleInfo geometry; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); flags=ParseAbsoluteGeometry(page,&geometry); if ((flags & WidthValue) != 0) { if ((flags & HeightValue) == 0) geometry.height=geometry.width; image->page.width=geometry.width; image->page.height=geometry.height; } if ((flags & AspectValue) != 0) { if ((flags & XValue) != 0) image->page.x+=geometry.x; if ((flags & YValue) != 0) image->page.y+=geometry.y; } else { if ((flags & XValue) != 0) { image->page.x=geometry.x; if ((image->page.width == 0) && (geometry.x > 0)) image->page.width=image->columns+geometry.x; } if ((flags & YValue) != 0) { image->page.y=geometry.y; if ((image->page.height == 0) && (geometry.y > 0)) image->page.height=image->rows+geometry.y; } } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetImagePixels() reset the image pixels, that is, all the pixel components % are zereod. % % The format of the SetImage method is: % % MagickBooleanType ResetImagePixels(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ResetImagePixels(Image *image, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; size_t length; ssize_t y; void *pixels; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); pixels=AcquirePixelCachePixels(image,&length,exception); if (pixels != (void *) NULL) { /* Reset in-core image pixels. */ (void) memset(pixels,0,length); return(MagickTrue); } /* Reset image pixels. */ status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { (void) memset(q,0,GetPixelChannels(image)*sizeof(Quantum)); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e A l p h a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageAlpha() sets the alpha levels of the image. % % The format of the SetImageAlpha method is: % % MagickBooleanType SetImageAlpha(Image *image,const Quantum alpha, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o alpha: the level of transparency: 0 is fully transparent and QuantumRange % is fully opaque. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageAlpha(Image *image,const Quantum alpha, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); image->alpha_trait=BlendPixelTrait; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelAlpha(image,alpha,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e B a c k g r o u n d C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageBackgroundColor() initializes the image pixels to the image % background color. The background color is defined by the background_color % member of the image structure. % % The format of the SetImage method is: % % MagickBooleanType SetImageBackgroundColor(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageBackgroundColor(Image *image, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; PixelInfo background; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if ((image->background_color.alpha != OpaqueAlpha) && (image->alpha_trait == UndefinedPixelTrait)) (void) SetImageAlphaChannel(image,OnAlphaChannel,exception); ConformPixelInfo(image,&image->background_color,&background,exception); /* Set image background color. */ status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelViaPixelInfo(image,&background,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e C h a n n e l M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageChannelMask() sets the image channel mask from the specified channel % mask. % % The format of the SetImageChannelMask method is: % % ChannelType SetImageChannelMask(Image *image, % const ChannelType channel_mask) % % A description of each parameter follows: % % o image: the image. % % o channel_mask: the channel mask. % */ MagickExport ChannelType SetImageChannelMask(Image *image, const ChannelType channel_mask) { return(SetPixelChannelMask(image,channel_mask)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageColor() set the entire image canvas to the specified color. % % The format of the SetImageColor method is: % % MagickBooleanType SetImageColor(Image *image,const PixelInfo *color, % ExeptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o background: the image color. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageColor(Image *image, const PixelInfo *color,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); assert(color != (const PixelInfo *) NULL); image->colorspace=color->colorspace; image->alpha_trait=color->alpha_trait; image->fuzz=color->fuzz; image->depth=color->depth; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelViaPixelInfo(image,color,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e S t o r a g e C l a s s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageStorageClass() sets the image class: DirectClass for true color % images or PseudoClass for colormapped images. % % The format of the SetImageStorageClass method is: % % MagickBooleanType SetImageStorageClass(Image *image, % const ClassType storage_class,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o storage_class: The image class. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageStorageClass(Image *image, const ClassType storage_class,ExceptionInfo *exception) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image->storage_class=storage_class; return(SyncImagePixelCache(image,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageExtent() sets the image size (i.e. columns & rows). % % The format of the SetImageExtent method is: % % MagickBooleanType SetImageExtent(Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: The image width in pixels. % % o rows: The image height in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageExtent(Image *image,const size_t columns, const size_t rows,ExceptionInfo *exception) { if ((columns == 0) || (rows == 0)) ThrowBinaryException(ImageError,"NegativeOrZeroImageSize",image->filename); image->columns=columns; image->rows=rows; if ((image->depth == 0) || (image->depth > (8*sizeof(MagickSizeType)))) ThrowBinaryException(ImageError,"ImageDepthNotSupported",image->filename); return(SyncImagePixelCache(image,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfo() initializes the 'magick' field of the ImageInfo structure. % It is set to a type of image format based on the prefix or suffix of the % filename. For example, 'ps:image' returns PS indicating a Postscript image. % JPEG is returned for this filename: 'image.jpg'. The filename prefix has % precendence over the suffix. Use an optional index enclosed in brackets % after a file name to specify a desired scene of a multi-resolution image % format like Photo CD (e.g. img0001.pcd[4]). A True (non-zero) return value % indicates success. % % The format of the SetImageInfo method is: % % MagickBooleanType SetImageInfo(ImageInfo *image_info, % const unsigned int frames,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o frames: the number of images you intend to write. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageInfo(ImageInfo *image_info, const unsigned int frames,ExceptionInfo *exception) { char component[MagickPathExtent], magic[MagickPathExtent], *q; const MagicInfo *magic_info; const MagickInfo *magick_info; ExceptionInfo *sans_exception; Image *image; MagickBooleanType status; register const char *p; ssize_t count; /* Look for 'image.format' in filename. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); *component='\0'; GetPathComponent(image_info->filename,SubimagePath,component); if (*component != '\0') { /* Look for scene specification (e.g. img0001.pcd[4]). */ if (IsSceneGeometry(component,MagickFalse) == MagickFalse) { if (IsGeometry(component) != MagickFalse) (void) CloneString(&image_info->extract,component); } else { size_t first, last; (void) CloneString(&image_info->scenes,component); image_info->scene=StringToUnsignedLong(image_info->scenes); image_info->number_scenes=image_info->scene; p=image_info->scenes; for (q=(char *) image_info->scenes; *q != '\0'; p++) { while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; first=(size_t) strtol(p,&q,10); last=first; while (isspace((int) ((unsigned char) *q)) != 0) q++; if (*q == '-') last=(size_t) strtol(q+1,&q,10); if (first > last) Swap(first,last); if (first < image_info->scene) image_info->scene=first; if (last > image_info->number_scenes) image_info->number_scenes=last; p=q; } image_info->number_scenes-=image_info->scene-1; } } *component='\0'; if (*image_info->magick == '\0') GetPathComponent(image_info->filename,ExtensionPath,component); #if defined(MAGICKCORE_ZLIB_DELEGATE) if (*component != '\0') if ((LocaleCompare(component,"gz") == 0) || (LocaleCompare(component,"Z") == 0) || (LocaleCompare(component,"svgz") == 0) || (LocaleCompare(component,"wmz") == 0)) { char path[MagickPathExtent]; (void) CopyMagickString(path,image_info->filename,MagickPathExtent); path[strlen(path)-strlen(component)-1]='\0'; GetPathComponent(path,ExtensionPath,component); } #endif #if defined(MAGICKCORE_BZLIB_DELEGATE) if (*component != '\0') if (LocaleCompare(component,"bz2") == 0) { char path[MagickPathExtent]; (void) CopyMagickString(path,image_info->filename,MagickPathExtent); path[strlen(path)-strlen(component)-1]='\0'; GetPathComponent(path,ExtensionPath,component); } #endif image_info->affirm=MagickFalse; sans_exception=AcquireExceptionInfo(); if ((*component != '\0') && (IsGlob(component) == MagickFalse)) { MagickFormatType format_type; register ssize_t i; static const char *format_type_formats[] = { "AUTOTRACE", "BROWSE", "DCRAW", "EDIT", "LAUNCH", "MPEG:DECODE", "MPEG:ENCODE", "PRINT", "PS:ALPHA", "PS:CMYK", "PS:COLOR", "PS:GRAY", "PS:MONO", "SCAN", "SHOW", "WIN", (char *) NULL }; /* User specified image format. */ (void) CopyMagickString(magic,component,MagickPathExtent); LocaleUpper(magic); /* Look for explicit image formats. */ format_type=UndefinedFormatType; magick_info=GetMagickInfo(magic,sans_exception); if ((magick_info != (const MagickInfo *) NULL) && (magick_info->format_type != UndefinedFormatType)) format_type=magick_info->format_type; i=0; while ((format_type == UndefinedFormatType) && (format_type_formats[i] != (char *) NULL)) { if ((*magic == *format_type_formats[i]) && (LocaleCompare(magic,format_type_formats[i]) == 0)) format_type=ExplicitFormatType; i++; } if (format_type == UndefinedFormatType) (void) CopyMagickString(image_info->magick,magic,MagickPathExtent); else if (format_type == ExplicitFormatType) { image_info->affirm=MagickTrue; (void) CopyMagickString(image_info->magick,magic,MagickPathExtent); } if (LocaleCompare(magic,"RGB") == 0) image_info->affirm=MagickFalse; /* maybe SGI disguised as RGB */ } /* Look for explicit 'format:image' in filename. */ *magic='\0'; GetPathComponent(image_info->filename,MagickPath,magic); if (*magic == '\0') { (void) CopyMagickString(magic,image_info->magick,MagickPathExtent); magick_info=GetMagickInfo(magic,sans_exception); GetPathComponent(image_info->filename,CanonicalPath,component); (void) CopyMagickString(image_info->filename,component,MagickPathExtent); } else { const DelegateInfo *delegate_info; /* User specified image format. */ LocaleUpper(magic); magick_info=GetMagickInfo(magic,sans_exception); delegate_info=GetDelegateInfo(magic,"*",sans_exception); if (delegate_info == (const DelegateInfo *) NULL) delegate_info=GetDelegateInfo("*",magic,sans_exception); if (((magick_info != (const MagickInfo *) NULL) || (delegate_info != (const DelegateInfo *) NULL)) && (IsMagickConflict(magic) == MagickFalse)) { image_info->affirm=MagickTrue; (void) CopyMagickString(image_info->magick,magic,MagickPathExtent); GetPathComponent(image_info->filename,CanonicalPath,component); (void) CopyMagickString(image_info->filename,component, MagickPathExtent); } } sans_exception=DestroyExceptionInfo(sans_exception); if ((magick_info == (const MagickInfo *) NULL) || (GetMagickEndianSupport(magick_info) == MagickFalse)) image_info->endian=UndefinedEndian; if ((image_info->adjoin != MagickFalse) && (frames > 1)) { /* Test for multiple image support (e.g. image%02d.png). */ (void) InterpretImageFilename(image_info,(Image *) NULL, image_info->filename,(int) image_info->scene,component,exception); if ((LocaleCompare(component,image_info->filename) != 0) && (strchr(component,'%') == (char *) NULL)) image_info->adjoin=MagickFalse; } if ((image_info->adjoin != MagickFalse) && (frames > 0)) { /* Some image formats do not support multiple frames per file. */ magick_info=GetMagickInfo(magic,exception); if (magick_info != (const MagickInfo *) NULL) if (GetMagickAdjoin(magick_info) == MagickFalse) image_info->adjoin=MagickFalse; } if (image_info->affirm != MagickFalse) return(MagickTrue); if (frames == 0) { unsigned char *magick; size_t magick_size; /* Determine the image format from the first few bytes of the file. */ magick_size=GetMagicPatternExtent(exception); if (magick_size == 0) return(MagickFalse); image=AcquireImage(image_info,exception); (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImage(image); return(MagickFalse); } if ((IsBlobSeekable(image) == MagickFalse) || (IsBlobExempt(image) != MagickFalse)) { /* Copy image to seekable temporary file. */ *component='\0'; status=ImageToFile(image,component,exception); (void) CloseBlob(image); if (status == MagickFalse) { image=DestroyImage(image); return(MagickFalse); } SetImageInfoFile(image_info,(FILE *) NULL); (void) CopyMagickString(image->filename,component,MagickPathExtent); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImage(image); return(MagickFalse); } (void) CopyMagickString(image_info->filename,component, MagickPathExtent); image_info->temporary=MagickTrue; } magick=(unsigned char *) AcquireMagickMemory(magick_size); if (magick == (unsigned char *) NULL) { (void) CloseBlob(image); image=DestroyImage(image); return(MagickFalse); } (void) memset(magick,0,magick_size); count=ReadBlob(image,magick_size,magick); (void) SeekBlob(image,-((MagickOffsetType) count),SEEK_CUR); (void) CloseBlob(image); image=DestroyImage(image); /* Check magic.xml configuration file. */ sans_exception=AcquireExceptionInfo(); magic_info=GetMagicInfo(magick,(size_t) count,sans_exception); magick=(unsigned char *) RelinquishMagickMemory(magick); if ((magic_info != (const MagicInfo *) NULL) && (GetMagicName(magic_info) != (char *) NULL)) { /* Try to use magick_info that was determined earlier by the extension */ if ((magick_info != (const MagickInfo *) NULL) && (GetMagickUseExtension(magick_info) != MagickFalse) && (LocaleCompare(magick_info->module,GetMagicName( magic_info)) == 0)) (void) CopyMagickString(image_info->magick,magick_info->name, MagickPathExtent); else { (void) CopyMagickString(image_info->magick,GetMagicName( magic_info),MagickPathExtent); magick_info=GetMagickInfo(image_info->magick,sans_exception); } if ((magick_info == (const MagickInfo *) NULL) || (GetMagickEndianSupport(magick_info) == MagickFalse)) image_info->endian=UndefinedEndian; sans_exception=DestroyExceptionInfo(sans_exception); return(MagickTrue); } magick_info=GetMagickInfo(image_info->magick,sans_exception); if ((magick_info == (const MagickInfo *) NULL) || (GetMagickEndianSupport(magick_info) == MagickFalse)) image_info->endian=UndefinedEndian; sans_exception=DestroyExceptionInfo(sans_exception); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e I n f o B l o b % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfoBlob() sets the image info blob member. % % The format of the SetImageInfoBlob method is: % % void SetImageInfoBlob(ImageInfo *image_info,const void *blob, % const size_t length) % % A description of each parameter follows: % % o image_info: the image info. % % o blob: the blob. % % o length: the blob length. % */ MagickExport void SetImageInfoBlob(ImageInfo *image_info,const void *blob, const size_t length) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); image_info->blob=(void *) blob; image_info->length=length; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e I n f o C u s t o m S t r e a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfoCustomStream() sets the image info custom stream handlers. % % The format of the SetImageInfoCustomStream method is: % % void SetImageInfoCustomStream(ImageInfo *image_info, % CustomStreamInfo *custom_stream) % % A description of each parameter follows: % % o image_info: the image info. % % o custom_stream: your custom stream methods. % */ MagickExport void SetImageInfoCustomStream(ImageInfo *image_info, CustomStreamInfo *custom_stream) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); image_info->custom_stream=(CustomStreamInfo *) custom_stream; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e I n f o F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfoFile() sets the image info file member. % % The format of the SetImageInfoFile method is: % % void SetImageInfoFile(ImageInfo *image_info,FILE *file) % % A description of each parameter follows: % % o image_info: the image info. % % o file: the file. % */ MagickExport void SetImageInfoFile(ImageInfo *image_info,FILE *file) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); image_info->file=file; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageMask() associates a mask with the image. The mask must be the same % dimensions as the image. % % The format of the SetImageMask method is: % % MagickBooleanType SetImageMask(Image *image,const PixelMask type, % const Image *mask,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the mask type, ReadPixelMask or WritePixelMask. % % o mask: the image mask. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageMask(Image *image,const PixelMask type, const Image *mask,ExceptionInfo *exception) { CacheView *mask_view, *image_view; MagickBooleanType status; ssize_t y; /* Set image mask. */ assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (mask == (const Image *) NULL) { switch (type) { case ReadPixelMask: image->channels&=(~ReadMaskChannel); break; case WritePixelMask: image->channels&=(~WriteMaskChannel); break; default: image->channels&=(~CompositeMaskChannel); break; } return(SyncImagePixelCache(image,exception)); } switch (type) { case ReadPixelMask: image->channels|=ReadMaskChannel; break; case WritePixelMask: image->channels|=WriteMaskChannel; break; default: image->channels|=CompositeMaskChannel; break; } if (SyncImagePixelCache(image,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; image->mask_trait=UpdatePixelTrait; mask_view=AcquireVirtualCacheView(mask,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(mask,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(mask_view,0,y,mask->columns,1,exception); q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType intensity; intensity=0.0; if ((x < (ssize_t) mask->columns) && (y < (ssize_t) mask->rows)) intensity=GetPixelIntensity(mask,p); switch (type) { case ReadPixelMask: { SetPixelReadMask(image,ClampToQuantum(intensity),q); break; } case WritePixelMask: { SetPixelWriteMask(image,ClampToQuantum(intensity),q); break; } default: { SetPixelCompositeMask(image,ClampToQuantum(intensity),q); break; } } p+=GetPixelChannels(mask); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image->mask_trait=UndefinedPixelTrait; mask_view=DestroyCacheView(mask_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e R e g i o n M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageRegionMask() associates a mask with the image as defined by the % specified region. % % The format of the SetImageRegionMask method is: % % MagickBooleanType SetImageRegionMask(Image *image,const PixelMask type, % const RectangleInfo *region,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the mask type, ReadPixelMask or WritePixelMask. % % o geometry: the mask region. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageRegionMask(Image *image, const PixelMask type,const RectangleInfo *region,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; /* Set image mask as defined by the region. */ assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (region == (const RectangleInfo *) NULL) { switch (type) { case ReadPixelMask: image->channels&=(~ReadMaskChannel); break; case WritePixelMask: image->channels&=(~WriteMaskChannel); break; default: image->channels&=(~CompositeMaskChannel); break; } return(SyncImagePixelCache(image,exception)); } switch (type) { case ReadPixelMask: image->channels|=ReadMaskChannel; break; case WritePixelMask: image->channels|=WriteMaskChannel; break; default: image->channels|=CompositeMaskChannel; break; } if (SyncImagePixelCache(image,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; image->mask_trait=UpdatePixelTrait; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { Quantum pixel; pixel=QuantumRange; if (((x >= region->x) && (x < (region->x+(ssize_t) region->width))) && ((y >= region->y) && (y < (region->y+(ssize_t) region->height)))) pixel=(Quantum) 0; switch (type) { case ReadPixelMask: { SetPixelReadMask(image,pixel,q); break; } case WritePixelMask: { SetPixelWriteMask(image,pixel,q); break; } default: { SetPixelCompositeMask(image,pixel,q); break; } } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image->mask_trait=UndefinedPixelTrait; image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e V i r t u a l P i x e l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageVirtualPixelMethod() sets the "virtual pixels" method for the % image and returns the previous setting. A virtual pixel is any pixel access % that is outside the boundaries of the image cache. % % The format of the SetImageVirtualPixelMethod() method is: % % VirtualPixelMethod SetImageVirtualPixelMethod(Image *image, % const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: choose the type of virtual pixel. % % o exception: return any errors or warnings in this structure. % */ MagickExport VirtualPixelMethod SetImageVirtualPixelMethod(Image *image, const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) { assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); return(SetPixelCacheVirtualMethod(image,virtual_pixel_method,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S m u s h I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SmushImages() takes all images from the current image pointer to the end % of the image list and smushes them to each other top-to-bottom if the % stack parameter is true, otherwise left-to-right. % % The current gravity setting now effects how the image is justified in the % final image. % % The format of the SmushImages method is: % % Image *SmushImages(const Image *images,const MagickBooleanType stack, % ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o stack: A value other than 0 stacks the images top-to-bottom. % % o offset: minimum distance in pixels between images. % % o exception: return any errors or warnings in this structure. % */ static ssize_t SmushXGap(const Image *smush_image,const Image *images, const ssize_t offset,ExceptionInfo *exception) { CacheView *left_view, *right_view; const Image *left_image, *right_image; RectangleInfo left_geometry, right_geometry; register const Quantum *p; register ssize_t i, y; size_t gap; ssize_t x; if (images->previous == (Image *) NULL) return(0); right_image=images; SetGeometry(smush_image,&right_geometry); GravityAdjustGeometry(right_image->columns,right_image->rows, right_image->gravity,&right_geometry); left_image=images->previous; SetGeometry(smush_image,&left_geometry); GravityAdjustGeometry(left_image->columns,left_image->rows, left_image->gravity,&left_geometry); gap=right_image->columns; left_view=AcquireVirtualCacheView(left_image,exception); right_view=AcquireVirtualCacheView(right_image,exception); for (y=0; y < (ssize_t) smush_image->rows; y++) { for (x=(ssize_t) left_image->columns-1; x > 0; x--) { p=GetCacheViewVirtualPixels(left_view,x,left_geometry.y+y,1,1,exception); if ((p == (const Quantum *) NULL) || (GetPixelAlpha(left_image,p) != TransparentAlpha) || ((left_image->columns-x-1) >= gap)) break; } i=(ssize_t) left_image->columns-x-1; for (x=0; x < (ssize_t) right_image->columns; x++) { p=GetCacheViewVirtualPixels(right_view,x,right_geometry.y+y,1,1, exception); if ((p == (const Quantum *) NULL) || (GetPixelAlpha(right_image,p) != TransparentAlpha) || ((x+i) >= (ssize_t) gap)) break; } if ((x+i) < (ssize_t) gap) gap=(size_t) (x+i); } right_view=DestroyCacheView(right_view); left_view=DestroyCacheView(left_view); if (y < (ssize_t) smush_image->rows) return(offset); return((ssize_t) gap-offset); } static ssize_t SmushYGap(const Image *smush_image,const Image *images, const ssize_t offset,ExceptionInfo *exception) { CacheView *bottom_view, *top_view; const Image *bottom_image, *top_image; RectangleInfo bottom_geometry, top_geometry; register const Quantum *p; register ssize_t i, x; size_t gap; ssize_t y; if (images->previous == (Image *) NULL) return(0); bottom_image=images; SetGeometry(smush_image,&bottom_geometry); GravityAdjustGeometry(bottom_image->columns,bottom_image->rows, bottom_image->gravity,&bottom_geometry); top_image=images->previous; SetGeometry(smush_image,&top_geometry); GravityAdjustGeometry(top_image->columns,top_image->rows,top_image->gravity, &top_geometry); gap=bottom_image->rows; top_view=AcquireVirtualCacheView(top_image,exception); bottom_view=AcquireVirtualCacheView(bottom_image,exception); for (x=0; x < (ssize_t) smush_image->columns; x++) { for (y=(ssize_t) top_image->rows-1; y > 0; y--) { p=GetCacheViewVirtualPixels(top_view,top_geometry.x+x,y,1,1,exception); if ((p == (const Quantum *) NULL) || (GetPixelAlpha(top_image,p) != TransparentAlpha) || ((top_image->rows-y-1) >= gap)) break; } i=(ssize_t) top_image->rows-y-1; for (y=0; y < (ssize_t) bottom_image->rows; y++) { p=GetCacheViewVirtualPixels(bottom_view,bottom_geometry.x+x,y,1,1, exception); if ((p == (const Quantum *) NULL) || (GetPixelAlpha(bottom_image,p) != TransparentAlpha) || ((y+i) >= (ssize_t) gap)) break; } if ((y+i) < (ssize_t) gap) gap=(size_t) (y+i); } bottom_view=DestroyCacheView(bottom_view); top_view=DestroyCacheView(top_view); if (x < (ssize_t) smush_image->columns) return(offset); return((ssize_t) gap-offset); } MagickExport Image *SmushImages(const Image *images, const MagickBooleanType stack,const ssize_t offset,ExceptionInfo *exception) { #define SmushImageTag "Smush/Image" const Image *image; Image *smush_image; MagickBooleanType proceed, status; MagickOffsetType n; PixelTrait alpha_trait; RectangleInfo geometry; register const Image *next; size_t height, number_images, width; ssize_t x_offset, y_offset; /* Compute maximum area of smushed area. */ assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=images; alpha_trait=image->alpha_trait; number_images=1; width=image->columns; height=image->rows; next=GetNextImageInList(image); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { if (next->alpha_trait != UndefinedPixelTrait) alpha_trait=BlendPixelTrait; number_images++; if (stack != MagickFalse) { if (next->columns > width) width=next->columns; height+=next->rows; if (next->previous != (Image *) NULL) height+=offset; continue; } width+=next->columns; if (next->previous != (Image *) NULL) width+=offset; if (next->rows > height) height=next->rows; } /* Smush images. */ smush_image=CloneImage(image,width,height,MagickTrue,exception); if (smush_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(smush_image,DirectClass,exception) == MagickFalse) { smush_image=DestroyImage(smush_image); return((Image *) NULL); } smush_image->alpha_trait=alpha_trait; (void) SetImageBackgroundColor(smush_image,exception); status=MagickTrue; x_offset=0; y_offset=0; for (n=0; n < (MagickOffsetType) number_images; n++) { SetGeometry(smush_image,&geometry); GravityAdjustGeometry(image->columns,image->rows,image->gravity,&geometry); if (stack != MagickFalse) { x_offset-=geometry.x; y_offset-=SmushYGap(smush_image,image,offset,exception); } else { x_offset-=SmushXGap(smush_image,image,offset,exception); y_offset-=geometry.y; } status=CompositeImage(smush_image,image,OverCompositeOp,MagickTrue,x_offset, y_offset,exception); proceed=SetImageProgress(image,SmushImageTag,n,number_images); if (proceed == MagickFalse) break; if (stack == MagickFalse) { x_offset+=(ssize_t) image->columns; y_offset=0; } else { x_offset=0; y_offset+=(ssize_t) image->rows; } image=GetNextImageInList(image); } if (stack == MagickFalse) smush_image->columns=(size_t) x_offset; else smush_image->rows=(size_t) y_offset; if (status == MagickFalse) smush_image=DestroyImage(smush_image); return(smush_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t r i p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StripImage() strips an image of all profiles and comments. % % The format of the StripImage method is: % % MagickBooleanType StripImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType StripImage(Image *image,ExceptionInfo *exception) { MagickBooleanType status; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); (void) exception; DestroyImageProfiles(image); (void) DeleteImageProperty(image,"comment"); (void) DeleteImageProperty(image,"date:create"); (void) DeleteImageProperty(image,"date:modify"); status=SetImageArtifact(image,"png:exclude-chunk", "bKGD,caNv,cHRM,eXIf,gAMA,iCCP,iTXt,pHYs,sRGB,tEXt,zCCP,zTXt,date"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImage() initializes the red, green, and blue intensities of each pixel % as defined by the colormap index. % % The format of the SyncImage method is: % % MagickBooleanType SyncImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static inline Quantum PushColormapIndex(Image *image,const Quantum index, MagickBooleanType *range_exception) { if ((size_t) index < image->colors) return(index); *range_exception=MagickTrue; return((Quantum) 0); } MagickExport MagickBooleanType SyncImage(Image *image,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType range_exception, status, taint; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (image->ping != MagickFalse) return(MagickTrue); if (image->storage_class != PseudoClass) return(MagickFalse); assert(image->colormap != (PixelInfo *) NULL); range_exception=MagickFalse; status=MagickTrue; taint=image->taint; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(range_exception,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum index; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { index=PushColormapIndex(image,GetPixelIndex(image,q),&range_exception); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); image->taint=taint; if ((image->ping == MagickFalse) && (range_exception != MagickFalse)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"InvalidColormapIndex","`%s'",image->filename); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c I m a g e S e t t i n g s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImageSettings() syncs any image_info global options into per-image % attributes. % % Note: in IMv6 free form 'options' were always mapped into 'artifacts', so % that operations and coders can find such settings. In IMv7 if a desired % per-image artifact is not set, then it will directly look for a global % option as a fallback, as such this copy is no longer needed, only the % link set up. % % The format of the SyncImageSettings method is: % % MagickBooleanType SyncImageSettings(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % MagickBooleanType SyncImagesSettings(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SyncImagesSettings(ImageInfo *image_info, Image *images,ExceptionInfo *exception) { Image *image; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); image=images; for ( ; image != (Image *) NULL; image=GetNextImageInList(image)) (void) SyncImageSettings(image_info,image,exception); (void) DeleteImageOption(image_info,"page"); return(MagickTrue); } MagickExport MagickBooleanType SyncImageSettings(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const char *option; GeometryInfo geometry_info; MagickStatusType flags; ResolutionType units; /* Sync image options. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); option=GetImageOption(image_info,"background"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&image->background_color, exception); option=GetImageOption(image_info,"black-point-compensation"); if (option != (const char *) NULL) image->black_point_compensation=(MagickBooleanType) ParseCommandOption( MagickBooleanOptions,MagickFalse,option); option=GetImageOption(image_info,"blue-primary"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.blue_primary.x=geometry_info.rho; image->chromaticity.blue_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.blue_primary.y=image->chromaticity.blue_primary.x; } option=GetImageOption(image_info,"bordercolor"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&image->border_color, exception); /* FUTURE: do not sync compose to per-image compose setting here */ option=GetImageOption(image_info,"compose"); if (option != (const char *) NULL) image->compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions, MagickFalse,option); /* -- */ option=GetImageOption(image_info,"compress"); if (option != (const char *) NULL) image->compression=(CompressionType) ParseCommandOption( MagickCompressOptions,MagickFalse,option); option=GetImageOption(image_info,"debug"); if (option != (const char *) NULL) image->debug=(MagickBooleanType) ParseCommandOption(MagickBooleanOptions, MagickFalse,option); option=GetImageOption(image_info,"density"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; } option=GetImageOption(image_info,"depth"); if (option != (const char *) NULL) image->depth=StringToUnsignedLong(option); option=GetImageOption(image_info,"endian"); if (option != (const char *) NULL) image->endian=(EndianType) ParseCommandOption(MagickEndianOptions, MagickFalse,option); option=GetImageOption(image_info,"filter"); if (option != (const char *) NULL) image->filter=(FilterType) ParseCommandOption(MagickFilterOptions, MagickFalse,option); option=GetImageOption(image_info,"fuzz"); if (option != (const char *) NULL) image->fuzz=StringToDoubleInterval(option,(double) QuantumRange+1.0); option=GetImageOption(image_info,"gravity"); if (option != (const char *) NULL) image->gravity=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,option); option=GetImageOption(image_info,"green-primary"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.green_primary.x=geometry_info.rho; image->chromaticity.green_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.green_primary.y=image->chromaticity.green_primary.x; } option=GetImageOption(image_info,"intent"); if (option != (const char *) NULL) image->rendering_intent=(RenderingIntent) ParseCommandOption( MagickIntentOptions,MagickFalse,option); option=GetImageOption(image_info,"intensity"); if (option != (const char *) NULL) image->intensity=(PixelIntensityMethod) ParseCommandOption( MagickPixelIntensityOptions,MagickFalse,option); option=GetImageOption(image_info,"interlace"); if (option != (const char *) NULL) image->interlace=(InterlaceType) ParseCommandOption(MagickInterlaceOptions, MagickFalse,option); option=GetImageOption(image_info,"interpolate"); if (option != (const char *) NULL) image->interpolate=(PixelInterpolateMethod) ParseCommandOption( MagickInterpolateOptions,MagickFalse,option); option=GetImageOption(image_info,"loop"); if (option != (const char *) NULL) image->iterations=StringToUnsignedLong(option); option=GetImageOption(image_info,"mattecolor"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&image->matte_color, exception); option=GetImageOption(image_info,"orient"); if (option != (const char *) NULL) image->orientation=(OrientationType) ParseCommandOption( MagickOrientationOptions,MagickFalse,option); option=GetImageOption(image_info,"page"); if (option != (const char *) NULL) { char *geometry; geometry=GetPageGeometry(option); flags=ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); } option=GetImageOption(image_info,"quality"); if (option != (const char *) NULL) image->quality=StringToUnsignedLong(option); option=GetImageOption(image_info,"red-primary"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.red_primary.x=geometry_info.rho; image->chromaticity.red_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.red_primary.y=image->chromaticity.red_primary.x; } if (image_info->quality != UndefinedCompressionQuality) image->quality=image_info->quality; option=GetImageOption(image_info,"scene"); if (option != (const char *) NULL) image->scene=StringToUnsignedLong(option); option=GetImageOption(image_info,"taint"); if (option != (const char *) NULL) image->taint=(MagickBooleanType) ParseCommandOption(MagickBooleanOptions, MagickFalse,option); option=GetImageOption(image_info,"tile-offset"); if (option != (const char *) NULL) { char *geometry; geometry=GetPageGeometry(option); flags=ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); } option=GetImageOption(image_info,"transparent-color"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&image->transparent_color, exception); option=GetImageOption(image_info,"type"); if (option != (const char *) NULL) image->type=(ImageType) ParseCommandOption(MagickTypeOptions,MagickFalse, option); option=GetImageOption(image_info,"units"); units=image_info->units; if (option != (const char *) NULL) units=(ResolutionType) ParseCommandOption(MagickResolutionOptions, MagickFalse,option); if (units != UndefinedResolution) { if (image->units != units) switch (image->units) { case PixelsPerInchResolution: { if (units == PixelsPerCentimeterResolution) { image->resolution.x/=2.54; image->resolution.y/=2.54; } break; } case PixelsPerCentimeterResolution: { if (units == PixelsPerInchResolution) { image->resolution.x=(double) ((size_t) (100.0*2.54* image->resolution.x+0.5))/100.0; image->resolution.y=(double) ((size_t) (100.0*2.54* image->resolution.y+0.5))/100.0; } break; } default: break; } image->units=units; } option=GetImageOption(image_info,"virtual-pixel"); if (option != (const char *) NULL) (void) SetImageVirtualPixelMethod(image,(VirtualPixelMethod) ParseCommandOption(MagickVirtualPixelOptions,MagickFalse,option), exception); option=GetImageOption(image_info,"white-point"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.white_point.x=geometry_info.rho; image->chromaticity.white_point.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.white_point.y=image->chromaticity.white_point.x; } /* Pointer to allow the lookup of pre-image artifact will fallback to a global option setting/define. This saves a lot of duplication of global options into per-image artifacts, while ensuring only specifically set per-image artifacts are preserved when parenthesis ends. */ if (image->image_info != (ImageInfo *) NULL) image->image_info=DestroyImageInfo(image->image_info); image->image_info=CloneImageInfo(image_info); return(MagickTrue); }
sum_parallel.c
#include <stdio.h> #include <stdlib.h> #include <omp.h> int main() { double sum = 0; int width = 40000000; #pragma omp parallel for simd reduction(+:sum) for(int i = 0; i < width; i++) { sum += i; } printf("\nSum = %lf\n",sum); }
GB_unop__log1p_fp32_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__log1p_fp32_fp32) // op(A') function: GB (_unop_tran__log1p_fp32_fp32) // C type: float // A type: float // cast: float cij = aij // unaryop: cij = log1pf (aij) #define GB_ATYPE \ float #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = log1pf (x) ; // casting #define GB_CAST(z, aij) \ float z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ float z = aij ; \ Cx [pC] = log1pf (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LOG1P || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__log1p_fp32_fp32) ( float *Cx, // Cx and Ax may be aliased const float *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; float z = aij ; Cx [p] = log1pf (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; float aij = Ax [p] ; float z = aij ; Cx [p] = log1pf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__log1p_fp32_fp32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
CSRPlus.c
// --------------------------------------------------------------- // @brief : CSRPlus matrix implementation file // @author : Hua Huang <huangh223@gatech.edu> // Edmond Chow <echow@cc.gatech.edu> // // Copyright (c) 2017-2020 Georgia Institute of Technology // ---------------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <omp.h> #include "CSRPlus.h" static void qsort_int_dbl_pair(int *key, double *val, int l, int r) { int i = l, j = r, tmp_key; int mid_key = key[(l + r) / 2]; double tmp_val; while (i <= j) { while (key[i] < mid_key) i++; while (key[j] > mid_key) j--; if (i <= j) { tmp_key = key[i]; key[i] = key[j]; key[j] = tmp_key; tmp_val = val[i]; val[i] = val[j]; val[j] = tmp_val; i++; j--; } } if (i < r) qsort_int_dbl_pair(key, val, i, r); if (j > l) qsort_int_dbl_pair(key, val, l, j); } // Initialize a CSRP_mat structure using a COO matrix void CSRP_init_with_COO_mat( const int nrow, const int ncol, const int nnz, const int *row, const int *col, const double *val, CSRP_mat_p *csrp_mat_ ) { CSRP_mat_p csrp_mat = (CSRP_mat_p) malloc(sizeof(CSRP_mat_s)); csrp_mat->nrow = nrow; csrp_mat->ncol = ncol; csrp_mat->nnz = nnz; csrp_mat->row_ptr = (int*) malloc(sizeof(int) * (nrow + 1)); csrp_mat->col = (int*) malloc(sizeof(int) * nnz); csrp_mat->val = (double*) malloc(sizeof(double) * nnz); assert(csrp_mat->row_ptr != NULL); assert(csrp_mat->col != NULL); assert(csrp_mat->val != NULL); csrp_mat->nnz_spos = NULL; csrp_mat->nnz_epos = NULL; csrp_mat->first_row = NULL; csrp_mat->last_row = NULL; csrp_mat->fr_intact = NULL; csrp_mat->lr_intact = NULL; csrp_mat->fr_res = NULL; csrp_mat->lr_res = NULL; int *row_ptr = csrp_mat->row_ptr; int *col_ = csrp_mat->col; double *val_ = csrp_mat->val; memset(row_ptr, 0, sizeof(int) * (nrow + 1)); // Get the number of non-zeros in each row for (int i = 0; i < nnz; i++) row_ptr[row[i] + 1]++; // Calculate the displacement of 1st non-zero in each row for (int i = 2; i <= nrow; i++) row_ptr[i] += row_ptr[i - 1]; // Use row_ptr to bucket sort col[] and val[] for (int i = 0; i < nnz; i++) { int idx = row_ptr[row[i]]; col_[idx] = col[i]; val_[idx] = val[i]; row_ptr[row[i]]++; } // Reset row_ptr for (int i = nrow; i >= 1; i--) row_ptr[i] = row_ptr[i - 1]; row_ptr[0] = 0; // Sort the non-zeros in each row according to column indices #pragma omp parallel for for (int i = 0; i < nrow; i++) qsort_int_dbl_pair(col_, val_, row_ptr[i], row_ptr[i + 1] - 1); *csrp_mat_ = csrp_mat; } // Free a CSRP_mat structure void CSRP_free(CSRP_mat_p *csrp_mat_) { CSRP_mat_p csrp_mat = *csrp_mat_; if (csrp_mat == NULL) return; free(csrp_mat->row_ptr); free(csrp_mat->col); free(csrp_mat->val); free(csrp_mat->nnz_spos); free(csrp_mat->nnz_epos); free(csrp_mat->first_row); free(csrp_mat->last_row); free(csrp_mat->fr_intact); free(csrp_mat->lr_intact); free(csrp_mat->fr_res); free(csrp_mat->lr_res); *csrp_mat_ = NULL; } static void partition_block_equal(const int len, const int nblk, int *displs) { int bs0 = len / nblk; int rem = len % nblk; int bs1 = (rem > 0) ? bs0 + 1 : bs0; displs[0] = 0; for (int i = 0; i < rem; i++) displs[i + 1] = displs[i] + bs1; for (int i = rem; i < nblk; i++) displs[i + 1] = displs[i] + bs0; } static int calc_lower_bound(const int *a, int n, int x) { int l = 0, h = n; while (l < h) { int mid = l + (h - l) / 2; if (x <= a[mid]) h = mid; else l = mid + 1; } return l; } // Partition a CSR matrix into multiple blocks with the same nnz // for multiple threads execution of SpMV void CSRP_partition_multithread(CSRP_mat_p csrp_mat, const int nblk, const int nthread) { csrp_mat->nblk = nblk; csrp_mat->nthread = nthread; csrp_mat->nnz_spos = (int*) malloc(sizeof(int) * nblk); csrp_mat->nnz_epos = (int*) malloc(sizeof(int) * nblk); csrp_mat->first_row = (int*) malloc(sizeof(int) * nblk); csrp_mat->last_row = (int*) malloc(sizeof(int) * nblk); csrp_mat->fr_intact = (int*) malloc(sizeof(int) * nblk); csrp_mat->lr_intact = (int*) malloc(sizeof(int) * nblk); csrp_mat->fr_res = (double*) malloc(sizeof(double) * nblk); csrp_mat->lr_res = (double*) malloc(sizeof(double) * nblk); assert(csrp_mat->nnz_spos != NULL); assert(csrp_mat->nnz_epos != NULL); assert(csrp_mat->first_row != NULL); assert(csrp_mat->last_row != NULL); assert(csrp_mat->fr_intact != NULL); assert(csrp_mat->lr_intact != NULL); assert(csrp_mat->fr_res != NULL); assert(csrp_mat->lr_res != NULL); int nnz = csrp_mat->nnz; int nrow = csrp_mat->nrow; int *row_ptr = csrp_mat->row_ptr; int *nnz_displs = (int *) malloc((nblk + 1) * sizeof(int)); partition_block_equal(nnz, nblk, nnz_displs); for (int iblk = 0; iblk < nblk; iblk++) { int iblk_nnz_spos = nnz_displs[iblk]; int iblk_nnz_epos = nnz_displs[iblk + 1] - 1; int spos_in_row = calc_lower_bound(row_ptr, nrow + 1, iblk_nnz_spos); int epos_in_row = calc_lower_bound(row_ptr, nrow + 1, iblk_nnz_epos); if (row_ptr[spos_in_row] > iblk_nnz_spos) spos_in_row--; if (row_ptr[epos_in_row] > iblk_nnz_epos) epos_in_row--; // Note: It is possible that the last nnz is the first nnz in a row, // and there are some empty rows between the last row and previous non-empty row while (row_ptr[epos_in_row] == row_ptr[epos_in_row + 1]) epos_in_row++; csrp_mat->nnz_spos[iblk] = iblk_nnz_spos; csrp_mat->nnz_epos[iblk] = iblk_nnz_epos; csrp_mat->first_row[iblk] = spos_in_row; csrp_mat->last_row[iblk] = epos_in_row; if ((epos_in_row - spos_in_row) >= 1) { int fr_intact = (iblk_nnz_spos == row_ptr[spos_in_row]); int lr_intact = (iblk_nnz_epos == row_ptr[epos_in_row + 1] - 1); csrp_mat->fr_intact[iblk] = fr_intact; csrp_mat->lr_intact[iblk] = lr_intact; } else { // Mark that this thread only handles a segment of a row csrp_mat->fr_intact[iblk] = 0; csrp_mat->lr_intact[iblk] = -1; } } csrp_mat->last_row[nblk - 1] = nrow - 1; csrp_mat->nnz_epos[nblk - 1] = row_ptr[nrow] - 1; free(nnz_displs); } // Use Use first-touch policy to optimize the storage of CSR arrays in a CSRP_mat structure void CSRP_optimize_NUMA(CSRP_mat_p csrp_mat) { int nnz = csrp_mat->nnz; int nrow = csrp_mat->nrow; int nblk = csrp_mat->nblk; int nthread = csrp_mat->nthread; int *row_ptr = (int*) malloc(sizeof(int) * (nrow + 1)); int *col = (int*) malloc(sizeof(int) * nnz); double *val = (double*) malloc(sizeof(double) * nnz); assert(row_ptr != NULL); assert(col != NULL); assert(val != NULL); #pragma omp parallel num_threads(nthread) { #pragma omp for schedule(static) for (int i = 0; i < nrow + 1; i++) row_ptr[i] = csrp_mat->row_ptr[i]; #pragma omp for schedule(static) for (int iblk = 0; iblk < nblk; iblk++) { int nnz_spos = csrp_mat->nnz_spos[iblk]; int nnz_epos = csrp_mat->nnz_epos[iblk]; for (int i = nnz_spos; i <= nnz_epos; i++) { col[i] = csrp_mat->col[i]; val[i] = csrp_mat->val[i]; } } } free(csrp_mat->row_ptr); free(csrp_mat->col); free(csrp_mat->val); csrp_mat->row_ptr = row_ptr; csrp_mat->col = col; csrp_mat->val = val; } static double CSR_SpMV_row_seg( const int seg_len, const int *__restrict col, const double *__restrict val, const double *__restrict x ) { register double res = 0.0; #pragma omp simd for (int idx = 0; idx < seg_len; idx++) res += val[idx] * x[col[idx]]; return res; } static void CSR_SpMV_row_block( const int srow, const int erow, const int *row_ptr, const int *col, const double *val, const double *__restrict x, double *__restrict y ) { for (int irow = srow; irow < erow; irow++) { register double res = 0.0; #pragma omp simd for (int idx = row_ptr[irow]; idx < row_ptr[irow + 1]; idx++) res += val[idx] * x[col[idx]]; y[irow] = res; } } static void CSRP_SpMV_block(CSRP_mat_p csrp_mat, const int iblk, const double *x, double *y) { int *row_ptr = csrp_mat->row_ptr; int *col = csrp_mat->col; int *first_row = csrp_mat->first_row; int *last_row = csrp_mat->last_row; int *nnz_spos = csrp_mat->nnz_spos; int *nnz_epos = csrp_mat->nnz_epos; int *fr_intact = csrp_mat->fr_intact; int *lr_intact = csrp_mat->lr_intact; double *val = csrp_mat->val; double *fr_res = csrp_mat->fr_res; double *lr_res = csrp_mat->lr_res; if (first_row[iblk] == last_row[iblk]) { // This thread handles a segment on 1 row int iblk_nnz_spos = nnz_spos[iblk]; int iblk_nnz_epos = nnz_epos[iblk]; int iblk_seg_len = iblk_nnz_epos - iblk_nnz_spos + 1; fr_res[iblk] = CSR_SpMV_row_seg(iblk_seg_len, col + iblk_nnz_spos, val + iblk_nnz_spos, x); lr_res[iblk] = 0.0; y[first_row[iblk]] = 0.0; } else { // This thread handles segments on multiple rows int first_intact_row = first_row[iblk]; int last_intact_row = last_row[iblk]; if (fr_intact[iblk] == 0) { int iblk_nnz_spos = nnz_spos[iblk]; int iblk_nnz_epos = row_ptr[first_intact_row + 1]; int iblk_seg_len = iblk_nnz_epos - iblk_nnz_spos; fr_res[iblk] = CSR_SpMV_row_seg(iblk_seg_len, col + iblk_nnz_spos, val + iblk_nnz_spos, x); y[first_intact_row] = 0.0; first_intact_row++; } if (lr_intact[iblk] == 0) { int iblk_nnz_spos = row_ptr[last_intact_row]; int iblk_nnz_epos = nnz_epos[iblk]; int iblk_seg_len = iblk_nnz_epos - iblk_nnz_spos + 1; lr_res[iblk] = CSR_SpMV_row_seg(iblk_seg_len, col + iblk_nnz_spos, val + iblk_nnz_spos, x); y[last_intact_row] = 0.0; last_intact_row--; } CSR_SpMV_row_block( first_intact_row, last_intact_row + 1, row_ptr, col, val, x, y ); } } // Perform OpenMP parallelized CSR SpMV with a CSRP_mat structure void CSRP_SpMV(CSRP_mat_p csrp_mat, const double *x, double *y) { int nblk = csrp_mat->nblk; int nthread = csrp_mat->nthread; #pragma omp parallel for schedule(static) num_threads(nthread) for (int iblk = 0; iblk < nblk; iblk++) CSRP_SpMV_block(csrp_mat, iblk, x, y); for (int iblk = 0; iblk < nblk; iblk++) { if (csrp_mat->fr_intact[iblk] == 0) { int first_row = csrp_mat->first_row[iblk]; y[first_row] += csrp_mat->fr_res[iblk]; } if (csrp_mat->lr_intact[iblk] == 0) { int last_row = csrp_mat->last_row[iblk]; y[last_row] += csrp_mat->lr_res[iblk]; } } }
util.h
#include <math.h> #include <iostream> #include <omp.h> //------------------------------------------------------------------- //--initialize array with maximum limit //------------------------------------------------------------------- template<typename datatype> void fill(datatype *A, const int n, const datatype maxi){ for (int j = 0; j < n; j++) { A[j] = ((datatype) maxi * (rand() / (RAND_MAX + 1.0f))); } } //--print matrix template<typename datatype> void print_matrix(datatype *A, int height, int width){ for(int i=0; i<height; i++){ for(int j=0; j<width; j++){ int idx = i*width + j; std::cout<<A[idx]<<" "; } std::cout<<std::endl; } return; } //------------------------------------------------------------------- //--verify results //------------------------------------------------------------------- #define MAX_RELATIVE_ERROR .002 template<typename datatype> void verify_array(const datatype *cpuResults, const datatype *gpuResults, const int size){ char passed = true; #pragma omp parallel for for (int i=0; i<size; i++){ if (fabs(cpuResults[i] - gpuResults[i]) / cpuResults[i] > MAX_RELATIVE_ERROR){ passed = false; } } if (passed){ std::cout << "--cambine:passed:-)" << std::endl; } else{ std::cout << "--cambine: failed:-(" << std::endl; } return ; } template<typename datatype> void compare_results(const datatype *cpu_results, const datatype *gpu_results, const int size){ char passed = true; //#pragma omp parallel for for (int i=0; i<size; i++){ if (cpu_results[i]!=gpu_results[i]){ passed = false; } } if (passed){ std::cout << "--cambine:passed:-)" << std::endl; } else{ std::cout << "--cambine: failed:-(" << std::endl; } return ; }
CC.h
/****************************************************************/ /* Parallel Combinatorial BLAS Library (for Graph Computations) */ /* version 1.6 -------------------------------------------------*/ /* date: 6/15/2017 ---------------------------------------------*/ /* authors: Ariful Azad, Aydin Buluc --------------------------*/ /****************************************************************/ /* Copyright (c) 2010-2017, The Regents of the University of California 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 <mpi.h> // These macros should be defined before stdint.h is included #ifndef __STDC_CONSTANT_MACROS #define __STDC_CONSTANT_MACROS #endif #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS #endif #include <stdint.h> #include <sys/time.h> #include <iostream> #include <fstream> #include <string> #include <sstream> #include <ctime> #include <cmath> #include "CombBLAS/CombBLAS.h" //#define CC_TIMING 1 #define NONSTAR 0 #define STAR 1 #define CONVERGED 2 using namespace std; /** ** Connected components based on Awerbuch-Shiloach algorithm **/ namespace combblas { template <typename T1, typename T2> struct Select2ndMinSR { typedef typename promote_trait<T1,T2>::T_promote T_promote; static T_promote id(){ return std::numeric_limits<T_promote>::max(); }; static bool returnedSAID() { return false; } static MPI_Op mpi_op() { return MPI_MIN; }; static T_promote add(const T_promote & arg1, const T_promote & arg2) { return std::min(arg1, arg2); } static T_promote multiply(const T1 & arg1, const T2 & arg2) { return static_cast<T_promote> (arg2); } static void axpy(const T1 a, const T2 & x, T_promote & y) { y = add(y, multiply(a, x)); } }; template <class T, class I> void omp_par_scan(T* A, T* B,I cnt) { int p=omp_get_max_threads(); if(cnt<100*p){ for(I i=1;i<cnt;i++) B[i]=B[i-1]+A[i-1]; return; } I step_size=cnt/p; #pragma omp parallel for for(int i=0; i<p; i++){ int start=i*step_size; int end=start+step_size; if(i==p-1) end=cnt; if(i!=0)B[start]=0; for(I j=start+1; j<end; j++) B[j]=B[j-1]+A[j-1]; } T* sum=new T[p]; sum[0]=0; for(int i=1;i<p;i++) sum[i]=sum[i-1]+B[i*step_size-1]+A[i*step_size-1]; #pragma omp parallel for for(int i=1; i<p; i++){ int start=i*step_size; int end=start+step_size; if(i==p-1) end=cnt; T sum_=sum[i]; for(I j=start; j<end; j++) B[j]+=sum_; } delete[] sum; } // copied from usort so that we can select k // an increased value of k reduces the bandwidth cost, but increases the latency cost // this does not work when p is not power of two and a processor is not sending data, template <typename T> int Mpi_Alltoallv_kway(T* sbuff_, int* s_cnt_, int* sdisp_, T* rbuff_, int* r_cnt_, int* rdisp_, MPI_Comm c, int kway=2) { int np, pid; MPI_Comm_size(c, &np); MPI_Comm_rank(c, &pid); if(np==1 || kway==1) { return MPI_Alltoallv(sbuff_, s_cnt_, sdisp_, MPIType<T>(), rbuff_, r_cnt_, rdisp_, MPIType<T>(), c); } int range[2]={0,np}; std::vector<int> s_cnt(np); #pragma omp parallel for for(int i=0;i<np;i++){ s_cnt[i]=s_cnt_[i]*sizeof(T)+2*sizeof(int); } std::vector<int> sdisp(np); sdisp[0]=0; omp_par_scan(&s_cnt[0],&sdisp[0],np); char* sbuff=new char[sdisp[np-1]+s_cnt[np-1]]; #pragma omp parallel for for(int i=0;i<np;i++){ ((int*)&sbuff[sdisp[i]])[0]=s_cnt[i]; ((int*)&sbuff[sdisp[i]])[1]=pid; memcpy(&sbuff[sdisp[i]]+2*sizeof(int),&sbuff_[sdisp_[i]],s_cnt[i]-2*sizeof(int)); } //int t_indx=0; int iter_cnt=0; while(range[1]-range[0]>1){ iter_cnt++; if(kway>range[1]-range[0]) kway=range[1]-range[0]; std::vector<int> new_range(kway+1); for(int i=0;i<=kway;i++) new_range[i]=(range[0]*(kway-i)+range[1]*i)/kway; int p_class=(std::upper_bound(&new_range[0],&new_range[kway],pid)-&new_range[0]-1); int new_np=new_range[p_class+1]-new_range[p_class]; int new_pid=pid-new_range[p_class]; //Communication. { std::vector<int> r_cnt (new_np*kway, 0); std::vector<int> r_cnt_ext(new_np*kway, 0); //Exchange send sizes. for(int i=0;i<kway;i++){ MPI_Status status; int cmp_np=new_range[i+1]-new_range[i]; int partner=(new_pid<cmp_np? new_range[i]+new_pid: new_range[i+1]-1) ; assert( (new_pid<cmp_np? true: new_range[i]+new_pid==new_range[i+1] )); //Remove this. MPI_Sendrecv(&s_cnt[new_range[i]-new_range[0]], cmp_np, MPI_INT, partner, 0, &r_cnt[new_np *i ], new_np, MPI_INT, partner, 0, c, &status); //Handle extra communication. if(new_pid==new_np-1 && cmp_np>new_np){ int partner=new_range[i+1]-1; std::vector<int> s_cnt_ext(cmp_np, 0); MPI_Sendrecv(&s_cnt_ext[ 0], cmp_np, MPI_INT, partner, 0, &r_cnt_ext[new_np*i], new_np, MPI_INT, partner, 0, c, &status); } } //Allocate receive buffer. std::vector<int> rdisp (new_np*kway, 0); std::vector<int> rdisp_ext(new_np*kway, 0); int rbuff_size, rbuff_size_ext; char *rbuff, *rbuff_ext; { omp_par_scan(&r_cnt [0], &rdisp [0],new_np*kway); omp_par_scan(&r_cnt_ext[0], &rdisp_ext[0],new_np*kway); rbuff_size = rdisp [new_np*kway-1] + r_cnt [new_np*kway-1]; rbuff_size_ext = rdisp_ext[new_np*kway-1] + r_cnt_ext[new_np*kway-1]; rbuff = new char[rbuff_size ]; rbuff_ext = new char[rbuff_size_ext]; } //Sendrecv data. //* int my_block=kway; while(pid<new_range[my_block]) my_block--; // MPI_Barrier(c); for(int i_=0;i_<=kway/2;i_++){ int i1=(my_block+i_)%kway; int i2=(my_block+kway-i_)%kway; for(int j=0;j<(i_==0 || i_==kway/2?1:2);j++){ int i=(i_==0?i1:((j+my_block/i_)%2?i1:i2)); MPI_Status status; int cmp_np=new_range[i+1]-new_range[i]; int partner=(new_pid<cmp_np? new_range[i]+new_pid: new_range[i+1]-1) ; int send_dsp =sdisp[new_range[i ]-new_range[0] ]; int send_dsp_last=sdisp[new_range[i+1]-new_range[0]-1]; int send_cnt =s_cnt[new_range[i+1]-new_range[0]-1]+send_dsp_last-send_dsp; // ttt=omp_get_wtime(); MPI_Sendrecv(&sbuff[send_dsp], send_cnt, MPI_BYTE, partner, 0, &rbuff[rdisp[new_np * i ]], r_cnt[new_np *(i+1)-1]+rdisp[new_np *(i+1)-1]-rdisp[new_np * i ], MPI_BYTE, partner, 0, c, &status); //Handle extra communication. if(pid==new_np-1 && cmp_np>new_np){ int partner=new_range[i+1]-1; std::vector<int> s_cnt_ext(cmp_np, 0); MPI_Sendrecv( NULL, 0, MPI_BYTE, partner, 0, &rbuff[rdisp_ext[new_np*i]], r_cnt_ext[new_np*(i+1)-1]+rdisp_ext[new_np*(i+1)-1]-rdisp_ext[new_np*i], MPI_BYTE, partner, 0, c, &status); } } } //Rearrange received data. { if(sbuff!=NULL) delete[] sbuff; sbuff=new char[rbuff_size+rbuff_size_ext]; std::vector<int> cnt_new(2*new_np*kway, 0); std::vector<int> disp_new(2*new_np*kway, 0); for(int i=0;i<new_np;i++) for(int j=0;j<kway;j++){ cnt_new[(i*2 )*kway+j]=r_cnt [j*new_np+i]; cnt_new[(i*2+1)*kway+j]=r_cnt_ext[j*new_np+i]; } omp_par_scan(&cnt_new[0], &disp_new[0],2*new_np*kway); #pragma omp parallel for for(int i=0;i<new_np;i++) for(int j=0;j<kway;j++){ memcpy(&sbuff[disp_new[(i*2 )*kway+j]], &rbuff [rdisp [j*new_np+i]], r_cnt [j*new_np+i]); memcpy(&sbuff[disp_new[(i*2+1)*kway+j]], &rbuff_ext[rdisp_ext[j*new_np+i]], r_cnt_ext[j*new_np+i]); } //Free memory. if(rbuff !=NULL) delete[] rbuff ; if(rbuff_ext!=NULL) delete[] rbuff_ext; s_cnt.clear(); s_cnt.resize(new_np,0); sdisp.resize(new_np); for(int i=0;i<new_np;i++){ for(int j=0;j<2*kway;j++) s_cnt[i]+=cnt_new[i*2*kway+j]; sdisp[i]=disp_new[i*2*kway]; } } } range[0]=new_range[p_class ]; range[1]=new_range[p_class+1]; } //Copy data to rbuff_. std::vector<char*> buff_ptr(np); char* tmp_ptr=sbuff; for(int i=0;i<np;i++){ int& blk_size=((int*)tmp_ptr)[0]; buff_ptr[i]=tmp_ptr; tmp_ptr+=blk_size; } #pragma omp parallel for for(int i=0;i<np;i++){ int& blk_size=((int*)buff_ptr[i])[0]; int& src_pid=((int*)buff_ptr[i])[1]; assert(blk_size-2*sizeof(int)<=r_cnt_[src_pid]*sizeof(T)); memcpy(&rbuff_[rdisp_[src_pid]],buff_ptr[i]+2*sizeof(int),blk_size-2*sizeof(int)); } //Free memory. if(sbuff !=NULL) delete[] sbuff; return 1; } template <typename T> int Mpi_Alltoallv(T* sbuff, int* s_cnt, int* sdisp, T* rbuff, int* r_cnt, int* rdisp, MPI_Comm comm) { int nprocs, rank; MPI_Comm_size(comm, &nprocs); MPI_Comm_rank(comm, &rank); int commCnt = 0; for(int i = 0; i < nprocs; i++) { if(i==rank) continue; if(s_cnt[i] > 0) commCnt++; if(r_cnt[i] > 0) commCnt++; } int totalCommCnt = 0; MPI_Allreduce(&commCnt, &totalCommCnt, 1, MPI_INT, MPI_SUM, comm); if(totalCommCnt < 2*log2(nprocs)) { return par::Mpi_Alltoallv_sparse(sbuff, s_cnt, sdisp, rbuff, r_cnt, rdisp, comm); } else if((nprocs & (nprocs - 1)) == 0) // processor count is power of 2 { Mpi_Alltoallv_kway(sbuff, s_cnt, sdisp, rbuff, r_cnt, rdisp, comm); } else { return MPI_Alltoallv(sbuff, s_cnt, sdisp, MPIType<T>(), rbuff, r_cnt, rdisp, MPIType<T>(), comm); } return 1; } template <class IT, class NT> int replicate(const FullyDistVec<IT,NT> dense, FullyDistSpVec<IT,IT> ri, vector<vector<NT>> &bcastBuffer) { auto commGrid = dense.getcommgrid(); MPI_Comm World = commGrid->GetWorld(); int nprocs = commGrid->GetSize(); vector<int> sendcnt (nprocs,0); vector<int> recvcnt (nprocs,0); std::vector<IT> rinum = ri.GetLocalNum(); IT riloclen = rinum.size(); for(IT i=0; i < riloclen; ++i) { IT locind; int owner = dense.Owner(rinum[i], locind); sendcnt[owner]++; } MPI_Alltoall(sendcnt.data(), 1, MPI_INT, recvcnt.data(), 1, MPI_INT, World); IT totrecv = std::accumulate(recvcnt.begin(),recvcnt.end(), static_cast<IT>(0)); double broadcast_cost = dense.LocArrSize() * log2(nprocs); // bandwidth cost IT bcastsize = 0; vector<IT> bcastcnt(nprocs,0); int nbcast = 0; if(broadcast_cost < totrecv) { bcastsize = dense.LocArrSize(); } MPI_Allgather(&bcastsize, 1, MPIType<IT>(), bcastcnt.data(), 1, MPIType<IT>(), World); for(int i=0; i<nprocs; i++) { if(bcastcnt[i]>0) nbcast++; } if(nbcast > 0) { MPI_Request* requests = new MPI_Request[nbcast]; assert(requests); MPI_Status* statuses = new MPI_Status[nbcast]; assert(statuses); int ibcast = 0; const NT * arr = dense.GetLocArr(); for(int i=0; i<nprocs; i++) { if(bcastcnt[i]>0) { bcastBuffer[i].resize(bcastcnt[i]); std::copy(arr, arr+bcastcnt[i], bcastBuffer[i].begin()); MPI_Ibcast(bcastBuffer[i].data(), bcastcnt[i], MPIType<NT>(), i, World, &requests[ibcast++]); } } MPI_Waitall(nbcast, requests, statuses); delete [] requests; delete [] statuses; } return nbcast; } // SubRef usign a sparse vector // given a dense vector dv and a sparse vector sv // sv_out[i]=dv[sv[i]] for all nonzero index i in sv // return sv_out // If sv has repeated entries, many processes are requesting same entries of dv from the same processes // (usually from the low rank processes in LACC) // In this case, it may be beneficial to broadcast some entries of dv so that dv[sv[i]] can be obtained locally. // This logic is implemented in this function: replicate(dense, ri, bcastBuffer) template <class IT, class NT> FullyDistSpVec<IT,NT> Extract (const FullyDistVec<IT,NT> dense, FullyDistSpVec<IT,IT> ri) { #ifdef CC_TIMING double ts = MPI_Wtime(); std::ostringstream outs; outs.str(""); outs.clear(); outs<< " Extract timing: "; #endif auto commGrid = ri.getcommgrid(); MPI_Comm World = commGrid->GetWorld(); int nprocs = commGrid->GetSize(); if(!(commGrid == dense.getcommgrid())) { std::cout << "Grids are not comparable for dense vector subsref" << std::endl; return FullyDistSpVec<IT,NT>(); } vector<vector<NT>> bcastBuffer(nprocs); #ifdef CC_TIMING double t1 = MPI_Wtime(); #endif int nbcast = replicate(dense, ri, bcastBuffer); #ifdef CC_TIMING double bcast = MPI_Wtime() - t1; outs << "bcast ( " << nbcast << " ): " << bcast << " "; #endif std::vector< std::vector< IT > > data_req(nprocs); std::vector< std::vector< IT > > revr_map(nprocs); // to put the incoming data to the correct location const NT * arr = dense.GetLocArr(); std::vector<IT> rinum = ri.GetLocalNum(); IT riloclen = rinum.size(); std::vector<NT> num(riloclen); // final output for(IT i=0; i < riloclen; ++i) { IT locind; int owner = dense.Owner(rinum[i], locind); if(bcastBuffer[owner].size() == 0) { data_req[owner].push_back(locind); revr_map[owner].push_back(i); } else { num[i] =bcastBuffer[owner][locind]; } } int * sendcnt = new int[nprocs]; int * sdispls = new int[nprocs]; for(int i=0; i<nprocs; ++i) sendcnt[i] = (int) data_req[i].size(); int * rdispls = new int[nprocs]; int * recvcnt = new int[nprocs]; #ifdef CC_TIMING t1 = MPI_Wtime(); #endif MPI_Alltoall(sendcnt, 1, MPI_INT, recvcnt, 1, MPI_INT, World); // share the request counts #ifdef CC_TIMING double all2ll1 = MPI_Wtime() - t1; outs << "all2ll1: " << all2ll1 << " "; #endif sdispls[0] = 0; rdispls[0] = 0; for(int i=0; i<nprocs-1; ++i) { sdispls[i+1] = sdispls[i] + sendcnt[i]; rdispls[i+1] = rdispls[i] + recvcnt[i]; } IT totsend = std::accumulate(sendcnt,sendcnt+nprocs, static_cast<IT>(0)); IT totrecv = std::accumulate(recvcnt,recvcnt+nprocs, static_cast<IT>(0)); IT * sendbuf = new IT[totsend]; for(int i=0; i<nprocs; ++i) { std::copy(data_req[i].begin(), data_req[i].end(), sendbuf+sdispls[i]); std::vector<IT>().swap(data_req[i]); } IT * reversemap = new IT[totsend]; for(int i=0; i<nprocs; ++i) { std::copy(revr_map[i].begin(), revr_map[i].end(), reversemap+sdispls[i]); // reversemap array is unique std::vector<IT>().swap(revr_map[i]); } IT * recvbuf = new IT[totrecv]; #ifdef CC_TIMING t1 = MPI_Wtime(); #endif Mpi_Alltoallv(sendbuf, sendcnt, sdispls, recvbuf, recvcnt, rdispls, World); #ifdef CC_TIMING double all2ll2 = MPI_Wtime() - t1; outs << "all2ll2: " << all2ll2 << " "; #endif delete [] sendbuf; // access requested data NT * databack = new NT[totrecv]; #ifdef THREADED #pragma omp parallel for #endif for(int i=0; i<totrecv; ++i) databack[i] = arr[recvbuf[i]]; delete [] recvbuf; // communicate requested data NT * databuf = new NT[totsend]; // the response counts are the same as the request counts #ifdef CC_TIMING t1 = MPI_Wtime(); #endif //Mpi_Alltoallv_sparse(databack, recvcnt, rdispls,databuf, sendcnt, sdispls, World); Mpi_Alltoallv(databack, recvcnt, rdispls,databuf, sendcnt, sdispls, World); #ifdef CC_TIMING double all2ll3 = MPI_Wtime() - t1; outs << "all2ll3: " << all2ll3 << " "; #endif // Create the output from databuf for(int i=0; i<totsend; ++i) num[reversemap[i]] = databuf[i]; DeleteAll(rdispls, recvcnt, databack); DeleteAll(sdispls, sendcnt, databuf,reversemap); std::vector<IT> ind = ri.GetLocalInd (); IT globallen = ri.TotalLength(); FullyDistSpVec<IT, NT> indexed(commGrid, globallen, ind, num, true, true); #ifdef CC_TIMING double total = MPI_Wtime() - ts; outs << "others: " << total - (bcast + all2ll1 + all2ll2 + all2ll3) << " "; outs<< endl; SpParHelper::Print(outs.str()); #endif return indexed; } template <class IT, class NT> int ReduceAssign(FullyDistSpVec<IT,IT> & ind, FullyDistSpVec<IT,NT> & val, vector<vector<NT>> &reduceBuffer, NT MAX_FOR_REDUCE) { auto commGrid = ind.getcommgrid(); MPI_Comm World = commGrid->GetWorld(); int nprocs = commGrid->GetSize(); int myrank; MPI_Comm_rank(World,&myrank); vector<int> sendcnt (nprocs,0); vector<int> recvcnt (nprocs); std::vector<std::vector<IT>> indBuf(nprocs); std::vector<std::vector<NT>> valBuf(nprocs); std::vector<IT> indices = ind.GetLocalNum(); std::vector<NT> values = val.GetLocalNum(); IT riloclen = indices.size(); for(IT i=0; i < riloclen; ++i) { IT locind; int owner = ind.Owner(indices[i], locind); indBuf[owner].push_back(locind); valBuf[owner].push_back(values[i]); sendcnt[owner]++; } MPI_Alltoall(sendcnt.data(), 1, MPI_INT, recvcnt.data(), 1, MPI_INT, World); IT totrecv = std::accumulate(recvcnt.begin(),recvcnt.end(), static_cast<IT>(0)); double reduceCost = ind.MyLocLength() * log2(nprocs); // bandwidth cost IT reducesize = 0; vector<IT> reducecnt(nprocs,0); int nreduce = 0; if(reduceCost < totrecv) { reducesize = ind.MyLocLength(); } MPI_Allgather(&reducesize, 1, MPIType<IT>(), reducecnt.data(), 1, MPIType<IT>(), World); for(int i=0; i<nprocs; ++i) { if(reducecnt[i]>0) nreduce++; } if(nreduce > 0) { MPI_Request* requests = new MPI_Request[nreduce]; assert(requests); MPI_Status* statuses = new MPI_Status[nreduce]; assert(statuses); int ireduce = 0; for(int i=0; i<nprocs; ++i) { if(reducecnt[i]>0) { reduceBuffer[i].resize(reducecnt[i], MAX_FOR_REDUCE); // this is specific to LACC for(int j=0; j<sendcnt[i]; j++) reduceBuffer[i][indBuf[i][j]] = std::min(reduceBuffer[i][indBuf[i][j]], valBuf[i][j]); if(myrank==i) MPI_Ireduce(MPI_IN_PLACE, reduceBuffer[i].data(), reducecnt[i], MPIType<NT>(), MPI_MIN, i, World, &requests[ireduce++]); else MPI_Ireduce(reduceBuffer[i].data(), NULL, reducecnt[i], MPIType<NT>(), MPI_MIN, i, World, &requests[ireduce++]); } } MPI_Waitall(nreduce, requests, statuses); //MPI_Barrier(World); delete [] requests; delete [] statuses; } return nreduce; } // for fixed value template <class IT, class NT> int ReduceAssign(FullyDistSpVec<IT,IT> & ind, NT val, vector<vector<NT>> &reduceBuffer, NT MAX_FOR_REDUCE) { auto commGrid = ind.getcommgrid(); MPI_Comm World = commGrid->GetWorld(); int nprocs = commGrid->GetSize(); int myrank; MPI_Comm_rank(World,&myrank); vector<int> sendcnt (nprocs,0); vector<int> recvcnt (nprocs); std::vector<std::vector<IT>> indBuf(nprocs); std::vector<IT> indices = ind.GetLocalNum(); IT riloclen = indices.size(); for(IT i=0; i < riloclen; ++i) { IT locind; int owner = ind.Owner(indices[i], locind); indBuf[owner].push_back(locind); sendcnt[owner]++; } MPI_Alltoall(sendcnt.data(), 1, MPI_INT, recvcnt.data(), 1, MPI_INT, World); IT totrecv = std::accumulate(recvcnt.begin(),recvcnt.end(), static_cast<IT>(0)); double reduceCost = ind.MyLocLength() * log2(nprocs); // bandwidth cost IT reducesize = 0; vector<IT> reducecnt(nprocs,0); int nreduce = 0; if(reduceCost < totrecv) { reducesize = ind.MyLocLength(); } MPI_Allgather(&reducesize, 1, MPIType<IT>(), reducecnt.data(), 1, MPIType<IT>(), World); for(int i=0; i<nprocs; ++i) { if(reducecnt[i]>0) nreduce++; } if(nreduce > 0) { MPI_Request* requests = new MPI_Request[nreduce]; assert(requests); MPI_Status* statuses = new MPI_Status[nreduce]; assert(statuses); int ireduce = 0; for(int i=0; i<nprocs; ++i) { if(reducecnt[i]>0) { reduceBuffer[i].resize(reducecnt[i], MAX_FOR_REDUCE); // this is specific to LACC for(int j=0; j<sendcnt[i]; j++) reduceBuffer[i][indBuf[i][j]] = val; if(myrank==i) MPI_Ireduce(MPI_IN_PLACE, reduceBuffer[i].data(), reducecnt[i], MPIType<NT>(), MPI_MIN, i, World, &requests[ireduce++]); else MPI_Ireduce(reduceBuffer[i].data(), NULL, reducecnt[i], MPIType<NT>(), MPI_MIN, i, World, &requests[ireduce++]); } } MPI_Waitall(nreduce, requests, statuses); //MPI_Barrier(World); delete [] requests; delete [] statuses; } return nreduce; } // given two sparse vectors sv and val // sv_out[sv[i]] = val[i] for all nonzero index i in sv, whre sv_out is the output sparse vector // If sv has repeated entries, a process may receive the same values of sv from different processes // In this case, it may be beneficial to reduce some entries of sv so that sv_out[sv[i]] can be updated locally. // This logic is implemented in this function: ReduceAssign template <class IT, class NT> FullyDistSpVec<IT,NT> Assign (FullyDistSpVec<IT,IT> & ind, FullyDistSpVec<IT,NT> & val) { IT ploclen = ind.getlocnnz(); if(ploclen != val.getlocnnz()) { SpParHelper::Print("Assign error: Index and value vectors have different size !!!\n"); return FullyDistSpVec<IT,NT>(ind.getcommgrid()); } IT globallen = ind.TotalLength(); IT maxInd = ind.Reduce(maximum<IT>(), (IT) 0 ) ; if(maxInd >= globallen) { std::cout << "At least one requested index is larger than the global length" << std::endl; return FullyDistSpVec<IT,NT>(ind.getcommgrid()); } #ifdef CC_TIMING double ts = MPI_Wtime(); std::ostringstream outs; outs.str(""); outs.clear(); outs<< " Assign timing: "; #endif auto commGrid = ind.getcommgrid(); MPI_Comm World = commGrid->GetWorld(); int nprocs = commGrid->GetSize(); int * rdispls = new int[nprocs+1]; int * recvcnt = new int[nprocs]; int * sendcnt = new int[nprocs](); // initialize to 0 int * sdispls = new int[nprocs+1]; vector<vector<NT>> reduceBuffer(nprocs); #ifdef CC_TIMING double t1 = MPI_Wtime(); #endif NT MAX_FOR_REDUCE = static_cast<NT>(globallen); int nreduce = ReduceAssign(ind, val, reduceBuffer, MAX_FOR_REDUCE); #ifdef CC_TIMING double reduce = MPI_Wtime() - t1; outs << "reduce (" << nreduce << "): " << reduce << " "; #endif std::vector<std::vector<IT>> indBuf(nprocs); std::vector<std::vector<NT>> valBuf(nprocs); std::vector<IT> indices = ind.GetLocalNum(); std::vector<NT> values = val.GetLocalNum(); IT riloclen = indices.size(); for(IT i=0; i < riloclen; ++i) { IT locind; int owner = ind.Owner(indices[i], locind); if(reduceBuffer[owner].size() == 0) { indBuf[owner].push_back(locind); valBuf[owner].push_back(values[i]); sendcnt[owner]++; } } #ifdef CC_TIMING t1 = MPI_Wtime(); #endif MPI_Alltoall(sendcnt, 1, MPI_INT, recvcnt, 1, MPI_INT, World); #ifdef CC_TIMING double all2ll1 = MPI_Wtime() - t1; outs << "all2ll1: " << all2ll1 << " "; #endif sdispls[0] = 0; rdispls[0] = 0; for(int i=0; i<nprocs; ++i) { sdispls[i+1] = sdispls[i] + sendcnt[i]; rdispls[i+1] = rdispls[i] + recvcnt[i]; } IT totsend = sdispls[nprocs]; IT totrecv = rdispls[nprocs]; vector<IT> sendInd(totsend); vector<NT> sendVal(totsend); for(int i=0; i<nprocs; ++i) { std::copy(indBuf[i].begin(), indBuf[i].end(), sendInd.begin()+sdispls[i]); std::vector<IT>().swap(indBuf[i]); std::copy(valBuf[i].begin(), valBuf[i].end(), sendVal.begin()+sdispls[i]); std::vector<NT>().swap(valBuf[i]); } vector<IT> recvInd(totrecv); vector<NT> recvVal(totrecv); #ifdef CC_TIMING t1 = MPI_Wtime(); #endif Mpi_Alltoallv(sendInd.data(), sendcnt, sdispls, recvInd.data(), recvcnt, rdispls, World); //MPI_Alltoallv(sendInd.data(), sendcnt, sdispls, MPIType<IT>(), recvInd.data(), recvcnt, rdispls, MPIType<IT>(), World); #ifdef CC_TIMING double all2ll2 = MPI_Wtime() - t1; outs << "all2ll2: " << all2ll2 << " "; #endif #ifdef CC_TIMING t1 = MPI_Wtime(); #endif Mpi_Alltoallv(sendVal.data(), sendcnt, sdispls, recvVal.data(), recvcnt, rdispls, World); #ifdef CC_TIMING double all2ll3 = MPI_Wtime() - t1; outs << "all2ll3: " << all2ll3 << " "; #endif DeleteAll(sdispls, rdispls, sendcnt, recvcnt); int myrank; MPI_Comm_rank(World,&myrank); if(reduceBuffer[myrank].size()>0) { //cout << myrank << " : " << recvInd.size() << endl; for(int i=0; i<reduceBuffer[myrank].size(); i++) { if(reduceBuffer[myrank][i] < MAX_FOR_REDUCE) { recvInd.push_back(i); recvVal.push_back(reduceBuffer[myrank][i]); } } } FullyDistSpVec<IT, NT> indexed(commGrid, globallen, recvInd, recvVal, false, false); #ifdef CC_TIMING double total = MPI_Wtime() - ts; outs << "others: " << total - (reduce + all2ll1 + all2ll2 + all2ll3) << " "; outs<< endl; SpParHelper::Print(outs.str()); #endif return indexed; } // given a sparse vector sv // sv_out[sv[i]] = val for all nonzero index i in sv, whre sv_out is the output sparse vector // If sv has repeated entries, a process may receive the same values of sv from different processes // In this case, it may be beneficial to reduce some entries of sv so that sv_out[sv[i]] can be updated locally. // This logic is implemented in this function: ReduceAssign template <class IT, class NT> FullyDistSpVec<IT,NT> Assign (FullyDistSpVec<IT,IT> & ind, NT val) { IT globallen = ind.TotalLength(); IT maxInd = ind.Reduce(maximum<IT>(), (IT) 0 ) ; if(maxInd >= globallen) { std::cout << "At least one requested index is larger than the global length" << std::endl; return FullyDistSpVec<IT,NT>(ind.getcommgrid()); } #ifdef CC_TIMING double ts = MPI_Wtime(); std::ostringstream outs; outs.str(""); outs.clear(); outs<< " Assign timing: "; #endif auto commGrid = ind.getcommgrid(); MPI_Comm World = commGrid->GetWorld(); int nprocs = commGrid->GetSize(); int * rdispls = new int[nprocs+1]; int * recvcnt = new int[nprocs]; int * sendcnt = new int[nprocs](); // initialize to 0 int * sdispls = new int[nprocs+1]; vector<vector<NT>> reduceBuffer(nprocs); #ifdef CC_TIMING double t1 = MPI_Wtime(); #endif NT MAX_FOR_REDUCE = static_cast<NT>(globallen); int nreduce = ReduceAssign(ind, val, reduceBuffer, MAX_FOR_REDUCE); #ifdef CC_TIMING double reduce = MPI_Wtime() - t1; outs << "reduce ( " << nreduce << " ): " << reduce << " "; #endif std::vector<std::vector<IT>> indBuf(nprocs); std::vector<IT> indices = ind.GetLocalNum(); IT riloclen = indices.size(); for(IT i=0; i < riloclen; ++i) { IT locind; int owner = ind.Owner(indices[i], locind); if(reduceBuffer[owner].size() == 0) { indBuf[owner].push_back(locind); sendcnt[owner]++; } } #ifdef CC_TIMING t1 = MPI_Wtime(); #endif MPI_Alltoall(sendcnt, 1, MPI_INT, recvcnt, 1, MPI_INT, World); #ifdef CC_TIMING double all2ll1 = MPI_Wtime() - t1; outs << "all2ll1: " << all2ll1 << " "; #endif sdispls[0] = 0; rdispls[0] = 0; for(int i=0; i<nprocs; ++i) { sdispls[i+1] = sdispls[i] + sendcnt[i]; rdispls[i+1] = rdispls[i] + recvcnt[i]; } IT totsend = sdispls[nprocs]; IT totrecv = rdispls[nprocs]; vector<IT> sendInd(totsend); for(int i=0; i<nprocs; ++i) { std::copy(indBuf[i].begin(), indBuf[i].end(), sendInd.begin()+sdispls[i]); std::vector<IT>().swap(indBuf[i]); } vector<IT> recvInd(totrecv); #ifdef CC_TIMING t1 = MPI_Wtime(); #endif Mpi_Alltoallv(sendInd.data(), sendcnt, sdispls, recvInd.data(), recvcnt, rdispls, World); //MPI_Alltoallv(sendInd.data(), sendcnt, sdispls, MPIType<IT>(), recvInd.data(), recvcnt, rdispls, MPIType<IT>(), World); #ifdef CC_TIMING double all2ll2 = MPI_Wtime() - t1; outs << "all2ll2: " << all2ll2 << " "; outs << "all2ll3: " << 0 << " "; #endif DeleteAll(sdispls, rdispls, sendcnt, recvcnt); int myrank; MPI_Comm_rank(World,&myrank); vector<NT> recvVal(totrecv); if(reduceBuffer[myrank].size()>0) { //cout << myrank << " : " << recvInd.size() << endl; for(int i=0; i<reduceBuffer[myrank].size(); i++) { if(reduceBuffer[myrank][i] < MAX_FOR_REDUCE) { recvInd.push_back(i); recvVal.push_back(val); } } } FullyDistSpVec<IT, NT> indexed(commGrid, globallen, recvInd, recvVal, false, false); #ifdef CC_TIMING double total = MPI_Wtime() - ts; outs << "others: " << total - (reduce + all2ll1 + all2ll2) << " "; outs<< endl; SpParHelper::Print(outs.str()); #endif return indexed; } // special starcheck after conditional and unconditional hooking template <typename IT, typename NT, typename DER> void StarCheckAfterHooking(const SpParMat<IT,NT,DER> & A, FullyDistVec<IT, IT> & parent, FullyDistVec<IT,short>& star, FullyDistSpVec<IT,IT> condhooks, bool isStar2StarHookPossible) { // hooks are nonstars star.EWiseApply(condhooks, [](short isStar, IT x){return static_cast<short>(NONSTAR);}, false, static_cast<IT>(NONSTAR)); if(isStar2StarHookPossible) { // this is not needed in the first iteration see the complicated proof in the paper // parents of hooks are nonstars // needed only after conditional hooking because in that case star can hook to a star FullyDistSpVec<IT, short> pNonStar= Assign(condhooks, NONSTAR); star.Set(pNonStar); } //star(parent) // If I am a star, I would like to know the star information of my parent // children of hooks and parents of hooks are nonstars // NOTE: they are not needed in the first iteration FullyDistSpVec<IT,short> spStars(star, [](short isStar){return isStar==STAR;}); FullyDistSpVec<IT, IT> parentOfStars = EWiseApply<IT>(spStars, parent, [](short isStar, IT p){return p;}, [](short isStar, IT p){return true;}, false, static_cast<short>(0)); FullyDistSpVec<IT,short> isParentStar = Extract(star, parentOfStars); star.Set(isParentStar); } /* // In iteration 1: "stars" has both vertices belongihg to stars and nonstars (no converged) // we only process nonstars and identify starts from them // After iteration 1: "stars" has vertices belongihg to converged and nonstars (no stars) // we only process nonstars and identify starts from them template <typename IT> void StarCheck(FullyDistVec<IT, IT> & parents, FullyDistVec<IT,short>& stars) { // this is done here so that in the first iteration, we don't process STAR vertices FullyDistSpVec<IT,short> nonStars(stars, [](short isStar){return isStar==NONSTAR;}); // initialize all nonstars to stars stars.Apply([](short isStar){return isStar==NONSTAR? STAR: isStar;}); // identify vertices at level >= 2 (grandchildren of roots) FullyDistSpVec<IT, IT> pOfNonStars = EWiseApply<IT>(nonStars, parents, [](short isStar, IT p){return p;}, [](short isStar, IT p){return true;}, false, static_cast<short>(0)); FullyDistSpVec<IT,IT> gpOfNonStars = Extract(parents, pOfNonStars); FullyDistSpVec<IT,short> keptNonStars = EWiseApply<short>(pOfNonStars, gpOfNonStars, [](IT p, IT gp){return static_cast<short>(NONSTAR);}, [](IT p, IT gp){return p!=gp;}, false, false, static_cast<IT>(0), static_cast<IT>(0)); stars.Set(keptNonStars); // setting level > 2 vertices as nonstars // identify grand parents of kept nonstars FullyDistSpVec<IT,IT> gpOfKeptNonStars = EWiseApply<IT>(pOfNonStars, gpOfNonStars, [](IT p, IT gp){return gp;}, [](IT p, IT gp){return p!=gp;}, false, false, static_cast<IT>(0), static_cast<IT>(0)); //FullyDistSpVec<IT, short> fixedNS = gpOfKeptNonStars; //fixedNS = NONSTAR; FullyDistSpVec<IT, short> gpNonStar= Assign(gpOfKeptNonStars, NONSTAR); stars.Set(gpNonStar); // remaining vertices: level-1 leaves of nonstars and any vertices in previous stars (iteration 1 only) FullyDistSpVec<IT,short> spStars(stars, [](short isStar){return isStar==STAR;}); // further optimization can be done to remove previous stars FullyDistSpVec<IT, IT> pOfStars = EWiseApply<IT>(spStars, parents, [](short isStar, IT p){return p;}, [](short isStar, IT p){return true;}, false, static_cast<short>(0)); FullyDistSpVec<IT,short> isParentStar = Extract(stars, pOfStars); stars.Set(isParentStar); } */ // In iteration>1: // We have only CONVERGED or NONSTAR vertices // some of the NONSTAR vertices may become STAR in the last shortcut operation // We would like to identify those new stars // In iteration 1: // we have STAR and NONSTAR vertices // every hooked vertex is marked as NONSTARs // roots are marked as STARs (includign singletones) template <typename IT> void StarCheck(FullyDistVec<IT, IT> & parents, FullyDistVec<IT,short>& stars) { // this is done here so that in the first iteration, we don't process STAR vertices // all current nonstars FullyDistSpVec<IT,short> nonStars(stars, [](short isStar){return isStar==NONSTAR;}); // initialize all nonstars to stars stars.Apply([](short isStar){return isStar==NONSTAR? STAR: isStar;}); // parents of all current nonstars FullyDistSpVec<IT, IT> pOfNonStars = EWiseApply<IT>(nonStars, parents, [](short isStar, IT p){return p;}, [](short isStar, IT p){return true;}, false, static_cast<short>(0)); // parents of all current nonstars indexed by parent // any vertex with a child should be here // leaves are not present as indices, but roots are present FullyDistSpVec<IT,short> pOfNonStarsIdx = Assign(pOfNonStars, NONSTAR); // copy parent information (the values are grandparents) FullyDistSpVec<IT,IT> gpOfNonStars_pindexed = EWiseApply<IT>(pOfNonStarsIdx, parents, [](short isStar, IT p){return p;}, [](short isStar, IT p){return true;}, false, static_cast<short>(0)); // identify if they are parents/grandparents of a vertex with level > 2 FullyDistSpVec<IT,IT> temp = gpOfNonStars_pindexed; temp.setNumToInd(); gpOfNonStars_pindexed = EWiseApply<IT>(temp, gpOfNonStars_pindexed, [](IT p, IT gp){return gp;}, [](IT p, IT gp){return p!=gp;}, false, false, static_cast<IT>(0), static_cast<IT>(0)); // index has parents of vertices with level > 2 // value has grand parents of vertices with level > 2 // update parents // All vertices (except the root and leave ) in a non-star tree will be updated stars.EWiseApply(gpOfNonStars_pindexed, [](short isStar, IT idx){return static_cast<short>(NONSTAR);}, false, static_cast<IT>(NONSTAR)); // now everything is updated except the root and leaves of nonstars // identify roots (indexed by level-1 vertices) FullyDistSpVec<IT,IT> rootsOfNonStars = EWiseApply<IT>(pOfNonStars, stars, [](IT p, short isStar){return p;}, [](IT p, short isStar){return isStar==NONSTAR;}, false, static_cast<IT>(0)); FullyDistSpVec<IT,short> rootsOfNonStarsIdx = Assign(rootsOfNonStars, NONSTAR); stars.Set( rootsOfNonStarsIdx); // remaining vertices // they must be stars (created after the shortcut) or level-1 leaves of a non-star FullyDistSpVec<IT,IT> pOflevel1V = EWiseApply<IT>(nonStars, stars, [](short s, short isStar){return static_cast<IT> (s);}, [](short s, short isStar){return isStar==STAR;}, false, static_cast<short>(0)); pOflevel1V = EWiseApply<IT>(pOflevel1V, parents, [](IT s, IT p){return p;}, [](IT s, IT p){return true;}, false, static_cast<IT>(0)); FullyDistSpVec<IT,short> isParentStar = Extract(stars, pOflevel1V); stars.Set(isParentStar); } template <typename IT, typename NT, typename DER> FullyDistSpVec<IT, IT> ConditionalHook(const SpParMat<IT,NT,DER> & A, FullyDistVec<IT, IT> & parent, FullyDistVec<IT,short> stars, int iteration) { #ifdef CC_TIMING double t1 = MPI_Wtime(); #endif FullyDistVec<IT, IT> minNeighborparent ( A.getcommgrid()); minNeighborparent = SpMV<Select2ndMinSR<NT, IT>>(A, parent); // value is the minimum of all neighbors' parents #ifdef CC_TIMING double tspmv = MPI_Wtime() - t1; #endif FullyDistSpVec<IT,IT> hooksMNP(stars, [](short isStar){return isStar==STAR;}); hooksMNP = EWiseApply<IT>(hooksMNP, minNeighborparent, [](IT x, IT mnp){return mnp;}, [](IT x, IT mnp){return true;}, false, static_cast<IT> (0)); hooksMNP = EWiseApply<IT>(hooksMNP, parent, [](IT mnp, IT p){return mnp;}, [](IT mnp, IT p){return p > mnp;}, false, static_cast<IT> (0)); FullyDistSpVec<IT, IT> finalhooks (A.getcommgrid()); if(iteration == 1) { finalhooks = hooksMNP; } else { FullyDistSpVec<IT,IT> hooksP = EWiseApply<IT>(hooksMNP, parent, [](IT mnp, IT p){return p;}, [](IT mnp, IT p){return true;}, false, static_cast<IT> (0)); finalhooks = Assign(hooksP, hooksMNP); } parent.Set(finalhooks); #ifdef CC_TIMING double tall = MPI_Wtime() - t1; std::ostringstream outs; outs.str(""); outs.clear(); outs << " Conditional Hooking Time: SpMV: " << tspmv << " Other: "<< tall-tspmv; outs<< endl; SpParHelper::Print(outs.str()); #endif return finalhooks; } template <typename IT, typename NT, typename DER> FullyDistSpVec<IT, IT> UnconditionalHook2(const SpParMat<IT,NT,DER> & A, FullyDistVec<IT, IT> & parents, FullyDistVec<IT,short> stars) { #ifdef CC_TIMING double ts = MPI_Wtime(); double t1, tspmv; #endif string spmv = "dense"; IT nNonStars = stars.Reduce(std::plus<IT>(), static_cast<IT>(0), [](short isStar){return static_cast<IT>(isStar==NONSTAR);}); IT nv = A.getnrow(); FullyDistSpVec<IT, IT> hooks(A.getcommgrid(), nv); if(nNonStars * 50 < nv) // use SpMSpV { spmv = "sparse"; FullyDistSpVec<IT,IT> nonStars(stars, [](short isStar){return isStar==NONSTAR;}); FullyDistSpVec<IT, IT> pOfNonStars = EWiseApply<IT>(nonStars, parents, [](short isStar, IT p){return p;}, [](short isStar, IT p){return true;}, false, static_cast<IT>(0)); //hooks = SpMV<Select2ndMinSR<NT, IT>>(A, pOfNonStars); #ifdef CC_TIMING t1 = MPI_Wtime(); #endif SpMV<Select2ndMinSR<NT, IT>>(A, pOfNonStars, hooks, false); #ifdef CC_TIMING tspmv = MPI_Wtime() - t1; #endif hooks = EWiseApply<IT>(hooks, stars, [](IT mnp, short isStar){return mnp;}, [](IT mnp, short isStar){return isStar==STAR;}, false, static_cast<IT> (0)); } else // use SpMV { FullyDistVec<IT, IT> parents1 = parents; parents1.EWiseApply(stars, [nv](IT p, short isStar){return isStar == STAR? nv: p;}); FullyDistVec<IT, IT> minNeighborParent ( A.getcommgrid()); #ifdef CC_TIMING t1 = MPI_Wtime(); #endif minNeighborParent = SpMV<Select2ndMinSR<NT, IT>>(A, parents1); // value is the minimum of all neighbors' parents #ifdef CC_TIMING tspmv = MPI_Wtime() - t1; #endif hooks = minNeighborParent.Find([nv](IT mnf){return mnf != nv;}); hooks = EWiseApply<IT>(hooks, stars, [](IT mnp, short isStar){return mnp;}, [](IT mnp, short isStar){return isStar==STAR;}, false, static_cast<IT> (0)); } FullyDistSpVec<IT,IT> hooksP = EWiseApply<IT>(hooks, parents, [](IT mnp, IT p){return p;}, [](IT mnp, IT p){return true;}, false, static_cast<IT> (0)); FullyDistSpVec<IT, IT> finalHooks = Assign(hooksP, hooks); parents.Set(finalHooks); #ifdef CC_TIMING double tall = MPI_Wtime() - ts; std::ostringstream outs; outs.str(""); outs.clear(); outs << " Unconditional Hooking Time " << spmv << " : " << tspmv << " Other: "<< tall-tspmv; outs<< endl; SpParHelper::Print(outs.str()); #endif return finalHooks; } template <typename IT> void Shortcut(FullyDistVec<IT, IT> & parent) { FullyDistVec<IT, IT> grandparent = parent(parent); parent = grandparent; // we can do it unconditionally because it is trivially true for stars } // before shortcut, we will make all remaining start as inactive // shortcut only on nonstar vertices // then find stars on nonstar vertices template <typename IT> void Shortcut(FullyDistVec<IT, IT> & parents, FullyDistVec<IT,short> stars) { FullyDistSpVec<IT,short> spNonStars(stars, [](short isStar){return isStar==NONSTAR;}); FullyDistSpVec<IT, IT> parentsOfNonStars = EWiseApply<IT>(spNonStars, parents, [](short isStar, IT p){return p;}, [](short isStar, IT p){return true;}, false, static_cast<short>(0)); FullyDistSpVec<IT,IT> grandParentsOfNonStars = Extract(parents, parentsOfNonStars); parents.Set(grandParentsOfNonStars); } template <typename IT, typename NT, typename DER> bool neigborsInSameCC(const SpParMat<IT,NT,DER> & A, FullyDistVec<IT, IT> & cclabel) { FullyDistVec<IT, IT> minNeighborCCLabel ( A.getcommgrid()); minNeighborCCLabel = SpMV<Select2ndMinSR<NT, IT>>(A, cclabel); return minNeighborCCLabel==cclabel; } // works only on P=1 template <typename IT, typename NT, typename DER> void Correctness(const SpParMat<IT,NT,DER> & A, FullyDistVec<IT, IT> & cclabel, IT nCC, FullyDistVec<IT,IT> parent) { DER* spSeq = A.seqptr(); // local submatrix for(auto colit = spSeq->begcol(); colit != spSeq->endcol(); ++colit) // iterate over columns { IT j = colit.colid(); // local numbering for(auto nzit = spSeq->begnz(colit); nzit < spSeq->endnz(colit); ++nzit) { IT i = nzit.rowid(); if( cclabel[i] != cclabel[j]) { std::cout << i << " (" << parent[i] << ", "<< cclabel[i] << ") & "<< j << "("<< parent[j] << ", " << cclabel[j] << ")\n"; } } } } // Input: // parent: parent of each vertex. parent is essentilly the root of the star which a vertex belongs to. // parent of the root is itself // Output: // cclabel: connected components are incrementally labeled // returns the number of connected components // Example: input = [0, 0, 2, 3, 0, 2], output = (0, 0, 1, 2, 0, 1), return 3 template <typename IT> IT LabelCC(FullyDistVec<IT, IT> & parent, FullyDistVec<IT, IT> & cclabel) { cclabel = parent; cclabel.ApplyInd([](IT val, IT ind){return val==ind ? -1 : val;}); FullyDistSpVec<IT, IT> roots (cclabel, bind2nd(std::equal_to<IT>(), -1)); // parents of leaves are still correct FullyDistSpVec<IT, IT> pOfLeaves (cclabel, bind2nd(std::not_equal_to<IT>(), -1)); roots.nziota(0); cclabel.Set(roots); FullyDistSpVec<IT,IT> labelOfParents = Extract(cclabel, pOfLeaves); cclabel.Set(labelOfParents); //cclabel = cclabel(parent); return roots.getnnz(); } template <typename IT, typename NT, typename DER> FullyDistVec<IT, IT> CC(SpParMat<IT,NT,DER> & A, IT & nCC) { IT nrows = A.getnrow(); //A.AddLoops(1); // needed for isolated vertices: not needed anymore FullyDistVec<IT,IT> parent(A.getcommgrid()); parent.iota(nrows, 0); // parent(i)=i initially FullyDistVec<IT,short> stars(A.getcommgrid(), nrows, STAR);// initially every vertex belongs to a star int iteration = 1; std::ostringstream outs; // isolated vertices are marked as converged FullyDistVec<int64_t,double> degree = A.Reduce(Column, plus<double>(), 0.0, [](double val){return 1.0;}); stars.EWiseApply(degree, [](short isStar, double degree){return degree == 0.0? CONVERGED: isStar;}); int nthreads = 1; #ifdef THREADED #pragma omp parallel { nthreads = omp_get_num_threads(); } #endif SpParMat<IT,bool,SpDCCols < IT, bool >> Abool = A; Abool.ActivateThreading(nthreads*4); while (true) { #ifdef CC_TIMING double t1 = MPI_Wtime(); #endif FullyDistSpVec<IT, IT> condhooks = ConditionalHook(Abool, parent, stars, iteration); #ifdef CC_TIMING double t_cond_hook = MPI_Wtime() - t1; t1 = MPI_Wtime(); #endif // Any iteration other than the first iteration, // a non-star is formed after a conditional hooking // In the first iteration, we can hook two vertices to create a star // After the first iteratio, only singletone CCs reamin isolated // Here, we are ignoring the first iteration (still correct, but may ignore few possible // unconditional hooking in the first iteration) // remove cond hooks from stars if(iteration > 1) { StarCheckAfterHooking(Abool, parent, stars, condhooks, true); } else { // explain stars.EWiseApply(condhooks, [](short isStar, IT x){return static_cast<short>(NONSTAR);}, false, static_cast<IT>(NONSTAR)); FullyDistSpVec<IT, short> pNonStar= Assign(condhooks, NONSTAR); stars.Set(pNonStar); // it does not create any cycle in the unconditional hooking, see the proof in the paper } #ifdef CC_TIMING double t_starcheck1 = MPI_Wtime() - t1; t1 = MPI_Wtime(); #endif FullyDistSpVec<IT, IT> uncondHooks = UnconditionalHook2(Abool, parent, stars); #ifdef CC_TIMING double t_uncond_hook = MPI_Wtime() - t1; t1 = MPI_Wtime(); #endif if(iteration > 1) { StarCheckAfterHooking(Abool, parent, stars, uncondHooks, false); stars.Apply([](short isStar){return isStar==STAR? CONVERGED: isStar;}); } else { // explain stars.EWiseApply(uncondHooks, [](short isStar, IT x){return static_cast<short>(NONSTAR);}, false, static_cast<IT>(NONSTAR)); } IT nconverged = stars.Reduce(std::plus<IT>(), static_cast<IT>(0), [](short isStar){return static_cast<IT>(isStar==CONVERGED);}); if(nconverged==nrows) { outs.clear(); outs << "Iteration: " << iteration << " converged: " << nrows << " stars: 0" << " nonstars: 0" ; outs<< endl; SpParHelper::Print(outs.str()); break; } #ifdef CC_TIMING double t_starcheck2 = MPI_Wtime() - t1; t1 = MPI_Wtime(); #endif Shortcut(parent, stars); #ifdef CC_TIMING double t_shortcut = MPI_Wtime() - t1; t1 = MPI_Wtime(); #endif StarCheck(parent, stars); #ifdef CC_TIMING double t_starcheck = MPI_Wtime() - t1; t1 = MPI_Wtime(); #endif IT nonstars = stars.Reduce(std::plus<IT>(), static_cast<IT>(0), [](short isStar){return static_cast<IT>(isStar==NONSTAR);}); IT nstars = nrows - (nonstars + nconverged); double t2 = MPI_Wtime(); outs.str(""); outs.clear(); outs << "Iteration: " << iteration << " converged: " << nconverged << " stars: " << nstars << " nonstars: " << nonstars; #ifdef CC_TIMING //outs << " Time: t_cond_hook: " << t_cond_hook << " t_starcheck1: " << t_starcheck1 << " t_uncond_hook: " << t_uncond_hook << " t_starcheck2: " << t_starcheck2 << " t_shortcut: " << t_shortcut << " t_starcheck: " << t_starcheck; #endif outs<< endl; SpParHelper::Print(outs.str()); iteration++; } FullyDistVec<IT, IT> cc(parent.getcommgrid()); nCC = LabelCC(parent, cc); // TODO: Print to file //PrintCC(cc, nCC); //Correctness(A, cc, nCC, parent); return cc; } template <typename IT> void PrintCC(FullyDistVec<IT, IT> CC, IT nCC) { for(IT i=0; i< nCC; i++) { FullyDistVec<IT, IT> ith = CC.FindInds(bind2nd(std::equal_to<IT>(), i)); ith.DebugPrint(); } } // Print the size of the first 4 clusters template <typename IT> void First4Clust(FullyDistVec<IT, IT>& cc) { FullyDistSpVec<IT, IT> cc1 = cc.Find([](IT label){return label==0;}); FullyDistSpVec<IT, IT> cc2 = cc.Find([](IT label){return label==1;}); FullyDistSpVec<IT, IT> cc3 = cc.Find([](IT label){return label==2;}); FullyDistSpVec<IT, IT> cc4 = cc.Find([](IT label){return label==3;}); std::ostringstream outs; outs.str(""); outs.clear(); outs << "Size of the first component: " << cc1.getnnz() << std::endl; outs << "Size of the second component: " << cc2.getnnz() << std::endl; outs << "Size of the third component: " << cc3.getnnz() << std::endl; outs << "Size of the fourth component: " << cc4.getnnz() << std::endl; } template <typename IT> void HistCC(FullyDistVec<IT, IT> CC, IT nCC) { FullyDistVec<IT, IT> ccSizes(CC.getcommgrid(), nCC, 0); for(IT i=0; i< nCC; i++) { FullyDistSpVec<IT, IT> ith = CC.Find(bind2nd(std::equal_to<IT>(), i)); ccSizes.SetElement(i, ith.getnnz()); } IT largestCCSise = ccSizes.Reduce(maximum<IT>(), static_cast<IT>(0)); const IT * locCCSizes = ccSizes.GetLocArr(); int numBins = 200; std::vector<IT> localHist(numBins,0); for(IT i=0; i< ccSizes.LocArrSize(); i++) { IT bin = (locCCSizes[i]*(numBins-1))/largestCCSise; localHist[bin]++; } std::vector<IT> globalHist(numBins,0); MPI_Comm world = CC.getcommgrid()->GetWorld(); MPI_Reduce(localHist.data(), globalHist.data(), numBins, MPIType<IT>(), MPI_SUM, 0, world); int myrank; MPI_Comm_rank(world,&myrank); if(myrank==0) { std::cout << "The largest component size: " << largestCCSise << std::endl; std::ofstream output; output.open("hist.txt", std::ios_base::app ); std::copy(globalHist.begin(), globalHist.end(), std::ostream_iterator<IT> (output, " ")); output << std::endl; output.close(); } //ccSizes.PrintToFile("histCC.txt"); } }
iter_helper.h
#pragma once #include "util/graph/graph.h" #include "util/timer.h" #include "util/log/log.h" #include "util/search/search_util.h" #include "util/stat.h" #include "pkt_support_update_utils.h" #include "parallel_all_edge_cnc.h" #include "iter_stat_helper.h" #include "extern_variables.h" #define V_BUFF_SIZE (4096) #define MAX_LEVEL (20000) class IterHelper { public: graph_t *g; int omp_num_threads_; size_t num_edges_; // num_edges_ is changed during the shrinking. int n_; public: BoolArray<word_type> processed_; // Bucket Related. BoolArray<word_type> bucket_removed_indicator_; int bucket_level_end_ = 0; bool *in_bucket_window_; eid_t *bucket_buf_; size_t window_bucket_buf_size_ = 0; size_t total_size_ = 0; // Queue Related. (curr_/next_). long curr_tail_; long next_tail_; eid_t *curr_; BoolArray<word_type> in_curr_; eid_t *next_; BoolArray<word_type> in_next_; // For Graph Shrink. bool *is_vertex_updated_; eid_t *off_end_; vid_t *global_v_buffer_; public: // View (edge list and edge support) int **edge_sup_ptr_; Edge **edge_lst_ptr_; public: // BSR. vector<vector<int>> partition_id_lst; vector<vector<bmp_word_type>> bitmap_in_partition_lst; void FreeBSR(); public: IterHelper(graph_t *g, int **edge_sup_ptr, Edge **edge_lst_ptr); void MemSetIterVariables(int max_omp_threads); void ComputeTriSupport(IterStatTLS &iter_stat_tls); void SCANGraph(int level); void ShrinkCSREID(volatile eid_t *global_buffer_size, vid_t *local_buffer); void MarkProcessed(); void SwapCurNextQueue(); void ProcessSupportZeros(); ~IterHelper(); }; void TriCntDetailSubLevel(graph_t *g, eid_t *curr, BoolArray<word_type> &InCurr, long currTail, int *EdgeSupport, int level, eid_t *next, BoolArray<word_type> &InNext, long *nextTail, BoolArray<word_type> &processed_, Edge *edgeIdtoEdge, eid_t *off_end, bool *is_vertex_updated, IterHelper &iter_helper, volatile eid_t &global_v_buff_size ); /* * F requires a callable or a functor with signature `void (int)` */ template<typename F> void AbstractPKT(graph_t *g, int *&EdgeSupport, Edge *&edgeIdToEdge, IterHelper &iter_helper, F f) { Timer malloc_timer; long numEdges = g->m / 2; auto max_omp_threads = omp_get_max_threads(); log_info("Max Threads: %d", max_omp_threads); #pragma omp parallel num_threads(max_omp_threads) { iter_helper.MemSetIterVariables(max_omp_threads); } log_info("Malloc & MemSet Time: %.6lfs", malloc_timer.elapsed()); vector<double> shrink_time_lst; Timer iter_timer; Timer comp_timer; size_t iter_num = 0; size_t local_iter_num = 0; volatile eid_t global_v_buff_size = 0; size_t num_of_shrinks = 0; vector<int> tc_level; vector<double> tc_level_time; double init_tc_time = 0; double penalty_tc_time = 0; #pragma omp parallel { // TC. IterStatTLS iter_stat_tls; iter_helper.ComputeTriSupport(iter_stat_tls); #pragma omp single { init_tc_time = iter_stat_tls.triTime; iter_timer.reset(); log_info("TC time: %.9lfs", init_tc_time); } // Compute Truss. auto *local_buffer = (vid_t *) malloc(sizeof(vid_t) * V_BUFF_SIZE); int level = 0; long acc_deleted = 0; long todo = numEdges; while (todo > 0) { // 1st: Synchronization. #pragma omp single { iter_stat_tls.PrintIterStat(iter_timer, todo, numEdges, level, iter_num, local_iter_num); } iter_stat_tls.ResetLocalTime(); iter_stat_tls.RecordSyncTime(); // 2nd: Scanning the graph to fetch the level. iter_helper.SCANGraph(level); iter_stat_tls.RecordSCANTime(); // size_t sub_level = 0; // 3rd: Processing the graph (shrinking and updating supports). while (iter_helper.curr_tail_ > 0) { //#pragma omp single // log_info("Level: %d, beg sub-level: %d, Task Size: %lld", level, sub_level, iter_helper.curr_tail_); todo = todo - iter_helper.curr_tail_; iter_stat_tls.RecordQueueSize(iter_helper.curr_tail_); // All of them being the last level. if (todo == 0) { // No need to process but need to copy the results back. level = level + 1; break; } // 3.1: Optional shrinking graph. (Move to here to maximally shrink the graph). if (acc_deleted > numEdges / graph_compaction_threshold) { #pragma omp single log_info("Shrink Graph!!!!!!!!!!!!"); #pragma omp barrier Timer shrink_timer; iter_helper.ShrinkCSREID(&global_v_buff_size, local_buffer); acc_deleted = 0; #pragma omp single { iter_stat_tls.RecordShrinkNum(num_of_shrinks); shrink_time_lst.emplace_back(shrink_timer.elapsed()); } } iter_stat_tls.RecordShrinkTime(); // 3.2: Real Processing (updating supports). if (level == 0) { iter_helper.ProcessSupportZeros(); } else { size_t task_size = iter_helper.curr_tail_ * (size_t) (level + 1); size_t left_edge_size = todo; double estimated_tc_time = left_edge_size / (g->m / 2.0) * init_tc_time + penalty_tc_time; double estimated_peel_time = task_size / estimated_process_throughput; if (estimated_tc_time > estimated_peel_time) { auto to_delete = iter_helper.curr_tail_; f(level); acc_deleted += to_delete; } else { #pragma omp single { log_info("Estimated TC Time: %.9lfs, Peel Time: %.9lfs", estimated_tc_time, estimated_peel_time); tc_level.emplace_back(level); log_info("!!!TriCnt!!!, Task-Size: %'zu, TC-Cnt/50: %'zu", task_size, tc_cnt / 50); } Timer tc_timer; TriCntDetailSubLevel(g, iter_helper.curr_, iter_helper.in_curr_, iter_helper.curr_tail_, *iter_helper.edge_sup_ptr_, level, iter_helper.next_, iter_helper.in_next_, &iter_helper.next_tail_, iter_helper.processed_, *iter_helper.edge_lst_ptr_, iter_helper.off_end_, iter_helper.is_vertex_updated_, iter_helper, global_v_buff_size); acc_deleted = 0; #pragma omp single { auto cost = tc_timer.elapsed(); if (estimated_tc_time * 1.2 < cost) { penalty_tc_time += cost - estimated_tc_time; log_info("Penalty TC-Time: %.9lfs", penalty_tc_time); } tc_level_time.emplace_back(cost); } } } // 3.3: Swap Queues. #pragma omp single { iter_helper.SwapCurNextQueue(); iter_stat_tls.RecordIterNum(iter_num, local_iter_num); } #pragma omp barrier iter_stat_tls.RecordProcessTime(); //#pragma omp single // log_info("Level: %d, Finish sub-level: %d, Tak size: %lld", level, sub_level, iter_helper.curr_tail_); // sub_level++; } level = level + 1; #pragma omp barrier // End of Iterative Peeling for this Level. } // The end. #pragma omp single { log_info("Total Levels: %d", level); log_trace("Last Level Finished: %d, Elapsed Time: %.9lfs, Left/Total: %'lld/%'lld, " "Local/Global-Iter#: %zu/%zu", level - 1, iter_timer.elapsed_and_reset(), todo, numEdges, local_iter_num, iter_num); iter_stat_tls.PrintFinalStat(level, num_of_shrinks); stringstream ss; ss << tc_level << ", Time: " << tc_level_time; log_trace("TC-levels: %s", ss.str().c_str()); stringstream ss2; ss2 << shrink_time_lst; log_trace("Shrink Time List: %s", ss2.str().c_str()); } free(local_buffer); } //End of parallel region log_info("Total computation cost: %.9lfs", comp_timer.elapsed_and_reset()); }
.body.c
#define S1(zT0,zT1,zT2,zT3,i,j) B[i][j]=A[i][j]+u1[i]*v1[j]+u2[i]*v2[j]; #define S2(zT0,zT1,zT2,zT3,i,j) x[i]=x[i]+beta*B[j][i]*y[j]; #define S3(zT0,zT1,zT2,zT3,i) x[i]=x[i]+z[i]; #define S4(zT0,zT1,zT2,zT3,i,j) w[i]=w[i]+alpha*B[i][j]*x[j]; int t0, t1, t2, t3, t4, t5, t6, t7; register int lb, ub, lb1, ub1, lb2, ub2; register int lbv, ubv; /* Generated from PLUTO-produced CLooG file by CLooG v0.14.1 64 bits in 0.03s. */ lb1=0; ub1=floord(N-1,8000); #pragma omp parallel for shared(t0,lb1,ub1) private(t1,t2,t3,t4,t5,t6,t7) for (t1=lb1; t1<=ub1; t1++) { for (t2=0;t2<=floord(N-1,256);t2++) { for (t3=max(20*t1,0);t3<=min(20*t1+19,floord(N-1,400));t3++) { for (t4=max(0,16*t2);t4<=min(16*t2+15,floord(N-1,16));t4++) { for (t5=max(0,16*t4);t5<=min(N-1,16*t4+15);t5++) { { lbv=max(0,400*t3); ubv=min(N-1,400*t3+399); #pragma ivdep #pragma vector always for (t6=lbv; t6<=ubv; t6++) { S1(t1,t2,t3,t4,t5,t6) ; S2(t1,t2,t3,t4,t6,t5) ; } } } } } } } lb1=0; ub1=floord(N-1,8000); #pragma omp parallel for shared(t0,lb1,ub1) private(t1,t2,t3,t4,t5,t6,t7) for (t1=lb1; t1<=ub1; t1++) { for (t3=max(20*t1,0);t3<=min(20*t1+19,floord(N-1,400));t3++) { for (t4=max(0,0);t4<=min(0,15);t4++) { { lbv=max(0,400*t3); ubv=min(N-1,400*t3+399); #pragma ivdep #pragma vector always for (t6=lbv; t6<=ubv; t6++) { S3(t1,0,t3,t4,t6) ; } } } } } lb1=0; ub1=floord(N-1,8000); #pragma omp parallel for shared(t0,lb1,ub1) private(t1,t2,t3,t4,t5,t6,t7) for (t1=lb1; t1<=ub1; t1++) { for (t2=0;t2<=floord(N-1,256);t2++) { for (t3=max(20*t1,0);t3<=min(20*t1+19,floord(N-1,400));t3++) { for (t4=max(16*t2,0);t4<=min(floord(N-1,16),16*t2+15);t4++) { for (t5=max(0,16*t4);t5<=min(N-1,16*t4+15);t5++) { { lbv=max(0,400*t3); ubv=min(N-1,400*t3+399); #pragma ivdep #pragma vector always for (t6=lbv; t6<=ubv; t6++) { S4(t1,t2,t3,t4,t6,t5) ; } } } } } } } /* End of CLooG code */
office_fmt_plug.c
/* Office 2007 cracker patch for JtR. Hacked together during March of 2012 by * Dhiru Kholia <dhiru.kholia at gmail.com> */ #if FMT_EXTERNS_H extern struct fmt_main fmt_office; #elif FMT_REGISTERS_H john_register_one(&fmt_office); #else #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <errno.h> #include <openssl/aes.h> #ifdef _OPENMP #include <omp.h> #define OMP_SCALE 4 #endif #include "arch.h" #include "misc.h" #include "common.h" #include "formats.h" #include "params.h" #include "options.h" #include "unicode.h" #include "sha.h" #include "sha2.h" #include "johnswap.h" #include "memdbg.h" #define FORMAT_LABEL "Office" #define FORMAT_NAME "2007/2010 (SHA-1) / 2013 (SHA-512), with AES" #define ALGORITHM_NAME "32/" ARCH_BITS_STR " " SHA2_LIB #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define PLAINTEXT_LENGTH 32 #define BINARY_SIZE 0 #define SALT_SIZE sizeof(*cur_salt) #define BINARY_ALIGN 1 #define SALT_ALIGN sizeof(int) #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #undef MIN #define MIN(a, b) (((a) > (b)) ? (b) : (a)) static struct fmt_tests office_tests[] = { {"$office$*2007*20*128*16*8b2c9e8c878844fc842012273be4bea8*aa862168b80d8c45c852696a8bb499eb*a413507fabe2d87606595f987f679ff4b5b4c2cd", "Password"}, /* 2007-Default_myhovercraftisfullofeels_.docx */ {"$office$*2007*20*128*16*91f095a1fd02595359fe3938fa9236fd*e22668eb1347957987175079e980990f*659f50b9062d36999bf3d0911068c93268ae1d86", "myhovercraftisfullofeels"}, /* 2007-Default_myhovercraftisfullofeels_.dotx */ {"$office$*2007*20*128*16*56ea65016fbb4eac14a6770b2dbe7e99*8cf82ce1b62f01fd3b2c7666a2313302*21443fe938177e648c482da72212a8848c2e9c80", "myhovercraftisfullofeels"}, /* 2007-Default_myhovercraftisfullofeels_.xlsb */ {"$office$*2007*20*128*16*fbd4cc5dab9b8e341778ddcde9eca740*3a040a9cef3d3675009b22f99718e39c*48053b27e95fa53b3597d48ca4ad41eec382e0c8", "myhovercraftisfullofeels"}, /* 2007-Default_myhovercraftisfullofeels_.xlsm */ {"$office$*2007*20*128*16*fbd4cc5dab9b8e341778ddcde9eca740*92bb2ef34ca662ca8a26c8e2105b05c0*0261ba08cd36a324aa1a70b3908a24e7b5a89dd6", "myhovercraftisfullofeels"}, /* 2007-Default_myhovercraftisfullofeels_.xlsx */ {"$office$*2007*20*128*16*fbd4cc5dab9b8e341778ddcde9eca740*46bef371486919d4bffe7280110f913d*b51af42e6696baa097a7109cebc3d0ff7cc8b1d8", "myhovercraftisfullofeels"}, /* 2007-Default_myhovercraftisfullofeels_.xltx */ {"$office$*2007*20*128*16*fbd4cc5dab9b8e341778ddcde9eca740*1addb6823689aca9ce400be8f9e55fc9*e06bf10aaf3a4049ffa49dd91cf9e7bbf88a1b3b", "myhovercraftisfullofeels"}, /* 2010-Default_myhovercraftisfullofeels_.docx */ {"$office$*2010*100000*128*16*213aefcafd9f9188e78c1936cbb05a44*d5fc7691292ab6daf7903b9a8f8c8441*46bfac7fb87cd43bd0ab54ebc21c120df5fab7e6f11375e79ee044e663641d5e", "myhovercraftisfullofeels"}, /* 2010-Default_myhovercraftisfullofeels_.dotx */ {"$office$*2010*100000*128*16*0907ec6ecf82ede273b7ee87e44f4ce5*d156501661638cfa3abdb7fdae05555e*4e4b64e12b23f44d9a8e2e00196e582b2da70e5e1ab4784384ad631000a5097a", "myhovercraftisfullofeels"}, /* 2010-Default_myhovercraftisfullofeels_.xlsb */ {"$office$*2010*100000*128*16*71093d08cf950f8e8397b8708de27c1f*00780eeb9605c7e27227c5619e91dc21*90aaf0ea5ccc508e699de7d62c310f94b6798ae77632be0fc1a0dc71600dac38", "myhovercraftisfullofeels"}, /* 2010-Default_myhovercraftisfullofeels_.xlsx */ {"$office$*2010*100000*128*16*71093d08cf950f8e8397b8708de27c1f*ef51883a775075f30d2207e87987e6a3*a867f87ea955d15d8cb08dc8980c04bf564f8af060ab61bf7fa3543853e0d11a", "myhovercraftisfullofeels"}, /* 2013-openwall.pptx */ {"$office$*2013*100000*256*16*9b12805dd6d56f46d07315153f3ecb9c*c5a4a167b51faa6629f6a4caf0b4baa8*87397e0659b2a6fff90291f8e6d6d0018b750b792fefed77001edbafba7769cd", "openwall"}, /* 365-2013-openwall.docx */ {"$office$*2013*100000*256*16*774a174239a7495a59cac39a122d991c*b2f9197840f9e5d013f95a3797708e83*ecfc6d24808691aac0daeaeba72aba314d72c6bbd12f7ff0ea1a33770187caef", "openwall"}, /* 365-2013-password.docx */ {"$office$*2013*100000*256*16*d4fc9302eedabf9872b24ca700a5258b*7c9554d582520747ec3e872f109a7026*1af5b5024f00e35eaf5fd8148b410b57e7451a32898acaf14275a8c119c3a4fd", "password"}, /* 365-2013-password.xlsx */ {"$office$*2013*100000*256*16*59b49c64c0d29de733f0025837327d50*70acc7946646ea300fc13cfe3bd751e2*627c8bdb7d9846228aaea81eeed434d022bb93bb5f4da146cb3ad9d847de9ec9", "password"}, /* 365-2013-strict-password.docx */ {"$office$*2013*100000*256*16*f1c23049d85876e6b20e95ab86a477f1*13303dbd27a38ea86ef11f1b2bc56225*9a69596de0655a6c6a5b2dc4b24d6e713e307fb70af2d6b67b566173e89f941d", "password"}, {NULL} }; static struct custom_salt { char unsigned osalt[32]; /* bigger than necessary */ char unsigned encryptedVerifier[16]; char unsigned encryptedVerifierHash[32]; int version; int verifierHashSize; int keySize; int saltSize; /* Office 2010/2013 */ int spinCount; } *cur_salt; #define MS_OFFICE_2007_ITERATIONS 50000 #if defined (_OPENMP) static int omp_t = 1; #endif /* Password encoded in UCS-2 */ static UTF16 (*saved_key)[PLAINTEXT_LENGTH + 1]; /* UCS-2 password length, in octets */ static int *saved_len; static int *cracked; /* Office 2010/2013 */ static const unsigned char encryptedVerifierHashInputBlockKey[] = { 0xfe, 0xa7, 0xd2, 0x76, 0x3b, 0x4b, 0x9e, 0x79 }; static const unsigned char encryptedVerifierHashValueBlockKey[] = { 0xd7, 0xaa, 0x0f, 0x6d, 0x30, 0x61, 0x34, 0x4e }; static unsigned char *DeriveKey(unsigned char *hashValue, unsigned char *X1) { int i; unsigned char derivedKey[64]; SHA_CTX ctx; // This is step 4a in 2.3.4.7 of MS_OFFCRYPT version 1.0 // and is required even though the notes say it should be // used only when the encryption algorithm key > hash length. for (i = 0; i < 64; i++) derivedKey[i] = (i < 20 ? 0x36 ^ hashValue[i] : 0x36); SHA1_Init(&ctx); SHA1_Update(&ctx, derivedKey, 64); SHA1_Final(X1, &ctx); if (cur_salt->verifierHashSize > cur_salt->keySize/8) return X1; /* TODO: finish up this function */ //for (i = 0; i < 64; i++) // derivedKey[i] = (i < 30 ? 0x5C ^ hashValue[i] : 0x5C); fprintf(stderr, "\n\n*** ERROR: DeriveKey() entered Limbo.\n"); fprintf(stderr, "Please report to john-dev mailing list.\n"); error(); return NULL; } static unsigned char* GeneratePasswordHashUsingSHA1(UTF16 *passwordBuf, int passwordBufSize, unsigned char *final) { unsigned char hashBuf[20], *key; /* H(0) = H(salt, password) * hashBuf = SHA1Hash(salt, password); * create input buffer for SHA1 from salt and unicode version of password */ unsigned int inputBuf[(0x14 + 0x04 + 4) / sizeof(int)]; unsigned char X1[20]; int i; SHA_CTX ctx; SHA1_Init(&ctx); SHA1_Update(&ctx, cur_salt->osalt, cur_salt->saltSize); SHA1_Update(&ctx, passwordBuf, passwordBufSize); SHA1_Final(hashBuf, &ctx); /* Generate each hash in turn * H(n) = H(i, H(n-1)) * hashBuf = SHA1Hash(i, hashBuf); */ // Create a byte array of the integer and put at the front of the input buffer // 1.3.6 says that little-endian byte ordering is expected memcpy(&inputBuf[1], hashBuf, 20); for (i = 0; i < MS_OFFICE_2007_ITERATIONS; i++) { #if ARCH_LITTLE_ENDIAN *inputBuf = i; #else *inputBuf = JOHNSWAP(i); #endif // 'append' the previously generated hash to the input buffer SHA1_Init(&ctx); SHA1_Update(&ctx, inputBuf, 0x14 + 0x04); SHA1_Final((unsigned char*)&inputBuf[1], &ctx); } // Finally, append "block" (0) to H(n) // hashBuf = SHA1Hash(hashBuf, 0); memset(&inputBuf[6], 0, 4); SHA1_Init(&ctx); SHA1_Update(&ctx, &inputBuf[1], 0x14 + 0x04); SHA1_Final(hashBuf, &ctx); key = DeriveKey(hashBuf, X1); // Should handle the case of longer key lengths as shown in 2.3.4.9 // Grab the key length bytes of the final hash as the encrypytion key memcpy(final, key, cur_salt->keySize/8); return final; } static int PasswordVerifier(unsigned char * key) { unsigned char decryptedVerifier[16]; unsigned char decryptedVerifierHash[16]; AES_KEY akey; SHA_CTX ctx; unsigned char checkHash[20]; memset(&akey, 0, sizeof(AES_KEY)); if(AES_set_decrypt_key(key, 128, &akey) < 0) { fprintf(stderr, "AES_set_decrypt_key failed!\n"); return 0; } AES_ecb_encrypt(cur_salt->encryptedVerifier, decryptedVerifier, &akey, AES_DECRYPT); memset(&akey, 0, sizeof(AES_KEY)); if(AES_set_decrypt_key(key, 128, &akey) < 0) { fprintf(stderr, "AES_set_decrypt_key failed!\n"); return 0; } AES_ecb_encrypt(cur_salt->encryptedVerifierHash, decryptedVerifierHash, &akey, AES_DECRYPT); /* find SHA1 hash of decryptedVerifier */ SHA1_Init(&ctx); SHA1_Update(&ctx, decryptedVerifier, 16); SHA1_Final(checkHash, &ctx); return !memcmp(checkHash, decryptedVerifierHash, 16); } static void GenerateAgileEncryptionKey(UTF16 *passwordBuf, int passwordBufSize, int hashSize, unsigned char *hashBuf) { /* H(0) = H(salt, password) * hashBuf = SHA1Hash(salt, password); * create input buffer for SHA1 from salt and unicode version of password */ unsigned int inputBuf[(28 + 4) / sizeof(int)]; int i; SHA_CTX ctx; SHA1_Init(&ctx); SHA1_Update(&ctx, cur_salt->osalt, cur_salt->saltSize); SHA1_Update(&ctx, passwordBuf, passwordBufSize); SHA1_Final(hashBuf, &ctx); /* Generate each hash in turn * H(n) = H(i, H(n-1)) * hashBuf = SHA1Hash(i, hashBuf); */ // Create a byte array of the integer and put at the front of the input buffer // 1.3.6 says that little-endian byte ordering is expected memcpy(&inputBuf[1], hashBuf, 20); for (i = 0; i < cur_salt->spinCount; i++) { #if ARCH_LITTLE_ENDIAN *inputBuf = i; #else *inputBuf = JOHNSWAP(i); #endif // 'append' the previously generated hash to the input buffer SHA1_Init(&ctx); SHA1_Update(&ctx, inputBuf, 0x14 + 0x04); SHA1_Final((unsigned char*)&inputBuf[1], &ctx); } // Finally, append "block" (0) to H(n) memcpy(&inputBuf[6], encryptedVerifierHashInputBlockKey, 8); SHA1_Init(&ctx); SHA1_Update(&ctx, &inputBuf[1], 28); SHA1_Final(hashBuf, &ctx); // And second "block" (0) to H(n) memcpy(&inputBuf[6], encryptedVerifierHashValueBlockKey, 8); SHA1_Init(&ctx); SHA1_Update(&ctx, &inputBuf[1], 28); SHA1_Final(&hashBuf[32], &ctx); // Fix up the size per the spec if (20 < hashSize) { // FIXME: Is this ever true? for(i = 20; i < hashSize; i++) { hashBuf[i] = 0x36; hashBuf[32 + i] = 0x36; } } } static void GenerateAgileEncryptionKey512(UTF16 *passwordBuf, int passwordBufSize, unsigned char *hashBuf) { unsigned int inputBuf[128 / sizeof(int)]; int i; SHA512_CTX ctx; SHA512_Init(&ctx); SHA512_Update(&ctx, cur_salt->osalt, cur_salt->saltSize); SHA512_Update(&ctx, passwordBuf, passwordBufSize); SHA512_Final(hashBuf, &ctx); // Create a byte array of the integer and put at the front of the input buffer // 1.3.6 says that little-endian byte ordering is expected memcpy(&inputBuf[1], hashBuf, 64); for (i = 0; i < cur_salt->spinCount; i++) { #if ARCH_LITTLE_ENDIAN *inputBuf = i; #else *inputBuf = JOHNSWAP(i); #endif // 'append' the previously generated hash to the input buffer SHA512_Init(&ctx); SHA512_Update(&ctx, inputBuf, 64 + 0x04); SHA512_Final((unsigned char*)&inputBuf[1], &ctx); } // Finally, append "block" (0) to H(n) memcpy(&inputBuf[68/4], encryptedVerifierHashInputBlockKey, 8); SHA512_Init(&ctx); SHA512_Update(&ctx, &inputBuf[1], 64 + 8); SHA512_Final(hashBuf, &ctx); // And second "block" (0) to H(n) memcpy(&inputBuf[68/4], encryptedVerifierHashValueBlockKey, 8); SHA512_Init(&ctx); SHA512_Update(&ctx, &inputBuf[1], 64 + 8); SHA512_Final(&hashBuf[64], &ctx); } static void DecryptUsingSymmetricKeyAlgorithm(unsigned char *verifierInputKey, unsigned char *encryptedVerifier, const unsigned char *decryptedVerifier, int length) { unsigned char iv[32]; AES_KEY akey; memcpy(iv, cur_salt->osalt, 16); memset(&iv[16], 0, 16); memset(&akey, 0, sizeof(AES_KEY)); if(cur_salt->keySize == 128) { if(AES_set_decrypt_key(verifierInputKey, 128, &akey) < 0) { fprintf(stderr, "AES_set_decrypt_key failed!\n"); } } else { if(AES_set_decrypt_key(verifierInputKey, 256, &akey) < 0) { fprintf(stderr, "AES_set_decrypt_key failed!\n"); } } AES_cbc_encrypt(encryptedVerifier, (unsigned char*)decryptedVerifier, length, &akey, iv, AES_DECRYPT); } static void init(struct fmt_main *self) { #if defined (_OPENMP) omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif saved_key = mem_calloc_tiny(sizeof(*saved_key) * self->params.max_keys_per_crypt, sizeof(UTF16)); saved_len = mem_calloc_tiny(sizeof(*saved_len) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); cracked = mem_calloc_tiny(sizeof(*cracked) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); if (pers_opts.target_enc == UTF_8) self->params.plaintext_length = MIN(125, PLAINTEXT_LENGTH * 3); } static int ishex(char *q) { while (atoi16[ARCH_INDEX(*q)] != 0x7F) q++; return !*q; } static int valid(char *ciphertext, struct fmt_main *self) { char *ctcopy, *ptr, *keeptr; int res; if (strncmp(ciphertext, "$office$*", 9)) return 0; if (!(ctcopy = strdup(ciphertext))) { fprintf(stderr, "Memory allocation failed in %s, unable to check if hash is valid!", FORMAT_LABEL); return 0; } keeptr = ctcopy; ctcopy += 9; if (!(ptr = strtok(ctcopy, "*"))) goto error; if (strncmp(ptr, "2007", 4) && strncmp(ptr, "2010", 4) && strncmp(ptr, "2013", 4)) goto error; if (!(ptr = strtok(NULL, "*"))) /* hash size or iterations */ goto error; if (!(ptr = strtok(NULL, "*"))) goto error; if (strncmp(ptr, "128", 3) && strncmp(ptr, "256", 3)) /* key size */ goto error; if (!(ptr = strtok(NULL, "*"))) /* salt size */ goto error; res = atoi(ptr); if (res != 16) /* can we handle other values? */ goto error; if (!(ptr = strtok(NULL, "*"))) /* salt */ goto error; if (strlen(ptr) != res * 2) goto error; if (!ishex(ptr)) goto error; if (!(ptr = strtok(NULL, "*"))) /* encrypted verifier */ goto error; if (!ishex(ptr)) goto error; if (!(ptr = strtok(NULL, "*"))) /* encrypted verifier hash */ goto error; if (!ishex(ptr)) goto error; if (strlen(ptr) > 64) goto error; if ((ptr = strtok(NULL, "*"))) goto error; MEM_FREE(keeptr); return 1; error: MEM_FREE(keeptr); return 0; } static void *get_salt(char *ciphertext) { int i, length; char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy, *p; ctcopy += 9; /* skip over "$office$*" */ cur_salt = mem_calloc_tiny(sizeof(struct custom_salt), MEM_ALIGN_WORD); p = strtok(ctcopy, "*"); cur_salt->version = atoi(p); p = strtok(NULL, "*"); if(cur_salt->version == 2007) { cur_salt->verifierHashSize = atoi(p); } else { cur_salt->spinCount = atoi(p); } p = strtok(NULL, "*"); cur_salt->keySize = atoi(p); p = strtok(NULL, "*"); cur_salt->saltSize = atoi(p); p = strtok(NULL, "*"); for (i = 0; i < cur_salt->saltSize; i++) cur_salt->osalt[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtok(NULL, "*"); for (i = 0; i < 16; i++) cur_salt->encryptedVerifier[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtok(NULL, "*"); length = strlen(p) / 2; for (i = 0; i < length; i++) cur_salt->encryptedVerifierHash[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; MEM_FREE(keeptr); return (void *)cur_salt; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } static int crypt_all(int *pcount, struct db_salt *salt) { int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index++) #endif { if(cur_salt->version == 2007) { unsigned char encryptionKey[256]; GeneratePasswordHashUsingSHA1(saved_key[index], saved_len[index], encryptionKey); cracked[index] = PasswordVerifier(encryptionKey); } else if (cur_salt->version == 2010) { unsigned char verifierKeys[64], decryptedVerifierHashInputBytes[16], decryptedVerifierHashBytes[32]; unsigned char hash[20]; SHA_CTX ctx; GenerateAgileEncryptionKey(saved_key[index], saved_len[index], cur_salt->keySize >> 3, verifierKeys); DecryptUsingSymmetricKeyAlgorithm(verifierKeys, cur_salt->encryptedVerifier, decryptedVerifierHashInputBytes, 16); DecryptUsingSymmetricKeyAlgorithm(&verifierKeys[32], cur_salt->encryptedVerifierHash, decryptedVerifierHashBytes, 32); SHA1_Init(&ctx); SHA1_Update(&ctx, decryptedVerifierHashInputBytes, 16); SHA1_Final(hash, &ctx); cracked[index] = !memcmp(hash, decryptedVerifierHashBytes, 20); } else if (cur_salt->version == 2013) { unsigned char verifierKeys[128], decryptedVerifierHashInputBytes[16], decryptedVerifierHashBytes[32]; unsigned char hash[64]; SHA512_CTX ctx; GenerateAgileEncryptionKey512(saved_key[index], saved_len[index], verifierKeys); DecryptUsingSymmetricKeyAlgorithm(verifierKeys, cur_salt->encryptedVerifier, decryptedVerifierHashInputBytes, 16); DecryptUsingSymmetricKeyAlgorithm(&verifierKeys[64], cur_salt->encryptedVerifierHash, decryptedVerifierHashBytes, 32); SHA512_Init(&ctx); SHA512_Update(&ctx, decryptedVerifierHashInputBytes, 16); SHA512_Final(hash, &ctx); cracked[index] = !memcmp(hash, decryptedVerifierHashBytes, 20); } } return count; } static int cmp_all(void *binary, int count) { int index; for (index = 0; index < count; index++) if (cracked[index]) return 1; return 0; } static int cmp_one(void *binary, int index) { return cracked[index]; } static int cmp_exact(char *source, int index) { return 1; } static void office_set_key(char *key, int index) { /* convert key to UTF-16LE */ saved_len[index] = enc_to_utf16(saved_key[index], PLAINTEXT_LENGTH, (UTF8*)key, strlen(key)); if (saved_len[index] < 0) saved_len[index] = strlen16(saved_key[index]); saved_len[index] <<= 1; } static char *get_key(int index) { return (char*)utf16_to_enc(saved_key[index]); } #if FMT_MAIN_VERSION > 11 /* * MS Office version (2007, 2010, 2013) as first tunable cost */ static unsigned int ms_office_version(void *salt) { struct custom_salt *my_salt; my_salt = salt; return (unsigned int) my_salt->version; } /* * Iteration count as second tunable cost * (hard coded value for MS Office version 2007) */ static unsigned int iteration_count(void *salt) { struct custom_salt *my_salt; my_salt = salt; if (my_salt->version == 2007) return MS_OFFICE_2007_ITERATIONS; else /* * Is spinCount always 100000, or just in our format tests? * Apparently, office2john.py extracts the spinCount from * the encrypted MS Office 2010/2013 document, * so it looks like that value can indeede vary. */ return (unsigned int) my_salt->spinCount; } #endif struct fmt_main fmt_office = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_UNICODE | FMT_UTF8, #if FMT_MAIN_VERSION > 11 { "MS Office version", "iteration count", }, #endif office_tests }, { init, fmt_default_done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, fmt_default_binary, get_salt, #if FMT_MAIN_VERSION > 11 { ms_office_version, iteration_count, }, #endif fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, set_salt, office_set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
GB_unaryop__ainv_bool_uint16.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__ainv_bool_uint16 // op(A') function: GB_tran__ainv_bool_uint16 // C type: bool // A type: uint16_t // cast: bool cij = (bool) aij // unaryop: cij = aij #define GB_ATYPE \ uint16_t #define GB_CTYPE \ bool // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, x) \ bool z = (bool) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_AINV || GxB_NO_BOOL || GxB_NO_UINT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__ainv_bool_uint16 ( bool *restrict Cx, const uint16_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__ainv_bool_uint16 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
1961.c
/* POLYBENCH/GPU-OPENMP * * This file is a part of the Polybench/GPU-OpenMP suite * * Contact: * William Killian <killian@udel.edu> * * Copyright 2013, The University of Delaware */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> /* Include polybench common header. */ #include <polybench.h> /* Include benchmark-specific header. */ /* Default data type is double, default size is 4000. */ #include "3mm.h" /* Array initialization. */ static void init_array(int ni, int nj, int nk, int nl, int nm, DATA_TYPE POLYBENCH_2D(A,NI,NK,ni,nk), DATA_TYPE POLYBENCH_2D(B,NK,NJ,nk,nj), DATA_TYPE POLYBENCH_2D(C,NJ,NM,nj,nm), DATA_TYPE POLYBENCH_2D(D,NM,NL,nm,nl)) { int i, j; for (i = 0; i < ni; i++) for (j = 0; j < nk; j++) A[i][j] = ((DATA_TYPE) i*j) / ni; for (i = 0; i < nk; i++) for (j = 0; j < nj; j++) B[i][j] = ((DATA_TYPE) i*(j+1)) / nj; for (i = 0; i < nj; i++) for (j = 0; j < nm; j++) C[i][j] = ((DATA_TYPE) i*(j+3)) / nl; for (i = 0; i < nm; i++) for (j = 0; j < nl; j++) D[i][j] = ((DATA_TYPE) i*(j+2)) / nk; } /* DCE code. Must scan the entire live-out data. Can be used also to check the correctness of the output. */ static void print_array(int ni, int nl, DATA_TYPE POLYBENCH_2D(G,NI,NL,ni,nl)) { int i, j; for (i = 0; i < ni; i++) for (j = 0; j < nl; j++) { fprintf (stderr, DATA_PRINTF_MODIFIER, G[i][j]); if ((i * ni + j) % 20 == 0) fprintf (stderr, "\n"); } fprintf (stderr, "\n"); } /* Main computational kernel. The whole function will be timed, including the call and return. */ static void kernel_3mm(int ni, int nj, int nk, int nl, int nm, DATA_TYPE POLYBENCH_2D(E,NI,NJ,ni,nj), DATA_TYPE POLYBENCH_2D(A,NI,NK,ni,nk), DATA_TYPE POLYBENCH_2D(B,NK,NJ,nk,nj), DATA_TYPE POLYBENCH_2D(F,NJ,NL,nj,nl), DATA_TYPE POLYBENCH_2D(C,NJ,NM,nj,nm), DATA_TYPE POLYBENCH_2D(D,NM,NL,nm,nl), DATA_TYPE POLYBENCH_2D(G,NI,NL,ni,nl)) { int i, j, k; #pragma scop #pragma omp parallel private (i, j, k) num_threads(#P11) { /* E := A*B */ #pragma omp parallel for schedule(static, 2) simd num_threads(2) for (i = 0; i < _PB_NI; i++) { #pragma omp parallel for schedule(static, 2) simd num_threads(2) for (j = 0; j < _PB_NJ; j++) { E[i][j] = 0; for (k = 0; k < _PB_NK; ++k) E[i][j] += A[i][k] * B[k][j]; } } /* F := C*D */ #pragma omp parallel for schedule(static, 2) simd num_threads(2) for (i = 0; i < _PB_NJ; i++) { #pragma omp parallel for schedule(static, 2) simd num_threads(2) for (j = 0; j < _PB_NL; j++) { F[i][j] = 0; for (k = 0; k < _PB_NM; ++k) F[i][j] += C[i][k] * D[k][j]; } } /* G := E*F */ #pragma omp parallel for schedule(static, 2) simd num_threads(2) for (i = 0; i < _PB_NI; i++) { #pragma omp parallel for schedule(static, 2) simd num_threads(2) for (j = 0; j < _PB_NL; j++) { G[i][j] = 0; for (k = 0; k < _PB_NJ; ++k) G[i][j] += E[i][k] * F[k][j]; } } } #pragma endscop } int main(int argc, char** argv) { /* Retrieve problem size. */ int ni = NI; int nj = NJ; int nk = NK; int nl = NL; int nm = NM; /* Variable declaration/allocation. */ POLYBENCH_2D_ARRAY_DECL(E, DATA_TYPE, NI, NJ, ni, nj); POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NI, NK, ni, nk); POLYBENCH_2D_ARRAY_DECL(B, DATA_TYPE, NK, NJ, nk, nj); POLYBENCH_2D_ARRAY_DECL(F, DATA_TYPE, NJ, NL, nj, nl); POLYBENCH_2D_ARRAY_DECL(C, DATA_TYPE, NJ, NM, nj, nm); POLYBENCH_2D_ARRAY_DECL(D, DATA_TYPE, NM, NL, nm, nl); POLYBENCH_2D_ARRAY_DECL(G, DATA_TYPE, NI, NL, ni, nl); /* Initialize array(s). */ init_array (ni, nj, nk, nl, nm, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(B), POLYBENCH_ARRAY(C), POLYBENCH_ARRAY(D)); /* Start timer. */ polybench_start_instruments; /* Run kernel. */ kernel_3mm (ni, nj, nk, nl, nm, POLYBENCH_ARRAY(E), POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(B), POLYBENCH_ARRAY(F), POLYBENCH_ARRAY(C), POLYBENCH_ARRAY(D), POLYBENCH_ARRAY(G)); /* Stop and print timer. */ polybench_stop_instruments; polybench_print_instruments; /* Prevent dead-code elimination. All live-out data must be printed by the function call in argument. */ polybench_prevent_dce(print_array(ni, nl, POLYBENCH_ARRAY(G))); /* Be clean. */ POLYBENCH_FREE_ARRAY(E); POLYBENCH_FREE_ARRAY(A); POLYBENCH_FREE_ARRAY(B); POLYBENCH_FREE_ARRAY(F); POLYBENCH_FREE_ARRAY(C); POLYBENCH_FREE_ARRAY(D); POLYBENCH_FREE_ARRAY(G); return 0; }
csr_matrix.c
/*BHEADER********************************************************************** * Copyright (c) 2008, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * This file is part of HYPRE. See file COPYRIGHT for details. * * HYPRE 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 dated February 1999. * * $Revision$ ***********************************************************************EHEADER*/ /****************************************************************************** * * Member functions for hypre_CSRMatrix class. * *****************************************************************************/ #include "seq_mv.h" #ifdef HYPRE_USING_GPU #include "gpukernels.h" #endif #ifdef HYPRE_PROFILE HYPRE_Real hypre_profile_times[HYPRE_TIMER_ID_COUNT] = { 0 }; #endif /*-------------------------------------------------------------------------- * hypre_CSRMatrixCreate *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_CSRMatrixCreate( HYPRE_Int num_rows, HYPRE_Int num_cols, HYPRE_Int num_nonzeros ) { hypre_CSRMatrix *matrix; matrix = hypre_CTAlloc(hypre_CSRMatrix, 1, HYPRE_MEMORY_HOST); hypre_CSRMatrixData(matrix) = NULL; hypre_CSRMatrixI(matrix) = NULL; hypre_CSRMatrixJ(matrix) = NULL; hypre_CSRMatrixBigJ(matrix) = NULL; hypre_CSRMatrixRownnz(matrix) = NULL; hypre_CSRMatrixNumRows(matrix) = num_rows; hypre_CSRMatrixNumCols(matrix) = num_cols; hypre_CSRMatrixNumNonzeros(matrix) = num_nonzeros; /* set defaults */ hypre_CSRMatrixOwnsData(matrix) = 1; hypre_CSRMatrixNumRownnz(matrix) = num_rows; #ifdef HYPRE_USING_UNIFIED_MEMORY matrix->on_device=0; #endif #ifdef HYPRE_USING_MAPPED_OPENMP_OFFLOAD matrix->mapped=-1; #endif #ifdef HYPRE_BIGINT matrix->i_short=NULL; matrix->j_short=NULL; #endif return matrix; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixDestroy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixDestroy( hypre_CSRMatrix *matrix ) { HYPRE_Int ierr=0; if (matrix) { #ifdef HYPRE_USING_MAPPED_OPENMP_OFFLOAD hypre_CSRMatrixUnMapFromDevice(matrix); #endif hypre_TFree(hypre_CSRMatrixI(matrix), HYPRE_MEMORY_SHARED); hypre_CSRMatrixI(matrix) = NULL; if (hypre_CSRMatrixRownnz(matrix)) hypre_TFree(hypre_CSRMatrixRownnz(matrix), HYPRE_MEMORY_SHARED); if ( hypre_CSRMatrixOwnsData(matrix) ) { hypre_TFree(hypre_CSRMatrixData(matrix), HYPRE_MEMORY_SHARED); if (hypre_CSRMatrixJ(matrix)) hypre_TFree(hypre_CSRMatrixJ(matrix), HYPRE_MEMORY_SHARED); if (hypre_CSRMatrixBigJ(matrix)) hypre_TFree(hypre_CSRMatrixBigJ(matrix), HYPRE_MEMORY_SHARED); hypre_CSRMatrixData(matrix) = NULL; hypre_CSRMatrixJ(matrix) = NULL; } hypre_TFree(matrix, HYPRE_MEMORY_HOST); matrix = NULL; } return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixInitialize *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixInitialize( hypre_CSRMatrix *matrix ) { HYPRE_Int num_rows = hypre_CSRMatrixNumRows(matrix); HYPRE_Int num_nonzeros = hypre_CSRMatrixNumNonzeros(matrix); /* HYPRE_Int num_rownnz = hypre_CSRMatrixNumRownnz(matrix); */ HYPRE_Int ierr=0; if ( ! hypre_CSRMatrixData(matrix) && num_nonzeros ) hypre_CSRMatrixData(matrix) = hypre_CTAlloc(HYPRE_Complex, num_nonzeros, HYPRE_MEMORY_SHARED); else { //if (PointerAttributes(hypre_CSRMatrixData(matrix))==HYPRE_HOST_POINTER) printf("MATREIX INITIAL WITH JHOST DATA\n"); } if ( ! hypre_CSRMatrixI(matrix) ) hypre_CSRMatrixI(matrix) = hypre_CTAlloc(HYPRE_Int, num_rows + 1, HYPRE_MEMORY_SHARED); /* if ( ! hypre_CSRMatrixRownnz(matrix) ) hypre_CSRMatrixRownnz(matrix) = hypre_CTAlloc(HYPRE_Int, num_rownnz, HYPRE_MEMORY_SHARED);*/ if ( ! hypre_CSRMatrixJ(matrix) && num_nonzeros ) hypre_CSRMatrixJ(matrix) = hypre_CTAlloc(HYPRE_Int, num_nonzeros, HYPRE_MEMORY_SHARED); return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixBigInitialize *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixBigInitialize( hypre_CSRMatrix *matrix ) { HYPRE_Int num_rows = hypre_CSRMatrixNumRows(matrix); HYPRE_Int num_nonzeros = hypre_CSRMatrixNumNonzeros(matrix); /* HYPRE_Int num_rownnz = hypre_CSRMatrixNumRownnz(matrix); */ HYPRE_Int ierr=0; if ( ! hypre_CSRMatrixData(matrix) && num_nonzeros ) hypre_CSRMatrixData(matrix) = hypre_CTAlloc(HYPRE_Complex, num_nonzeros, HYPRE_MEMORY_SHARED); else { //if (PointerAttributes(hypre_CSRMatrixData(matrix))==HYPRE_HOST_POINTER) printf("MATREIX INITIAL WITH JHOST DATA\n"); } if ( ! hypre_CSRMatrixI(matrix) ) hypre_CSRMatrixI(matrix) = hypre_CTAlloc(HYPRE_Int, num_rows + 1, HYPRE_MEMORY_SHARED); /* if ( ! hypre_CSRMatrixRownnz(matrix) ) hypre_CSRMatrixRownnz(matrix) = hypre_CTAlloc(HYPRE_Int, num_rownnz, HYPRE_MEMORY_SHARED);*/ if ( ! hypre_CSRMatrixBigJ(matrix) && num_nonzeros ) hypre_CSRMatrixBigJ(matrix) = hypre_CTAlloc(HYPRE_BigInt, num_nonzeros, HYPRE_MEMORY_SHARED); return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixBigJtoJ *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixBigJtoJ( hypre_CSRMatrix *matrix ) { HYPRE_Int num_nonzeros = hypre_CSRMatrixNumNonzeros(matrix); HYPRE_BigInt *matrix_big_j = hypre_CSRMatrixBigJ(matrix); HYPRE_Int *matrix_j = NULL; HYPRE_Int i; /* HYPRE_Int num_rownnz = hypre_CSRMatrixNumRownnz(matrix); */ HYPRE_Int ierr=0; if (num_nonzeros && matrix_big_j ) { matrix_j = hypre_CTAlloc(HYPRE_Int, num_nonzeros, HYPRE_MEMORY_SHARED); for (i=0; i < num_nonzeros; i++) matrix_j[i] = (HYPRE_Int) matrix_big_j[i]; hypre_CSRMatrixJ(matrix) = matrix_j; hypre_TFree(matrix_big_j, HYPRE_MEMORY_SHARED); hypre_CSRMatrixBigJ(matrix) = NULL; } return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixJtoBigJ *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixJtoBigJ( hypre_CSRMatrix *matrix ) { HYPRE_Int num_nonzeros = hypre_CSRMatrixNumNonzeros(matrix); HYPRE_Int *matrix_j = hypre_CSRMatrixJ(matrix); HYPRE_BigInt *matrix_big_j = NULL; HYPRE_Int i; /* HYPRE_Int num_rownnz = hypre_CSRMatrixNumRownnz(matrix); */ HYPRE_Int ierr=0; if (num_nonzeros && matrix_j ) { matrix_big_j = hypre_CTAlloc(HYPRE_BigInt, num_nonzeros, HYPRE_MEMORY_SHARED); for (i=0; i < num_nonzeros; i++) matrix_big_j[i] = (HYPRE_BigInt) matrix_j[i]; hypre_CSRMatrixBigJ(matrix) = matrix_big_j; hypre_TFree(matrix_j, HYPRE_MEMORY_SHARED); hypre_CSRMatrixJ(matrix) = NULL; } return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixSetDataOwner *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixSetDataOwner( hypre_CSRMatrix *matrix, HYPRE_Int owns_data ) { HYPRE_Int ierr=0; hypre_CSRMatrixOwnsData(matrix) = owns_data; return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixSetRownnz * * function to set the substructure rownnz and num_rowsnnz inside the CSRMatrix * it needs the A_i substructure of CSRMatrix to find the nonzero rows. * It runs after the create CSR and when A_i is known..It does not check for * the existence of A_i or of the CSR matrix. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixSetRownnz( hypre_CSRMatrix *matrix ) { HYPRE_Int ierr=0; HYPRE_Int num_rows = hypre_CSRMatrixNumRows(matrix); HYPRE_Int *A_i = hypre_CSRMatrixI(matrix); HYPRE_Int *Arownnz; HYPRE_Int i, adiag; HYPRE_Int irownnz=0; for (i=0; i < num_rows; i++) { adiag = (A_i[i+1] - A_i[i]); if(adiag > 0) irownnz++; } hypre_CSRMatrixNumRownnz(matrix) = irownnz; if ((irownnz == 0) || (irownnz == num_rows)) { hypre_CSRMatrixRownnz(matrix) = NULL; } else { Arownnz = hypre_CTAlloc(HYPRE_Int, irownnz, HYPRE_MEMORY_SHARED); irownnz = 0; for (i=0; i < num_rows; i++) { adiag = A_i[i+1]-A_i[i]; if(adiag > 0) Arownnz[irownnz++] = i; } hypre_CSRMatrixRownnz(matrix) = Arownnz; } return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixRead *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_CSRMatrixRead( char *file_name ) { hypre_CSRMatrix *matrix; FILE *fp; HYPRE_Complex *matrix_data; HYPRE_Int *matrix_i; HYPRE_Int *matrix_j; HYPRE_Int num_rows; HYPRE_Int num_nonzeros; HYPRE_Int max_col = 0; HYPRE_Int file_base = 1; HYPRE_Int j; /*---------------------------------------------------------- * Read in the data *----------------------------------------------------------*/ fp = fopen(file_name, "r"); hypre_fscanf(fp, "%d", &num_rows); matrix_i = hypre_CTAlloc(HYPRE_Int, num_rows + 1, HYPRE_MEMORY_SHARED); for (j = 0; j < num_rows+1; j++) { hypre_fscanf(fp, "%d", &matrix_i[j]); matrix_i[j] -= file_base; } num_nonzeros = matrix_i[num_rows]; matrix = hypre_CSRMatrixCreate(num_rows, num_rows, matrix_i[num_rows]); hypre_CSRMatrixI(matrix) = matrix_i; hypre_CSRMatrixInitialize(matrix); matrix_j = hypre_CSRMatrixJ(matrix); for (j = 0; j < num_nonzeros; j++) { hypre_fscanf(fp, "%d", &matrix_j[j]); matrix_j[j] -= file_base; if (matrix_j[j] > max_col) { max_col = matrix_j[j]; } } matrix_data = hypre_CSRMatrixData(matrix); for (j = 0; j < matrix_i[num_rows]; j++) { hypre_fscanf(fp, "%le", &matrix_data[j]); } fclose(fp); hypre_CSRMatrixNumNonzeros(matrix) = num_nonzeros; hypre_CSRMatrixNumCols(matrix) = ++max_col; return matrix; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixPrint *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixPrint( hypre_CSRMatrix *matrix, char *file_name ) { FILE *fp; HYPRE_Complex *matrix_data; HYPRE_Int *matrix_i; HYPRE_Int *matrix_j; HYPRE_Int num_rows; HYPRE_Int file_base = 1; HYPRE_Int j; HYPRE_Int ierr = 0; /*---------------------------------------------------------- * Print the matrix data *----------------------------------------------------------*/ matrix_data = hypre_CSRMatrixData(matrix); matrix_i = hypre_CSRMatrixI(matrix); matrix_j = hypre_CSRMatrixJ(matrix); num_rows = hypre_CSRMatrixNumRows(matrix); fp = fopen(file_name, "w"); hypre_fprintf(fp, "%d\n", num_rows); for (j = 0; j <= num_rows; j++) { hypre_fprintf(fp, "%d\n", matrix_i[j] + file_base); } for (j = 0; j < matrix_i[num_rows]; j++) { hypre_fprintf(fp, "%d\n", matrix_j[j] + file_base); } if (matrix_data) { for (j = 0; j < matrix_i[num_rows]; j++) { #ifdef HYPRE_COMPLEX hypre_fprintf(fp, "%.14e , %.14e\n", hypre_creal(matrix_data[j]), hypre_cimag(matrix_data[j])); #else hypre_fprintf(fp, "%.14e\n", matrix_data[j]); #endif } } else { hypre_fprintf(fp, "Warning: No matrix data!\n"); } fclose(fp); return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixPrintHB: print a CSRMatrix in Harwell-Boeing format *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixPrintHB( hypre_CSRMatrix *matrix_input, char *file_name ) { FILE *fp; hypre_CSRMatrix *matrix; HYPRE_Complex *matrix_data; HYPRE_Int *matrix_i; HYPRE_Int *matrix_j; HYPRE_Int num_rows; HYPRE_Int file_base = 1; HYPRE_Int j, totcrd, ptrcrd, indcrd, valcrd, rhscrd; HYPRE_Int ierr = 0; /*---------------------------------------------------------- * Print the matrix data *----------------------------------------------------------*/ /* First transpose the input matrix, since HB is in CSC format */ hypre_CSRMatrixTranspose(matrix_input, &matrix, 1); matrix_data = hypre_CSRMatrixData(matrix); matrix_i = hypre_CSRMatrixI(matrix); matrix_j = hypre_CSRMatrixJ(matrix); num_rows = hypre_CSRMatrixNumRows(matrix); fp = fopen(file_name, "w"); hypre_fprintf(fp, "%-70s Key \n", "Title"); ptrcrd = num_rows; indcrd = matrix_i[num_rows]; valcrd = matrix_i[num_rows]; rhscrd = 0; totcrd = ptrcrd + indcrd + valcrd + rhscrd; hypre_fprintf (fp, "%14d%14d%14d%14d%14d\n", totcrd, ptrcrd, indcrd, valcrd, rhscrd); hypre_fprintf (fp, "%-14s%14i%14i%14i%14i\n", "RUA", num_rows, num_rows, valcrd, 0); hypre_fprintf (fp, "%-16s%-16s%-16s%26s\n", "(1I8)", "(1I8)", "(1E16.8)", ""); for (j = 0; j <= num_rows; j++) { hypre_fprintf(fp, "%8d\n", matrix_i[j] + file_base); } for (j = 0; j < matrix_i[num_rows]; j++) { hypre_fprintf(fp, "%8d\n", matrix_j[j] + file_base); } if (matrix_data) { for (j = 0; j < matrix_i[num_rows]; j++) { #ifdef HYPRE_COMPLEX hypre_fprintf(fp, "%16.8e , %16.8e\n", hypre_creal(matrix_data[j]), hypre_cimag(matrix_data[j])); #else hypre_fprintf(fp, "%16.8e\n", matrix_data[j]); #endif } } else { hypre_fprintf(fp, "Warning: No matrix data!\n"); } fclose(fp); hypre_CSRMatrixDestroy(matrix); return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixCopy: * copys A to B, * if copy_data = 0 only the structure of A is copied to B. * the routine does not check if the dimensions of A and B match !!! *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixCopy( hypre_CSRMatrix *A, hypre_CSRMatrix *B, HYPRE_Int copy_data ) { HYPRE_Int ierr=0; HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Complex *A_data; HYPRE_Int *B_i = hypre_CSRMatrixI(B); HYPRE_Int *B_j = hypre_CSRMatrixJ(B); HYPRE_Complex *B_data; HYPRE_Int num_nonzeros = hypre_CSRMatrixNumNonzeros(A); HYPRE_Int i, j; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i=0; i <= num_rows; i++) { B_i[i] = A_i[i]; } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_nonzeros; ++j) { B_j[j] = A_j[j]; } if (copy_data) { A_data = hypre_CSRMatrixData(A); B_data = hypre_CSRMatrixData(B); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j=0; j < num_nonzeros; j++) { B_data[j] = A_data[j]; } } return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixClone * Creates and returns a new copy of the argument, A. * Data is not copied, only structural information is reproduced. * Copying is a deep copy in that no pointers are copied; new arrays are * created where necessary. *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_CSRMatrixClone( hypre_CSRMatrix * A ) { HYPRE_Int num_rows = hypre_CSRMatrixNumRows( A ); HYPRE_Int num_cols = hypre_CSRMatrixNumCols( A ); HYPRE_Int num_nonzeros = hypre_CSRMatrixNumNonzeros( A ); hypre_CSRMatrix * B = hypre_CSRMatrixCreate( num_rows, num_cols, num_nonzeros ); HYPRE_Int * A_i; HYPRE_Int * A_j; HYPRE_Int * B_i; HYPRE_Int * B_j; HYPRE_Int i, j; hypre_CSRMatrixInitialize( B ); A_i = hypre_CSRMatrixI(A); A_j = hypre_CSRMatrixJ(A); B_i = hypre_CSRMatrixI(B); B_j = hypre_CSRMatrixJ(B); for ( i=0; i<num_rows+1; ++i ) B_i[i] = A_i[i]; for ( j=0; j<num_nonzeros; ++j ) B_j[j] = A_j[j]; hypre_CSRMatrixNumRownnz(B) = hypre_CSRMatrixNumRownnz(A); if ( hypre_CSRMatrixRownnz(A) ) hypre_CSRMatrixSetRownnz( B ); return B; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixUnion * Creates and returns a matrix whose elements are the union of those of A and B. * Data is not computed, only structural information is created. * A and B must have the same numbers of rows. * Nothing is done about Rownnz. * * If col_map_offd_A and col_map_offd_B are zero, A and B are expected to have * the same column indexing. Otherwise, col_map_offd_A, col_map_offd_B should * be the arrays of that name from two ParCSRMatrices of which A and B are the * offd blocks. * * The algorithm can be expected to have reasonable efficiency only for very * sparse matrices (many rows, few nonzeros per row). * The nonzeros of a computed row are NOT necessarily in any particular order. *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_CSRMatrixUnion( hypre_CSRMatrix *A, hypre_CSRMatrix *B, HYPRE_BigInt *col_map_offd_A, HYPRE_BigInt *col_map_offd_B, HYPRE_BigInt **col_map_offd_C ) { HYPRE_Int num_rows = hypre_CSRMatrixNumRows( A ); HYPRE_Int num_cols_A = hypre_CSRMatrixNumCols( A ); HYPRE_Int num_cols_B = hypre_CSRMatrixNumCols( B ); HYPRE_Int num_cols; HYPRE_Int num_nonzeros; HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int *B_i = hypre_CSRMatrixI(B); HYPRE_Int *B_j = hypre_CSRMatrixJ(B); HYPRE_Int *C_i; HYPRE_Int *C_j; HYPRE_Int *jC = NULL; HYPRE_BigInt jBg, big_jA, big_jB; HYPRE_Int i, jA, jB; HYPRE_Int ma, mb, mc, ma_min, ma_max, match; hypre_CSRMatrix * C; hypre_assert( num_rows == hypre_CSRMatrixNumRows(B) ); if ( col_map_offd_B ) hypre_assert( col_map_offd_A ); if ( col_map_offd_A ) hypre_assert( col_map_offd_B ); /* ==== First, go through the columns of A and B to count the columns of C. */ if ( col_map_offd_A==0 ) { /* The matrices are diagonal blocks. Normally num_cols_A==num_cols_B, col_starts is the same, etc. */ num_cols = hypre_max( num_cols_A, num_cols_B ); } else { /* The matrices are offdiagonal blocks. */ jC = hypre_CTAlloc( HYPRE_Int, num_cols_B , HYPRE_MEMORY_SHARED); num_cols = num_cols_A; /* initialization; we'll compute the actual value */ for ( jB=0; jB<num_cols_B; ++jB ) { match = 0; jBg = col_map_offd_B[jB]; for ( ma=0; ma<num_cols_A; ++ma ) { if ( col_map_offd_A[ma]==jBg ) match = 1; } if ( match==0 ) { jC[jB] = num_cols; ++num_cols; } } } /* ==== If we're working on a ParCSRMatrix's offd block, make and load col_map_offd_C */ if ( col_map_offd_A ) { *col_map_offd_C = hypre_CTAlloc( HYPRE_BigInt, num_cols , HYPRE_MEMORY_SHARED); for ( jA=0; jA<num_cols_A; ++jA ) (*col_map_offd_C)[jA] = col_map_offd_A[jA]; for ( jB=0; jB<num_cols_B; ++jB ) { match = 0; jBg = col_map_offd_B[jB]; for ( ma=0; ma<num_cols_A; ++ma ) { if ( col_map_offd_A[ma]==jBg ) match = 1; } if ( match==0 ) (*col_map_offd_C)[ jC[jB] ] = jBg; } } /* ==== The first run through A and B is to count the number of nonzero elements, without HYPRE_Complex-counting duplicates. Then we can create C. */ num_nonzeros = hypre_CSRMatrixNumNonzeros(A); for ( i=0; i<num_rows; ++i ) { ma_min = A_i[i]; ma_max = A_i[i+1]; for ( mb=B_i[i]; mb<B_i[i+1]; ++mb ) { jB = B_j[mb]; if ( col_map_offd_B ) big_jB = col_map_offd_B[jB]; match = 0; for ( ma=ma_min; ma<ma_max; ++ma ) { jA = A_j[ma]; if ( col_map_offd_A ) big_jA = col_map_offd_A[jA]; if ( big_jB == big_jA ) { match = 1; if( ma==ma_min ) ++ma_min; break; } } if ( match==0 ) ++num_nonzeros; } } C = hypre_CSRMatrixCreate( num_rows, num_cols, num_nonzeros ); hypre_CSRMatrixInitialize( C ); /* ==== The second run through A and B is to pick out the column numbers for each row, and put them in C. */ C_i = hypre_CSRMatrixI(C); C_i[0] = 0; C_j = hypre_CSRMatrixJ(C); mc = 0; for ( i=0; i<num_rows; ++i ) { ma_min = A_i[i]; ma_max = A_i[i+1]; for ( ma=ma_min; ma<ma_max; ++ma ) { C_j[mc] = A_j[ma]; ++mc; } for ( mb=B_i[i]; mb<B_i[i+1]; ++mb ) { jB = B_j[mb]; if ( col_map_offd_B ) big_jB = col_map_offd_B[jB]; match = 0; for ( ma=ma_min; ma<ma_max; ++ma ) { jA = A_j[ma]; if ( col_map_offd_A ) big_jA = col_map_offd_A[jA]; if ( big_jB == big_jA ) { match = 1; if( ma==ma_min ) ++ma_min; break; } } if ( match==0 ) { if ( col_map_offd_A ) C_j[mc] = jC[ B_j[mb] ]; else C_j[mc] = B_j[mb]; /* ... I don't know whether column indices are required to be in any particular order. If so, we'll need to sort. */ ++mc; } } C_i[i+1] = mc; } hypre_assert( mc == num_nonzeros ); if (jC) hypre_TFree( jC , HYPRE_MEMORY_SHARED); return C; } static HYPRE_Int hypre_CSRMatrixGetLoadBalancedPartitionBoundary(hypre_CSRMatrix *A, HYPRE_Int idx) { HYPRE_Int num_nonzerosA = hypre_CSRMatrixNumNonzeros(A); HYPRE_Int num_rowsA = hypre_CSRMatrixNumRows(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int num_threads = hypre_NumActiveThreads(); HYPRE_Int nonzeros_per_thread = (num_nonzerosA + num_threads - 1)/num_threads; if (idx <= 0) { return 0; } else if (idx >= num_threads) { return num_rowsA; } else { return (HYPRE_Int)(hypre_LowerBound(A_i, A_i + num_rowsA, nonzeros_per_thread*idx) - A_i); } } HYPRE_Int hypre_CSRMatrixGetLoadBalancedPartitionBegin(hypre_CSRMatrix *A) { return hypre_CSRMatrixGetLoadBalancedPartitionBoundary(A, hypre_GetThreadNum()); } HYPRE_Int hypre_CSRMatrixGetLoadBalancedPartitionEnd(hypre_CSRMatrix *A) { return hypre_CSRMatrixGetLoadBalancedPartitionBoundary(A, hypre_GetThreadNum() + 1); } #ifdef HYPRE_USING_UNIFIED_MEMORY void hypre_CSRMatrixPrefetchToDevice(hypre_CSRMatrix *A){ if (hypre_CSRMatrixNumNonzeros(A)==0) return; PUSH_RANGE_PAYLOAD("hypre_CSRMatrixPrefetchToDevice",0,hypre_CSRMatrixNumNonzeros(A)); if ((!A->on_device)&&(hypre_CSRMatrixNumNonzeros(A)>8192)){ //printf("Pointer type %d value = %p\n",PointerAttributes((hypre_CSRMatrixI(A))),hypre_CSRMatrixI(A)); #if defined(TRACK_MEMORY_ALLOCATIONS) ASSERT_MANAGED(hypre_CSRMatrixData(A)); ASSERT_MANAGED(hypre_CSRMatrixI(A)); ASSERT_MANAGED(hypre_CSRMatrixJ(A)); #endif hypre_CheckErrorDevice(cudaMemPrefetchAsync(hypre_CSRMatrixData(A),hypre_CSRMatrixNumNonzeros(A)*sizeof(HYPRE_Complex),HYPRE_DEVICE,HYPRE_STREAM(4))); hypre_CheckErrorDevice(cudaMemPrefetchAsync(hypre_CSRMatrixI(A),(hypre_CSRMatrixNumRows(A)+1)*sizeof(HYPRE_Int),HYPRE_DEVICE,HYPRE_STREAM(5))); hypre_CheckErrorDevice(cudaMemPrefetchAsync(hypre_CSRMatrixJ(A),hypre_CSRMatrixNumNonzeros(A)*sizeof(HYPRE_Int),HYPRE_DEVICE,HYPRE_STREAM(6))); hypre_CheckErrorDevice(cudaStreamSynchronize(HYPRE_STREAM(4))); hypre_CheckErrorDevice(cudaStreamSynchronize(HYPRE_STREAM(5))); hypre_CheckErrorDevice(cudaStreamSynchronize(HYPRE_STREAM(6))); #ifdef HYPRE_USING_OPENMP_OFFLOAD A->on_device=0; // Should be 1 for CUDA code. 0 for OMP for now #else A->on_device=1; #endif } POP_RANGE; } void hypre_CSRMatrixPrefetchToDeviceBIGINT(hypre_CSRMatrix *A){ if (hypre_CSRMatrixNumNonzeros(A)==0) return; PUSH_RANGE_PAYLOAD("hypre_CSRMatrixPrefetchToDevice",0,hypre_CSRMatrixNumNonzeros(A)); if ((!A->on_device)&&(hypre_CSRMatrixNumNonzeros(A)>8192)){ //printf("Pointer type %d value = %p\n",PointerAttributes((hypre_CSRMatrixI(A))),hypre_CSRMatrixI(A)); #if defined(TRACK_MEMORY_ALLOCATIONS) ASSERT_MANAGED(hypre_CSRMatrixData(A)); ASSERT_MANAGED(hypre_CSRMatrixI(A)); ASSERT_MANAGED(hypre_CSRMatrixJ(A)); #endif hypre_CheckErrorDevice(cudaMemPrefetchAsync(hypre_CSRMatrixData(A),hypre_CSRMatrixNumNonzeros(A)*sizeof(HYPRE_Complex),HYPRE_DEVICE,HYPRE_STREAM(4))); hypre_CheckErrorDevice(cudaMemPrefetchAsync(hypre_CSRMatrixI(A),(hypre_CSRMatrixNumRows(A)+1)*sizeof(HYPRE_Int),HYPRE_DEVICE,HYPRE_STREAM(5))); hypre_CheckErrorDevice(cudaMemPrefetchAsync(hypre_CSRMatrixJ(A),hypre_CSRMatrixNumNonzeros(A)*sizeof(HYPRE_Int),HYPRE_DEVICE,HYPRE_STREAM(6))); hypre_CheckErrorDevice(cudaStreamSynchronize(HYPRE_STREAM(4))); hypre_CheckErrorDevice(cudaStreamSynchronize(HYPRE_STREAM(5))); hypre_CheckErrorDevice(cudaStreamSynchronize(HYPRE_STREAM(6))); #ifdef HYPRE_USING_OPENMP_OFFLOAD A->on_device=0; // Should be 1 for CUDA code. 0 for OMP for now #else A->on_device=1; #endif } POP_RANGE; } void hypre_CSRMatrixPrefetchToHost(hypre_CSRMatrix *A){ PUSH_RANGE("hypre_CSRMatrixPrefetchToDevice",0); if (A->on_device){ A->on_device=0; hypre_CheckErrorDevice(cudaMemPrefetchAsync(hypre_CSRMatrixData(A),hypre_CSRMatrixNumNonzeros(A)*sizeof(HYPRE_Complex),cudaCpuDeviceId,HYPRE_STREAM(4))); hypre_CheckErrorDevice(cudaMemPrefetchAsync(hypre_CSRMatrixI(A),(hypre_CSRMatrixNumRows(A)+1)*sizeof(HYPRE_Int),cudaCpuDeviceId,HYPRE_STREAM(4))); hypre_CheckErrorDevice(cudaMemPrefetchAsync(hypre_CSRMatrixJ(A),hypre_CSRMatrixNumNonzeros(A)*sizeof(HYPRE_Int),cudaCpuDeviceId,HYPRE_STREAM(4))); hypre_CheckErrorDevice(cudaStreamSynchronize(HYPRE_STREAM(4))); } POP_RANGE; } hypre_int hypre_CSRMatrixIsManaged(hypre_CSRMatrix *a){ return ((pointerIsManaged((void*)hypre_CSRMatrixData(a))) && (pointerIsManaged((void*)hypre_CSRMatrixI(a))) && (pointerIsManaged((void*)hypre_CSRMatrixJ(a)))); } #endif #ifdef HYPRE_USING_MAPPED_OPENMP_OFFLOAD void hypre_CSRMatrixMapToDevice(hypre_CSRMatrix *A){ if (A==NULL) return; HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A); HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A); HYPRE_Int nnz = hypre_CSRMatrixNumNonzeros(A); //printf("MAPPED %p sizes = %d %d \n",A,nnz,num_rows); #pragma omp target enter data map(to:A[0:0]) #pragma omp target enter data map(alloc:A_data[:nnz]) if (nnz>0) #pragma omp target enter data map(alloc:A_i[:num_rows+1]) if (num_rows>0) #pragma omp target enter data map(alloc:A_j[:nnz]) if (nnz>0) A->mapped=0; } void hypre_CSRMatrixUpdateToDevice(hypre_CSRMatrix *A){ if (A==NULL) return; HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A); HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A); HYPRE_Int nnz = hypre_CSRMatrixNumNonzeros(A); //printf("Updating MAtrix...%p \n",A); //#pragma omp target update device(0) to(A[0:0]) //printf("Updating MAtrix data...%p %d\n",A_data,nnz); #pragma omp target update device(0) to(A_data[:nnz]) if (nnz>0) //printf("Updating MAtrix I ...%p %d\n",A_i,num_rows); #pragma omp target update device(0) to(A_i[:num_rows+1]) if (num_rows>0) //printf("Updating MAtrix J ...%p %d\n",A_j,nnz); #pragma omp target update device(0) to(A_j[:nnz]) if (nnz>0) A->mapped=1; //printf("Done \n"); } void hypre_CSRMatrixUnMapFromDevice(hypre_CSRMatrix *A){ HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A); HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A); HYPRE_Int nnz = hypre_CSRMatrixNumNonzeros(A); //#pragma omp target exit data map(delete:A[0:0]) #pragma omp target exit data map(delete:A_data[0:nnz]) if (nnz>0) #pragma omp target exit data map(delete:A_i[0:num_rows+1]) if (num_rows>0) #pragma omp target exit data map(delete:A_j[0:nnz]) if (nnz>0) } #endif
GB_binop__div_fc32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__div_fc32 // A.*B function (eWiseMult): GB_AemultB__div_fc32 // A*D function (colscale): GB_AxD__div_fc32 // D*A function (rowscale): GB_DxB__div_fc32 // C+=B function (dense accum): GB_Cdense_accumB__div_fc32 // C+=b function (dense accum): GB_Cdense_accumb__div_fc32 // C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__div_fc32 // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__div_fc32 // C=scalar+B GB_bind1st__div_fc32 // C=scalar+B' GB_bind1st_tran__div_fc32 // C=A+scalar GB_bind2nd__div_fc32 // C=A'+scalar GB_bind2nd_tran__div_fc32 // C type: GxB_FC32_t // A type: GxB_FC32_t // B,b type: GxB_FC32_t // BinaryOp: cij = GB_FC32_div (aij, bij) #define GB_ATYPE \ GxB_FC32_t #define GB_BTYPE \ GxB_FC32_t #define GB_CTYPE \ GxB_FC32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ GxB_FC32_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ GxB_FC32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = GB_FC32_div (x, y) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_DIV || GxB_NO_FC32 || GxB_NO_DIV_FC32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB_Cdense_ewise3_accum__div_fc32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__div_fc32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__div_fc32 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__div_fc32 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type GxB_FC32_t GxB_FC32_t bwork = (*((GxB_FC32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__div_fc32 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t *GB_RESTRICT Cx = (GxB_FC32_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__div_fc32 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t *GB_RESTRICT Cx = (GxB_FC32_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__div_fc32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__div_fc32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__div_fc32 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ; GxB_FC32_t x = (*((GxB_FC32_t *) x_input)) ; GxB_FC32_t *Bx = (GxB_FC32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC32_t bij = Bx [p] ; Cx [p] = GB_FC32_div (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__div_fc32 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ; GxB_FC32_t *Ax = (GxB_FC32_t *) Ax_input ; GxB_FC32_t y = (*((GxB_FC32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC32_t aij = Ax [p] ; Cx [p] = GB_FC32_div (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ GxB_FC32_t aij = Ax [pA] ; \ Cx [pC] = GB_FC32_div (x, aij) ; \ } GrB_Info GB_bind1st_tran__div_fc32 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ GxB_FC32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t x = (*((const GxB_FC32_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ GxB_FC32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ GxB_FC32_t aij = Ax [pA] ; \ Cx [pC] = GB_FC32_div (aij, y) ; \ } GrB_Info GB_bind2nd_tran__div_fc32 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t y = (*((const GxB_FC32_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
blockchain_fmt_plug.c
/* blockchain "My Wallet" cracker patch for JtR. Hacked together during June of * 2013 by Dhiru Kholia <dhiru at openwall.com>. * * See https://blockchain.info/wallet/wallet-format * * This software is Copyright (c) 2013 Dhiru Kholia <dhiru at openwall.com>, * and it is hereby released to the general public under the following terms: * * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * improved dection, added iteration count and handle v2 hashes, Feb, 2015, JimF. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_blockchain; #elif FMT_REGISTERS_H john_register_one(&fmt_blockchain); #else #include <string.h> #include <errno.h> #include "arch.h" #include "jumbo.h" #include "common.h" #include "formats.h" #include "params.h" #include "options.h" #include "johnswap.h" #include "pbkdf2_hmac_sha1.h" #include "aes.h" #ifdef _OPENMP #include <omp.h> //#define OMP_SCALE 1 // tuned on core i7 #ifndef OMP_SCALE #define OMP_SCALE 64 // tuned on AMD K8 dual-HT (XOP) #endif #endif #include "memdbg.h" #define FORMAT_LABEL "Blockchain" #define FORMAT_NAME "My Wallet" #define FORMAT_TAG "$blockchain$" #define TAG_LENGTH 12 #ifdef SIMD_COEF_32 #define ALGORITHM_NAME "PBKDF2-SHA1 AES " SHA1_ALGORITHM_NAME #else #define ALGORITHM_NAME "PBKDF2-SHA1 AES 32/" ARCH_BITS_STR #endif #define BENCHMARK_COMMENT " (x10)" #define BENCHMARK_LENGTH -1 #define BINARY_SIZE 0 #define BINARY_ALIGN 1 #define PLAINTEXT_LENGTH 125 #define SALT_SIZE sizeof(struct custom_salt) #define SALT_ALIGN 4 #ifdef SIMD_COEF_32 #define MIN_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA1 #define MAX_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA1 #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif #define BIG_ENOUGH (8192 * 32) // increase me (in multiples of 16) to increase the decrypted and search area #define SAFETY_FACTOR 160 static struct fmt_tests agile_keychain_tests[] = { {"$blockchain$400$53741f25a90ef521c90bb2fd73673e64089ff2cca6ba3cbf6f34e0f80f960b2f60b9ac48df009dc30c288dcf1ade5f16c70a3536403fc11a68f242ba5ad3fcceae3ca5ecd23905997474260aa1357fc322b1434ffa026ba6ad33707c9ad5260e7230b87d8888a45ddc27513adb30af8755ec0737963ae6bb281318c48f224e9c748f6697f75f63f718bebb3401d6d5f02cf62b1701c205762c2f43119b68771ed10ddab79b5f74f56d611f61f77b8b65b5b5669756017429633118b8e5b8b638667e44154de4cc76468c4200eeebda2711a65333a7e3c423c8241e219cdca5ac47c0d4479444241fa27da20dba1a1d81e778a037d40d33ddea7c39e6d02461d97185f66a73deedff39bc53af0e9b04a3d7bf43648303c9f652d99630cd0789819376d68443c85f0eeb7af7c83eecddf25ea912f7721e3fb73ccaedf860f0f033ffc990ed73db441220d0cbe6e029676fef264dc2dc497f39bedf4041ba355d086134744d5a36e09515d230cd499eb20e0c574fb1bd9d994ce26f53f21d06dd58db4f8e0efbcaee7038df793bbb3daa96", "strongpassword"}, {"$blockchain$384$ece598c58b22a3b245a02039ce36bdf589a86b6344e802b4a3ac9b727cc0b6977e9509bc1ac4d1b7b9cbf9089ecdc89706f0a469325f7ee218b2212b6cd3e32677be20eee91e267fe13ebded02946d4ae1163ef22b3dca327d7390091247ac770288a0c7be181b21a48a8f945d9913cdfdc4cfd739ee3a41ced11cacde22e3233250e36f8b8fb4d81de5298a84374af75b88afda3438eed232e52aa0eb29e0d475456c86ae9d1aaadca14bc25f273c93fd4d7fd8316ed5306733bca77e8214277edd3155342abe0710985dc20b4f80e6620e386aa7658f92df25c7c932f0eb1beca25253662bd558647a3ba741f89450bfdba59a0c016477450fbcecd62226626e06ed2e3f5a4180e32d534c7769bcd1160aad840cfd3b7b13a90d34fedb3408fe74379a9e8a840fe3bfee8e0ee01f77ee389613fa750c3d2771b83eeb4e16598f76c15c311c325bd5d54543571aa20934060e332f451e58d67ad0f4635c0c021fa76821a68d64f1a5fb6fd70365eef4442cedcc91eb8696d52d078807edd89d", "qwertyuiop1"}, /* here is a v2 hash. NOTE, it uses 5000 pbkdf2 for the hash */ {"$blockchain$v2$5000$544$9a4d5157d4969636b2fe0738f77a376feda2fb979738c5cf0e712f5d4a2f001608824a865d25041bc85e0ad35985999fcfae7d218eb109a703781f57e7b5a03c29ffdfb756ec8ee38ed8941b056922cdd174c8e89feb40e1a0e1766792845f57992ae9d7667eff41a5e5580f3f289b050d76cc0f049cbd30c675efc3a553c0f19f30cb9589c7c3773dd095de92a991963789408351f543c1dc307751e5f781c278da77270035e3743df01ab4e41155b6437d9c7e64388a28f8331aca4822e6b89cdd5f45061b99768218d853a3575bbd029564826bcb188d55444273cda588d4e593fc5d29696713d747cfc8302a3e9c9dbb1bb3754c2e00f28b69d8faeb2e45c04085359c6a9b6bfecfd0a6a8f27ad647b6bfd498f2224a8c0442f7fe730656263ac2869923b296ad9955dbad515b4f88ad33619bdacc33ae7f14c65fce029e0f9e4a9c414716d9a23e4361aa264493bb6fc9a7fda82599b0232174b9fc92a1c717ca2cc6deb8bd6aaf3706b95fdfdc582316cb3d271178dafe3a6704a918e07be057bef676bb144840c7f26676f183f2744fc2fe22c9c3feb7461b4383981c00b6fff403fef578f6e5464dc2d0bcb7b8d0dc2e7add502b34c8fe9f9b638eebe7ede25e351b17ea8b8c1f5213b69780c0ba7ef3d5734c0635e9d2ee49524914f047d45536180be25e7610db809db694ceeb16a3bfd8abd5ab0cda4415203408387698fe707568566f7f567164707091a806ac2d11b9b9dd0c3c991ff037f457", "Openwall1234#"}, /* this is the 'raw' hash to the line above. We do not handle this yet, but probably should. It is also mime, and not base-16 */ //{"{\"pbkdf2_iterations\":5000,\"version\":2,\"payload\":\"mk1RV9SWljay/gc493o3b+2i+5eXOMXPDnEvXUovABYIgkqGXSUEG8heCtNZhZmfz659IY6xCacDeB9X57WgPCn/37dW7I7jjtiUGwVpIs3RdMjon+tA4aDhdmeShF9XmSrp12Z+/0Gl5VgPPyibBQ12zA8EnL0wxnXvw6VTwPGfMMuVicfDdz3Qld6SqZGWN4lAg1H1Q8HcMHdR5feBwnjadycANeN0PfAatOQRVbZDfZx+ZDiKKPgzGspIIua4nN1fRQYbmXaCGNhTo1dbvQKVZIJryxiNVURCc82liNTlk/xdKWlnE9dHz8gwKj6cnbsbs3VMLgDyi2nY+usuRcBAhTWcaptr/s/QpqjyetZHtr/UmPIiSowEQvf+cwZWJjrChpkjspatmVXbrVFbT4itM2Gb2swzrn8Uxl/OAp4PnkqcQUcW2aI+Q2GqJkSTu2/Jp/2oJZmwIyF0ufySoccXyizG3ri9aq83Brlf39xYIxbLPScReNr+OmcEqRjge+BXvvZ2uxRIQMfyZnbxg/J0T8L+IsnD/rdGG0ODmBwAtv/0A/71ePblRk3C0Ly3uNDcLnrdUCs0yP6fm2OO6+ft4l41Gxfqi4wfUhO2l4DAun7z1XNMBjXp0u5JUkkU8EfUVTYYC+JedhDbgJ22lM7rFqO/2KvVqwzaRBUgNAg4dpj+cHVoVm9/VnFkcHCRqAasLRG5ud0MPJkf8Df0Vw==\"}", "Openwall1234#"}, {"$blockchain$v2$5000$544$a48c0a5f37986945940bd374f2e473a8f7c04719c04f7e3843f9f58caef832a738f6e3eb48f78ee059495790b0db93d8e2a1bbe9b81cdf6ac278599a30be0a12fcfa341fc29705948b2d885b2e93627ab53f5b67c4294bf2ae59571c04fbedc5a0e65547d356fef8b8090ad8e5744d63224f160b00f898e2583b2abe818454d15878afc11d0aee31f12e0553a84dff23e8e1438a212ae9c51d2c203d6c3e4746cddc94182f83fb8b2f7de79d3493d991f3d8718a58b6af7c2d33d8ef77b76e20bb859b13fad787ea7ad9a057e3ac9697b051c6749e3d3dc9a7699e13b08c7254ad687cf09f005800ab190e13c7cf9b881582b52e6c154e562fe73a723b0b1c0b80be352873c1ab8456a4a0d57bb5185f5c4cb1e150359578344ea8321cc5a0a94807fe06a89742226b2c74e8b6f1653ea84bf79e525fc92ebb7aa9106774e1b9dc794f5280ab2a5df818aeae0e467aeac0083aaea0b1f9d4c754324938caa4e8594aa69f988a0c424ae1fe5e1b91c82bccf6f995ec28d3e300b2eb62daa6ba72b4df46a788d724ec0f1f102d262b6c129ee9cd0d5674d3bc71350091b23a6219ff900653cdb52143b549829330abd15eb1f2d8e742565ed5ede6285908b040b75ca0b1871bbfb8e3a8115afef2ff8c46f180765387fb55e896a9c3a3073f57509a4102dec52d77dbb88f97cf6d83f0834b1dc7c0343a1a6b2144f2d264a3f0c4d9eb014c07fde9f1c1b6cc02fdb2e87583277194332d90b3b491d1a441ed57ce", "johntheripper!"}, {NULL} }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static int *cracked; static struct custom_salt { unsigned char data[BIG_ENOUGH]; int length; int iter; } *cur_salt; static void init(struct fmt_main *self) { #if defined (_OPENMP) int omp_t = 1; omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif saved_key = mem_calloc_align(sizeof(*saved_key), self->params.max_keys_per_crypt, MEM_ALIGN_WORD); cracked = mem_calloc_align(sizeof(*cracked), self->params.max_keys_per_crypt, MEM_ALIGN_WORD); } static void done(void) { MEM_FREE(cracked); MEM_FREE(saved_key); } static int valid(char *ciphertext, struct fmt_main *self) { char *ctcopy, *keeptr, *p; int len; if (strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH) != 0) return 0; /* handle 'chopped' .pot lines */ if (ldr_isa_pot_source(ciphertext)) return 1; ctcopy = strdup(ciphertext); keeptr = ctcopy; ctcopy += TAG_LENGTH; if ((p = strtokm(ctcopy, "$")) == NULL) goto err; if (!strcmp(p, "v2")) { if ((p = strtokm(NULL, "$")) == NULL) goto err; if (!isdec(p)) goto err; if ((p = strtokm(NULL, "$")) == NULL) goto err; } if (!isdec(p)) goto err; len = atoi(p); if(len > BIG_ENOUGH || !len) goto err; if ((p = strtokm(NULL, "$")) == NULL) goto err; if (hexlenl(p) != len * 2) goto err; MEM_FREE(keeptr); return 1; err: MEM_FREE(keeptr); return 0; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; int i; char *p; static union { struct custom_salt _cs; ARCH_WORD_32 dummy; } un; struct custom_salt *cs = &(un._cs); memset(&un, 0, sizeof(un)); ctcopy += TAG_LENGTH; p = strtokm(ctcopy, "$"); if (!strcmp(p, "v2")) { p = strtokm(NULL, "$"); cs->iter = atoi(p); p = strtokm(NULL, "$"); } else cs->iter = 10; cs->length = atoi(p); p = strtokm(NULL, "$"); for (i = 0; i < cs->length; i++) cs->data[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; MEM_FREE(keeptr); return (void *)cs; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } static int blockchain_decrypt(unsigned char *derived_key, unsigned char *data) { unsigned char out[SAFETY_FACTOR]; AES_KEY akey; unsigned char iv[16]; memcpy(iv, cur_salt->data, 16); if(AES_set_decrypt_key(derived_key, 256, &akey) < 0) { fprintf(stderr, "AES_set_decrypt_key failed in crypt!\n"); } AES_cbc_encrypt(data + 16, out, 16, &akey, iv, AES_DECRYPT); /* various tests */ if (out[0] != '{') // fast test return -1; // "guid" will be found in the first block if (memmem(out, 16, "\"guid\"", 6)) { memcpy(iv, cur_salt->data, 16); //IV has to be reset. AES_cbc_encrypt(data + 16, out, SAFETY_FACTOR, &akey, iv, AES_DECRYPT); if (memmem(out, SAFETY_FACTOR, "\"sharedKey\"", 11) && memmem(out, SAFETY_FACTOR, "\"options\"", 9)) // Note, we 'could' check that the guid and sharedKey values are // 'valid' GUID's, but there really is no point. We already have // 2^216 confidence in the simple text strings being found. return 0; } return -1; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT) #endif { #ifdef SIMD_COEF_32 unsigned char master[MAX_KEYS_PER_CRYPT][32]; int lens[MAX_KEYS_PER_CRYPT], i; unsigned char *pin[MAX_KEYS_PER_CRYPT], *pout[MAX_KEYS_PER_CRYPT]; for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { lens[i] = strlen(saved_key[i+index]); pin[i] = (unsigned char*)saved_key[i+index]; pout[i] = master[i]; } pbkdf2_sha1_sse((const unsigned char **)pin, lens, cur_salt->data, 16, cur_salt->iter, pout, 32, 0); for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { if(blockchain_decrypt(master[i], cur_salt->data) == 0) cracked[i+index] = 1; else cracked[i+index] = 0; } #else unsigned char master[32]; pbkdf2_sha1((unsigned char *)saved_key[index], strlen(saved_key[index]), cur_salt->data, 16, cur_salt->iter, master, 32, 0); if(blockchain_decrypt(master, cur_salt->data) == 0) cracked[index] = 1; else cracked[index] = 0; #endif } return count; } static int cmp_all(void *binary, int count) { int index; for (index = 0; index < count; index++) if (cracked[index]) return 1; return 0; } static int cmp_one(void *binary, int index) { return cracked[index]; } static int cmp_exact(char *source, int index) { return 1; } static void agile_keychain_set_key(char *key, int index) { int saved_len = strlen(key); if (saved_len > PLAINTEXT_LENGTH) saved_len = PLAINTEXT_LENGTH; memcpy(saved_key[index], key, saved_len); saved_key[index][saved_len] = 0; } static char *get_key(int index) { return saved_key[index]; } struct fmt_main fmt_blockchain = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP, { NULL }, agile_keychain_tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, fmt_default_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, NULL, set_salt, agile_keychain_set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
example_10-StructOfArrays-CellLinkedList-OuterLoop-SymmetricalLoadBalancing.c
/* * SPDX-License-Identifier: BSD-3-Clause * * example_10-StructOfArrays-CellLinkedList-OuterLoop-SymmetricalLoadBalancing.c : * Example of SPH Density Calculation using * fast neighbor search the main density loop via * Cell Linked List method, Struct of Arrays (SoA) * data layout, OpenMP parallelization at the * cell-pair level, SIMD directives in the kernel * and in the inner-most loop. It also implements * symmetrical load balancing by moving the parallelism * from iterating over cells to iterate over * unique pairs of cell (i.e. i<j) and recyling the * intermediary calculations. * * (C) Copyright 2021 José Hugo Elsas * Author: José Hugo Elsas <jhelsas@gmail.com> * * Command Line Options: * -runs <int> : Set the number of repetitions (runs) for * calculating the density. The value of * the density is based on the last * iteration. * Default value: 1 * -run_seed <int>: Flag to set an alternative seed use for * for the PRNG. Instead of feeding seed * to the PRNG directly, it feeds * seed + iteration, as to generate different * configurations for each iteration. * Default value: 0 - (possible 0/1) * -seed <int>: Set the seed to use for the SPH particles * uniform position generation in the box * Default value: 123123123 * * -N <int>: Set the number of SPH particles to be used * Default value: 1e5 = 100,000 * -h <float>: Set the value of the smoothing kernel * parameter h, which corresponds to half * of the support of the kernel. * Default value: 0.05 * * -Nx <int>: Set the number of Cells in the X direction * Default value: 10 * -Ny <int>: Set the number of Cells in the Y direction * Default value: 10 * -Nz <int>: Set the number of Cells in the Z direction * Default value: 10 * * -Xmin <float>: Set the lower bound in the X direction for * the Cell Linked List box * Default value: 0.0 * -Ymin <float>: Set the lower bound in the Y direction for * the Cell Linked List box * Default value: 0.0 * -Ymin <float>: Set the lower bound in the Z direction for * the Cell Linked List box * Default value: 0.0 * * -Xmax <float>: Set the lower bound in the X direction for * the Cell Linked List box * Default value: 1.0 * -Ymax <float>: Set the lower bound in the Y direction for * the Cell Linked List box * Default value: 1.0 * -Zmax <float>: Set the lower bound in the Z direction for * the Cell Linked List box * Default value: 1.0 */ #include <math.h> #include <ctype.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <limits.h> #include <unistd.h> #include <stdbool.h> #include <sys/time.h> #include <inttypes.h> #include <omp.h> #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_heapsort.h> #include "sph_data_types.h" #include "sph_linked_list.h" #include "sph_utils.h" #ifndef M_PI #define M_PI (3.14159265358979323846) #endif #define COMPUTE_BLOCKS 5 int main_loop(int run, bool run_seed, int64_t N, double h, long int seed, void *swap_arr, linkedListBox *box, SPHparticle *lsph, double *times); int compute_density_3d_symmetrical_load_ballance(int N, double h, SPHparticle *lsph, linkedListBox *box); int compute_density_3d_chunk_symmetrical(int64_t node_begin, int64_t node_end, int64_t nb_begin, int64_t nb_end,double h, double* restrict x, double* restrict y, double* restrict z, double* restrict nu, double* restrict rhoi, double* restrict rhoj); double w_bspline_3d_constant(double h); #pragma omp declare simd double w_bspline_3d_simd(double q); int main(int argc, char **argv){ bool run_seed = false; // By default the behavior is is to use the same seed int runs = 1,err; // it only runs once long int seed = 123123123; // The default seed is 123123123 int64_t N = 100000; // The default number of particles is N = 1e5 = 100,000 double h=0.05; // The default kernel smoothing length is h = 0.05 linkedListBox *box; // Uninitialized Box containing the cells for the cell linked list method SPHparticle *lsph; // Uninitialized array of SPH particles box = (linkedListBox*)malloc(1*sizeof(linkedListBox)); // Create a box representing the entire 3d domain // allow for command line customization of the run arg_parse(argc,argv,&N,&h,&seed,&runs,&run_seed,box); // Parse the command line options // line arguments and override default values err = SPHparticle_SoA_malloc(N,&lsph); if(err) fprintf(stderr,"error in SPHparticle_SoA_malloc\n"); void *swap_arr = malloc(N*sizeof(double)); double times[runs*COMPUTE_BLOCKS]; for(int run=0;run<runs;run+=1) main_loop(run,run_seed,N,h,seed,swap_arr,box,lsph,times); bool is_cll = true; const char *prefix = "ex10,cll,SoA,outer,simd,symmLB"; print_time_stats(prefix,is_cll,N,h,seed,runs,lsph,box,times); print_sph_particles_density(prefix,is_cll,N,h,seed,runs,lsph,box); SPHparticleSOA_safe_free(N,&lsph); safe_free_box(box); free(swap_arr); return 0; } /* * Function main_loop: * Runs the main loop of the program, including the particle array generation, * density calculation and the timings annotations. * * Arguments: * run <int> : index (or value) or the present iteration * run_seed <bool> : boolean defining whether to use run index for seed or not * N <int> : Number of SPH particles to be used in the run * h <double> : Smoothing Length for the Smoothing Kernel w_bspline * seed <long int> : seed for GSL PRNG generator to generate particle positions * box <linkedListBox> : Box of linked list cells, encapsulating the 3d domain * lsph <SPHparticle> : Array (pointer) of SPH particles to be updated * times <double> : Array to store the computation timings to be updated * Returns: * 0 : error code returned * lsph <SPHparticle> : SPH particle array is updated in the rho field by reference * times <double> : Times is updated by reference */ int main_loop(int run, bool run_seed, int64_t N, double h, long int seed, void *swap_arr, linkedListBox *box, SPHparticle *lsph, double *times) { int err; if(run_seed) err = gen_unif_rdn_pos_box(N,seed+run,box,lsph); else err = gen_unif_rdn_pos_box(N,seed,box,lsph); if(err) fprintf(stderr,"error in gen_unif_rdn_pos\n"); // ------------------------------------------------------ // double t0,t1,t2,t3,t4,t5; t0 = omp_get_wtime(); err = compute_hash_MC3D(N,lsph,box); // Compute Morton Z 3D hash based on the if(err) // cell index for each of the X, Y and Z fprintf(stderr,"error in compute_hash_MC3D\n"); // directions, in which a given particle reside t1 = omp_get_wtime(); qsort(lsph->hash,N,2*sizeof(int64_t),compare_int64_t); // Sort the Particle Hash Hashes, getting the shuffled // index necessary to re-shuffle the remaining arrays t2 = omp_get_wtime(); err = reorder_lsph_SoA(N,lsph,swap_arr); // Reorder all arrays according to the sorted hash, if(err) // As to have a quick way to retrieve a cell fprintf(stderr,"error in reorder_lsph_SoA\n"); // given its hash. t3 = omp_get_wtime(); err = setup_interval_hashtables(N,lsph,box); // Annotate the begining and end of each cell if(err) // on the cell linked list method for fast fprintf(stderr,"error in setup_interval_hashtables\n"); // neighbor search t4 = omp_get_wtime(); err = compute_density_3d_symmetrical_load_ballance(N,h,lsph,box); // Compute the density of the particles based if(err) // on the cell linked list method for fast fprintf(stderr,"error in compute_density_3d_load_ballanced\n"); // neighbor search // --------------------------------------------------------------- // t5 = omp_get_wtime(); times[COMPUTE_BLOCKS*run+0] = t1-t0; // Time for compute morton Z 3d hash times[COMPUTE_BLOCKS*run+1] = t2-t1; // Time for sorting the particles' hashes times[COMPUTE_BLOCKS*run+2] = t3-t2; // Time for reordering all other arrays accordingly times[COMPUTE_BLOCKS*run+3] = t4-t3; // Time for setting up the interval hash tables times[COMPUTE_BLOCKS*run+4] = t5-t4; // Time for computing the SPH particle densities return 0; } /* * Function compute_density_3d_symmetrical_load_ballance: * Computes the SPH density from the particles using cell linked list with * vectorization at the compute_density_3d_chunk level, but the parallelization * done at the level of the outer-most loop of the compute_density_3d_cll_outerOmp * function, not at the chunk level. * * The parallelization is done at the level of unique cell pair instead of cells, * with the indexes for the cell pairs pre-computed before parallelization. * * Arguments: * N <int> : Number of SPH particles to be used in the run * h <double> : Smoothing Length for the Smoothing Kernel w_bspline * lsph <SPHparticle> : Array (pointer) of SPH particles to be updated * Returns: * 0 : error code returned * lsph <SPHparticle> : SPH particle array is updated in the rho field by reference */ int compute_density_3d_symmetrical_load_ballance(int N, double h, SPHparticle *lsph, linkedListBox *box){ int64_t *node_begin,*node_end,*nb_begin,*nb_end; // Define the arrays for cell boundaries int64_t max_cell_pair_count = 0; // and the number of cell pairs const double kernel_constant = w_bspline_3d_constant(h); max_cell_pair_count = count_box_pairs(box); // compute the maximum number of cell pairs node_begin = (int64_t*)malloc(max_cell_pair_count*sizeof(int64_t)); // allocate space for node_begin node_end = (int64_t*)malloc(max_cell_pair_count*sizeof(int64_t)); // allocate space for node_end nb_begin = (int64_t*)malloc(max_cell_pair_count*sizeof(int64_t)); // allocate space for nb_begin nb_end = (int64_t*)malloc(max_cell_pair_count*sizeof(int64_t)); // allocate space for nb_end max_cell_pair_count = setup_unique_box_pairs(box, // set the values for cell pairs node_begin,node_end, nb_begin,nb_end); memset(lsph->rho,(int)0,N*sizeof(double)); // Pre-initialize the density to zero // Parallelism was moved // to the level of unique pairs #pragma omp parallel for schedule(dynamic,5) proc_bind(master) // Execute in parallel for(size_t i=0;i<max_cell_pair_count;i+=1){ // over the unique pairs' array double local_rhoi[node_end[i] - node_begin[i]]; // partial density array for node indexs double local_rhoj[ nb_end[i] - nb_begin[i]]; // partial density array for nb indexs memset(local_rhoi,(int)0,(node_end[i]-node_begin[i])*sizeof(double)); // initialize node partial density to zero memset(local_rhoj,(int)0, (nb_end[i]-nb_begin[i])*sizeof(double)); // initialize nb partial density to zero compute_density_3d_chunk_symmetrical(node_begin[i],node_end[i], // Compute the density contribution nb_begin[i],nb_end[i],h, // from this particular cell pair lsph->x,lsph->y,lsph->z, // for both node and nb partial density lsph->nu,local_rhoi, local_rhoj); // merging the results can result in race conditions, therefore needs to be serialized #pragma omp critical // this serializes this code section { for(size_t ii=node_begin[i];ii<node_end[i];ii+=1){ // iterate over the node_ cell lsph->rho[ii] += kernel_constant*local_rhoi[ii-node_begin[i]]; // add the partial density contribution } if(node_begin[i] != nb_begin[i]) // if sender and receiver are different for(size_t ii=nb_begin[i];ii<nb_end[i];ii+=1){ // iterate over the nb_ cell lsph->rho[ii] += kernel_constant*local_rhoj[ii-nb_begin[i]]; // add the partial density contribution } } } free(node_begin); free(node_end); free(nb_begin); free(nb_end); return 0; } /* * Function compute_density_3d_chunk_symmetrical: * Computes the SPH density contribution to both the node_ cell and the nb_ cell. * Vectorization in the inner-most loop, but no parallelization. * The density contribution is symmetrical. * * Arguments: * N <int> : Number of SPH particles to be used in the run * h <double> : Smoothing Length for the Smoothing Kernel w_bspline * x <double*> : Array of particles' X positions * y <double*> : Array of particles' Y positions * z <double*> : Array of particles' Z positions * nu <double*> : Array of particles' density weights (i.e. masses) * Returns: * 0 : error code returned * rho <double*> : Array of particles' densities */ int compute_density_3d_chunk_symmetrical(int64_t node_begin, int64_t node_end, int64_t nb_begin, int64_t nb_end,double h, double* restrict x, double* restrict y, double* restrict z, double* restrict nu, double* restrict rhoi, double* restrict rhoj){ const double inv_h = 1./h; for(int64_t ii=node_begin;ii<node_end;ii+=1){ // Iterate over the ii index of the chunk double xii = x[ii]; // Load the X component of the ii particle position double yii = y[ii]; // Load the Y component of the ii particle position double zii = z[ii]; // Load the Z component of the ii particle position #pragma omp simd // Hint at the compiler to vectorize the inner most loop for(int64_t jj=nb_begin;jj<nb_end;jj+=1){ // Iterate over the each other particle in jj loop double q = 0.; // Initialize the distance double xij = xii-x[jj]; // Load and subtract jj particle's X position component double yij = yii-y[jj]; // Load and subtract jj particle's Y position component double zij = zii-z[jj]; // Load and subtract jj particle's Z position component q += xij*xij; // Add the jj contribution to the ii distance in X q += yij*yij; // Add the jj contribution to the ii distance in Y q += zij*zij; // Add the jj contribution to the ii distance in Z q = sqrt(q)*inv_h; // Sqrt to compute the normalized distance, measured in h double wij = w_bspline_3d_simd(q); // compute the smoothing kernel separately for re-use rhoi[ii-node_begin] += nu[jj]*wij; // add the jj contribution to ii density rhoj[jj-nb_begin] += nu[ii]*wij; // add the ii contribution to jj density } } return 0; } /* * Function w_bspline_3d_constant: * Returns the 3d normalization constant for the cubic b-spline SPH smoothing kernel * * Arguments: * h <double> : Smoothing Length for the Smoothing Kernel w_bspline * Returns: * 3d bspline normalization density <double> */ double w_bspline_3d_constant(double h){ return 3./(2.*M_PI*h*h*h); // 3d normalization value for the b-spline kernel } /* * Function w_bspline_3d_simd: * Returns the un-normalized value of the cubic b-spline SPH smoothing kernel * * Arguments: * q <double> : Distance between particles normalized by the smoothing length h * Returns: * wq <double> : Unnormalized value of the kernel * * Observation: * Why not else if(q<2.)? * Because if you use "else if", the compiler refuses to vectorize, * This results in a large slowdown, as of 2.5x slower for example_04 */ #pragma omp declare simd double w_bspline_3d_simd(double q){ double wq=0; double wq1 = (0.6666666666666666 - q*q + 0.5*q*q*q); // The first polynomial of the spline double wq2 = 0.16666666666666666*(2.-q)*(2.-q)*(2.-q); // The second polynomial of the spline if(q<2.) // If the distance is below 2 wq = wq2; // Use the 2nd polynomial for the spline if(q<1.) // If the distance is below 1 wq = wq1; // Use the 1st polynomial for the spline return wq; // return which ever value corresponds to the distance }
blake2bp-ref.c
/* BLAKE2 reference source code package - reference C implementations Copyright 2012, Samuel Neves <sneves@dei.uc.pt>. You may use this under the terms of the CC0, the OpenSSL Licence, or the Apache Public License 2.0, at your option. The terms of these licenses can be found at: - CC0 1.0 Universal : http://creativecommons.org/publicdomain/zero/1.0 - OpenSSL license : https://www.openssl.org/source/license.html - Apache 2.0 : http://www.apache.org/licenses/LICENSE-2.0 More information about the BLAKE2 hash function can be found at https://blake2.net. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #if defined(_OPENMP) #include <omp.h> #endif #include "blake2.h" #include "blake2-impl.h" #define PARALLELISM_DEGREE 4 /* blake2b_init_param defaults to setting the expecting output length from the digest_length parameter block field. In some cases, however, we do not want this, as the output length of these instances is given by inner_length instead. */ static int blake2bp_init_leaf_param( blake2b_state *S, const blake2b_param *P ) { int err = blake2b_init_param(S, P); S->outlen = P->inner_length; return err; } static int blake2bp_init_leaf( blake2b_state *S, size_t outlen, size_t keylen, uint64_t offset ) { blake2b_param P[1]; P->digest_length = (uint8_t)outlen; P->key_length = (uint8_t)keylen; P->fanout = PARALLELISM_DEGREE; P->depth = 2; store32( &P->leaf_length, 0 ); store32( &P->node_offset, offset ); store32( &P->xof_length, 0 ); P->node_depth = 0; P->inner_length = BLAKE2B_OUTBYTES; memset( P->reserved, 0, sizeof( P->reserved ) ); memset( P->salt, 0, sizeof( P->salt ) ); memset( P->personal, 0, sizeof( P->personal ) ); return blake2bp_init_leaf_param( S, P ); } static int blake2bp_init_root( blake2b_state *S, size_t outlen, size_t keylen ) { blake2b_param P[1]; P->digest_length = (uint8_t)outlen; P->key_length = (uint8_t)keylen; P->fanout = PARALLELISM_DEGREE; P->depth = 2; store32( &P->leaf_length, 0 ); store32( &P->node_offset, 0 ); store32( &P->xof_length, 0 ); P->node_depth = 1; P->inner_length = BLAKE2B_OUTBYTES; memset( P->reserved, 0, sizeof( P->reserved ) ); memset( P->salt, 0, sizeof( P->salt ) ); memset( P->personal, 0, sizeof( P->personal ) ); return blake2b_init_param( S, P ); } int blake2bp_init( blake2bp_state *S, size_t outlen ) { size_t i; if( !outlen || outlen > BLAKE2B_OUTBYTES ) return -1; memset( S->buf, 0, sizeof( S->buf ) ); S->buflen = 0; S->outlen = outlen; if( blake2bp_init_root( S->R, outlen, 0 ) < 0 ) return -1; for( i = 0; i < PARALLELISM_DEGREE; ++i ) if( blake2bp_init_leaf( S->S[i], outlen, 0, i ) < 0 ) return -1; S->R->last_node = 1; S->S[PARALLELISM_DEGREE - 1]->last_node = 1; return 0; } int blake2bp_init_key( blake2bp_state *S, size_t outlen, const void *key, size_t keylen ) { size_t i; if( !outlen || outlen > BLAKE2B_OUTBYTES ) return -1; if( !key || !keylen || keylen > BLAKE2B_KEYBYTES ) return -1; memset( S->buf, 0, sizeof( S->buf ) ); S->buflen = 0; S->outlen = outlen; if( blake2bp_init_root( S->R, outlen, keylen ) < 0 ) return -1; for( i = 0; i < PARALLELISM_DEGREE; ++i ) if( blake2bp_init_leaf( S->S[i], outlen, keylen, i ) < 0 ) return -1; S->R->last_node = 1; S->S[PARALLELISM_DEGREE - 1]->last_node = 1; { uint8_t block[BLAKE2B_BLOCKBYTES]; memset( block, 0, BLAKE2B_BLOCKBYTES ); memcpy( block, key, keylen ); for( i = 0; i < PARALLELISM_DEGREE; ++i ) blake2b_update( S->S[i], block, BLAKE2B_BLOCKBYTES ); secure_zero_memory( block, BLAKE2B_BLOCKBYTES ); /* Burn the key from stack */ } return 0; } int blake2bp_update( blake2bp_state *S, const void *pin, size_t inlen ) { const unsigned char * in = (const unsigned char *)pin; size_t left = S->buflen; size_t fill = sizeof( S->buf ) - left; size_t i; if( left && inlen >= fill ) { memcpy( S->buf + left, in, fill ); for( i = 0; i < PARALLELISM_DEGREE; ++i ) blake2b_update( S->S[i], S->buf + i * BLAKE2B_BLOCKBYTES, BLAKE2B_BLOCKBYTES ); in += fill; inlen -= fill; left = 0; } #if defined(_OPENMP) #pragma omp parallel shared(S), num_threads(PARALLELISM_DEGREE) #else for( i = 0; i < PARALLELISM_DEGREE; ++i ) #endif { #if defined(_OPENMP) size_t i = omp_get_thread_num(); #endif size_t inlen__ = inlen; const unsigned char *in__ = ( const unsigned char * )in; in__ += i * BLAKE2B_BLOCKBYTES; while( inlen__ >= PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES ) { blake2b_update( S->S[i], in__, BLAKE2B_BLOCKBYTES ); in__ += PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES; inlen__ -= PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES; } } in += inlen - inlen % ( PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES ); inlen %= PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES; if( inlen > 0 ) memcpy( S->buf + left, in, inlen ); S->buflen = left + inlen; return 0; } int blake2bp_final( blake2bp_state *S, void *out, size_t outlen ) { uint8_t hash[PARALLELISM_DEGREE][BLAKE2B_OUTBYTES]; size_t i; if(out == NULL || outlen < S->outlen) { return -1; } for( i = 0; i < PARALLELISM_DEGREE; ++i ) { if( S->buflen > i * BLAKE2B_BLOCKBYTES ) { size_t left = S->buflen - i * BLAKE2B_BLOCKBYTES; if( left > BLAKE2B_BLOCKBYTES ) left = BLAKE2B_BLOCKBYTES; blake2b_update( S->S[i], S->buf + i * BLAKE2B_BLOCKBYTES, left ); } blake2b_final( S->S[i], hash[i], BLAKE2B_OUTBYTES ); } for( i = 0; i < PARALLELISM_DEGREE; ++i ) blake2b_update( S->R, hash[i], BLAKE2B_OUTBYTES ); return blake2b_final( S->R, out, S->outlen ); } int blake2bp( void *out, size_t outlen, const void *in, size_t inlen, const void *key, size_t keylen ) { uint8_t hash[PARALLELISM_DEGREE][BLAKE2B_OUTBYTES]; blake2b_state S[PARALLELISM_DEGREE][1]; blake2b_state FS[1]; size_t i; /* Verify parameters */ if ( NULL == in && inlen > 0 ) return -1; if ( NULL == out ) return -1; if( NULL == key && keylen > 0 ) return -1; if( !outlen || outlen > BLAKE2B_OUTBYTES ) return -1; if( keylen > BLAKE2B_KEYBYTES ) return -1; for( i = 0; i < PARALLELISM_DEGREE; ++i ) if( blake2bp_init_leaf( S[i], outlen, keylen, i ) < 0 ) return -1; S[PARALLELISM_DEGREE - 1]->last_node = 1; /* mark last node */ if( keylen > 0 ) { uint8_t block[BLAKE2B_BLOCKBYTES]; memset( block, 0, BLAKE2B_BLOCKBYTES ); memcpy( block, key, keylen ); for( i = 0; i < PARALLELISM_DEGREE; ++i ) blake2b_update( S[i], block, BLAKE2B_BLOCKBYTES ); secure_zero_memory( block, BLAKE2B_BLOCKBYTES ); /* Burn the key from stack */ } #if defined(_OPENMP) #pragma omp parallel shared(S,hash), num_threads(PARALLELISM_DEGREE) #else for( i = 0; i < PARALLELISM_DEGREE; ++i ) #endif { #if defined(_OPENMP) size_t i = omp_get_thread_num(); #endif size_t inlen__ = inlen; const unsigned char *in__ = ( const unsigned char * )in; in__ += i * BLAKE2B_BLOCKBYTES; while( inlen__ >= PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES ) { blake2b_update( S[i], in__, BLAKE2B_BLOCKBYTES ); in__ += PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES; inlen__ -= PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES; } if( inlen__ > i * BLAKE2B_BLOCKBYTES ) { const size_t left = inlen__ - i * BLAKE2B_BLOCKBYTES; const size_t len = left <= BLAKE2B_BLOCKBYTES ? left : BLAKE2B_BLOCKBYTES; blake2b_update( S[i], in__, len ); } blake2b_final( S[i], hash[i], BLAKE2B_OUTBYTES ); } if( blake2bp_init_root( FS, outlen, keylen ) < 0 ) return -1; FS->last_node = 1; /* Mark as last node */ for( i = 0; i < PARALLELISM_DEGREE; ++i ) blake2b_update( FS, hash[i], BLAKE2B_OUTBYTES ); return blake2b_final( FS, out, outlen );; } #if defined(BLAKE2BP_SELFTEST) #include <string.h> #include "blake2-kat.h" int main( void ) { uint8_t key[BLAKE2B_KEYBYTES]; uint8_t buf[BLAKE2_KAT_LENGTH]; size_t i, step; for( i = 0; i < BLAKE2B_KEYBYTES; ++i ) key[i] = ( uint8_t )i; for( i = 0; i < BLAKE2_KAT_LENGTH; ++i ) buf[i] = ( uint8_t )i; /* Test simple API */ for( i = 0; i < BLAKE2_KAT_LENGTH; ++i ) { uint8_t hash[BLAKE2B_OUTBYTES]; blake2bp( hash, BLAKE2B_OUTBYTES, buf, i, key, BLAKE2B_KEYBYTES ); if( 0 != memcmp( hash, blake2bp_keyed_kat[i], BLAKE2B_OUTBYTES ) ) { goto fail; } } /* Test streaming API */ for(step = 1; step < BLAKE2B_BLOCKBYTES; ++step) { for (i = 0; i < BLAKE2_KAT_LENGTH; ++i) { uint8_t hash[BLAKE2B_OUTBYTES]; blake2bp_state S; uint8_t * p = buf; size_t mlen = i; int err = 0; if( (err = blake2bp_init_key(&S, BLAKE2B_OUTBYTES, key, BLAKE2B_KEYBYTES)) < 0 ) { goto fail; } while (mlen >= step) { if ( (err = blake2bp_update(&S, p, step)) < 0 ) { goto fail; } mlen -= step; p += step; } if ( (err = blake2bp_update(&S, p, mlen)) < 0) { goto fail; } if ( (err = blake2bp_final(&S, hash, BLAKE2B_OUTBYTES)) < 0) { goto fail; } if (0 != memcmp(hash, blake2bp_keyed_kat[i], BLAKE2B_OUTBYTES)) { goto fail; } } } puts( "ok" ); return 0; fail: puts("error"); return -1; } #endif
subteam2.c
/* test two omp for loops in two subteams and a single thread in the 3rd subteam */ #include <stdio.h> #include <stdlib.h> #if defined(_OPENMP) #include <omp.h> #endif /* _OPENMP */ /*by Liao, new data types and functions to support thread subteams*/ /*compiler generated new data type to store thread ids in a subteam*/ typedef struct{ int iCount; int *iThreadIds; } omp_id_set_t; omp_id_set_t idSet1,idSet2,idSet3; extern int __ompc_is_in_idset(); extern void __ompc_subteam_create(); void *subteam1, *subteam2, *subteam3; /*use it as &threadsubteam*/ #define NUMELEMENT 100 int main(void) { int a[NUMELEMENT]; int i,j=0,sum=0,sum2=0; /* assume 5 threads */ #ifdef _OPENMP omp_set_num_threads(5); #endif /* manual code to generate the thread subteams' ID sets currently */ /*stuff code to get ids from the thread ids in the subteam*/ idSet1.iCount=2; idSet1.iThreadIds=(int *)malloc(2*sizeof(int)); idSet1.iThreadIds[0]=1; idSet1.iThreadIds[1]=3; idSet2.iCount=2; idSet2.iThreadIds=(int *)malloc(2*sizeof(int)); idSet2.iThreadIds[0]=0; idSet2.iThreadIds[1]=2; idSet3.iCount=1; idSet3.iThreadIds=(int *)malloc(1*sizeof(int)); idSet3.iThreadIds[0]=1; #pragma omp parallel { /* onthreads(0,2) */ #pragma omp for reduction(+:sum) for (i=1;i<=NUMELEMENT;i++) { sum = sum +i; } /* onthreads(1,3) */ #pragma omp for schedule(dynamic,5) for (i=0;i<NUMELEMENT;i++) { a[i]=9; } /* onthread 4 */ #pragma omp single { #ifdef _OPENMP j=omp_get_thread_num(); #endif printf("I am the single one: %d\n",j ); } }/*end of parallel */ /*------verify results---------------*/ for (i=0;i<NUMELEMENT;i++) { sum2=sum2+a[i]; } printf("sum=%d\n",sum); printf("sum2=%d\n",sum2); return 0; }
PR44893.c
// RUN: %clang -fopenmp -O -g -x c %s -S -disable-output -o %t // Do not crash ;) void foo() { #pragma omp critical ; } void bar() { foo(); foo(); }
2541.c
/* POLYBENCH/GPU-OPENMP * * This file is a part of the Polybench/GPU-OpenMP suite * * Contact: * William Killian <killian@udel.edu> * * Copyright 2013, The University of Delaware */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> /* Include polybench common header. */ #include <polybench.h> /* Include benchmark-specific header. */ /* Default data type is double, default size is 4000. */ #include "3mm.h" /* Array initialization. */ static void init_array(int ni, int nj, int nk, int nl, int nm, DATA_TYPE POLYBENCH_2D(A,NI,NK,ni,nk), DATA_TYPE POLYBENCH_2D(B,NK,NJ,nk,nj), DATA_TYPE POLYBENCH_2D(C,NJ,NM,nj,nm), DATA_TYPE POLYBENCH_2D(D,NM,NL,nm,nl)) { int i, j; for (i = 0; i < ni; i++) for (j = 0; j < nk; j++) A[i][j] = ((DATA_TYPE) i*j) / ni; for (i = 0; i < nk; i++) for (j = 0; j < nj; j++) B[i][j] = ((DATA_TYPE) i*(j+1)) / nj; for (i = 0; i < nj; i++) for (j = 0; j < nm; j++) C[i][j] = ((DATA_TYPE) i*(j+3)) / nl; for (i = 0; i < nm; i++) for (j = 0; j < nl; j++) D[i][j] = ((DATA_TYPE) i*(j+2)) / nk; } /* DCE code. Must scan the entire live-out data. Can be used also to check the correctness of the output. */ static void print_array(int ni, int nl, DATA_TYPE POLYBENCH_2D(G,NI,NL,ni,nl)) { int i, j; for (i = 0; i < ni; i++) for (j = 0; j < nl; j++) { fprintf (stderr, DATA_PRINTF_MODIFIER, G[i][j]); if ((i * ni + j) % 20 == 0) fprintf (stderr, "\n"); } fprintf (stderr, "\n"); } /* Main computational kernel. The whole function will be timed, including the call and return. */ static void kernel_3mm(int ni, int nj, int nk, int nl, int nm, DATA_TYPE POLYBENCH_2D(E,NI,NJ,ni,nj), DATA_TYPE POLYBENCH_2D(A,NI,NK,ni,nk), DATA_TYPE POLYBENCH_2D(B,NK,NJ,nk,nj), DATA_TYPE POLYBENCH_2D(F,NJ,NL,nj,nl), DATA_TYPE POLYBENCH_2D(C,NJ,NM,nj,nm), DATA_TYPE POLYBENCH_2D(D,NM,NL,nm,nl), DATA_TYPE POLYBENCH_2D(G,NI,NL,ni,nl)) { int i, j, k; #pragma scop #pragma omp parallel private (i, j, k) num_threads(#P11) { /* E := A*B */ #pragma omp parallel for num_threads(2) for (i = 0; i < _PB_NI; i++) { for (j = 0; j < _PB_NJ; j++) { E[i][j] = 0; for (k = 0; k < _PB_NK; ++k) E[i][j] += A[i][k] * B[k][j]; } } /* F := C*D */ #pragma omp parallel for num_threads(2) for (i = 0; i < _PB_NJ; i++) { for (j = 0; j < _PB_NL; j++) { F[i][j] = 0; for (k = 0; k < _PB_NM; ++k) F[i][j] += C[i][k] * D[k][j]; } } /* G := E*F */ #pragma omp parallel for num_threads(2) for (i = 0; i < _PB_NI; i++) { for (j = 0; j < _PB_NL; j++) { G[i][j] = 0; for (k = 0; k < _PB_NJ; ++k) G[i][j] += E[i][k] * F[k][j]; } } } #pragma endscop } int main(int argc, char** argv) { /* Retrieve problem size. */ int ni = NI; int nj = NJ; int nk = NK; int nl = NL; int nm = NM; /* Variable declaration/allocation. */ POLYBENCH_2D_ARRAY_DECL(E, DATA_TYPE, NI, NJ, ni, nj); POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NI, NK, ni, nk); POLYBENCH_2D_ARRAY_DECL(B, DATA_TYPE, NK, NJ, nk, nj); POLYBENCH_2D_ARRAY_DECL(F, DATA_TYPE, NJ, NL, nj, nl); POLYBENCH_2D_ARRAY_DECL(C, DATA_TYPE, NJ, NM, nj, nm); POLYBENCH_2D_ARRAY_DECL(D, DATA_TYPE, NM, NL, nm, nl); POLYBENCH_2D_ARRAY_DECL(G, DATA_TYPE, NI, NL, ni, nl); /* Initialize array(s). */ init_array (ni, nj, nk, nl, nm, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(B), POLYBENCH_ARRAY(C), POLYBENCH_ARRAY(D)); /* Start timer. */ polybench_start_instruments; /* Run kernel. */ kernel_3mm (ni, nj, nk, nl, nm, POLYBENCH_ARRAY(E), POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(B), POLYBENCH_ARRAY(F), POLYBENCH_ARRAY(C), POLYBENCH_ARRAY(D), POLYBENCH_ARRAY(G)); /* Stop and print timer. */ polybench_stop_instruments; polybench_print_instruments; /* Prevent dead-code elimination. All live-out data must be printed by the function call in argument. */ polybench_prevent_dce(print_array(ni, nl, POLYBENCH_ARRAY(G))); /* Be clean. */ POLYBENCH_FREE_ARRAY(E); POLYBENCH_FREE_ARRAY(A); POLYBENCH_FREE_ARRAY(B); POLYBENCH_FREE_ARRAY(F); POLYBENCH_FREE_ARRAY(C); POLYBENCH_FREE_ARRAY(D); POLYBENCH_FREE_ARRAY(G); return 0; }
draw.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % DDDD RRRR AAA W W % % D D R R A A W W % % D D RRRR AAAAA W W W % % D D R RN A A WW WW % % DDDD R R A A W W % % % % % % MagickCore Image Drawing Methods % % % % % % Software Design % % Cristy % % July 1998 % % % % % % Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Bill Radcliffe of Corbis (www.corbis.com) contributed the polygon % rendering code based on Paul Heckbert's "Concave Polygon Scan Conversion", % Graphics Gems, 1990. Leonard Rosenthal and David Harr of Appligent % (www.appligent.com) contributed the dash pattern, linecap stroking % algorithm, and minor rendering improvements. % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/annotate.h" #include "MagickCore/artifact.h" #include "MagickCore/blob.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/constitute.h" #include "MagickCore/draw.h" #include "MagickCore/draw-private.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/memory-private.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/paint.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/property.h" #include "MagickCore/resample.h" #include "MagickCore/resample-private.h" #include "MagickCore/resource_.h" #include "MagickCore/splay-tree.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/token.h" #include "MagickCore/transform-private.h" #include "MagickCore/utility.h" /* Define declarations. */ #define BezierQuantum 200 #define PrimitiveExtentPad 4296.0 #define MaxBezierCoordinates 67108864 #define ThrowPointExpectedException(token,exception) \ { \ (void) ThrowMagickException(exception,GetMagickModule(),DrawError, \ "NonconformingDrawingPrimitiveDefinition","`%s'",token); \ status=MagickFalse; \ break; \ } /* Typedef declarations. */ typedef struct _EdgeInfo { SegmentInfo bounds; double scanline; PointInfo *points; size_t number_points; ssize_t direction; MagickBooleanType ghostline; size_t highwater; } EdgeInfo; typedef struct _ElementInfo { double cx, cy, major, minor, angle; } ElementInfo; typedef struct _MVGInfo { PrimitiveInfo **primitive_info; size_t *extent; ssize_t offset; PointInfo point; ExceptionInfo *exception; } MVGInfo; typedef struct _PolygonInfo { EdgeInfo *edges; size_t number_edges; } PolygonInfo; typedef enum { MoveToCode, OpenCode, GhostlineCode, LineToCode, EndCode } PathInfoCode; typedef struct _PathInfo { PointInfo point; PathInfoCode code; } PathInfo; /* Forward declarations. */ static Image *DrawClippingMask(Image *,const DrawInfo *,const char *,const char *, ExceptionInfo *); static MagickBooleanType DrawStrokePolygon(Image *,const DrawInfo *,const PrimitiveInfo *, ExceptionInfo *), RenderMVGContent(Image *,const DrawInfo *,const size_t,ExceptionInfo *), TraceArc(MVGInfo *,const PointInfo,const PointInfo,const PointInfo), TraceArcPath(MVGInfo *,const PointInfo,const PointInfo,const PointInfo, const double,const MagickBooleanType,const MagickBooleanType), TraceBezier(MVGInfo *,const size_t), TraceCircle(MVGInfo *,const PointInfo,const PointInfo), TraceEllipse(MVGInfo *,const PointInfo,const PointInfo,const PointInfo), TraceLine(PrimitiveInfo *,const PointInfo,const PointInfo), TraceRectangle(PrimitiveInfo *,const PointInfo,const PointInfo), TraceRoundRectangle(MVGInfo *,const PointInfo,const PointInfo,PointInfo), TraceSquareLinecap(PrimitiveInfo *,const size_t,const double); static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *,const PrimitiveInfo *,ExceptionInfo *); static ssize_t TracePath(MVGInfo *,const char *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireDrawInfo() returns a DrawInfo structure properly initialized. % % The format of the AcquireDrawInfo method is: % % DrawInfo *AcquireDrawInfo(void) % */ MagickExport DrawInfo *AcquireDrawInfo(void) { DrawInfo *draw_info; draw_info=(DrawInfo *) AcquireCriticalMemory(sizeof(*draw_info)); GetDrawInfo((ImageInfo *) NULL,draw_info); return(draw_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneDrawInfo() makes a copy of the given draw_info structure. If NULL % is specified, a new DrawInfo structure is created initialized to default % values. % % The format of the CloneDrawInfo method is: % % DrawInfo *CloneDrawInfo(const ImageInfo *image_info, % const DrawInfo *draw_info) % % A description of each parameter follows: % % o image_info: the image info. % % o draw_info: the draw info. % */ MagickExport DrawInfo *CloneDrawInfo(const ImageInfo *image_info, const DrawInfo *draw_info) { DrawInfo *clone_info; ExceptionInfo *exception; clone_info=(DrawInfo *) AcquireCriticalMemory(sizeof(*clone_info)); GetDrawInfo(image_info,clone_info); if (draw_info == (DrawInfo *) NULL) return(clone_info); exception=AcquireExceptionInfo(); if (draw_info->id != (char *) NULL) (void) CloneString(&clone_info->id,draw_info->id); if (draw_info->primitive != (char *) NULL) (void) CloneString(&clone_info->primitive,draw_info->primitive); if (draw_info->geometry != (char *) NULL) (void) CloneString(&clone_info->geometry,draw_info->geometry); clone_info->compliance=draw_info->compliance; clone_info->viewbox=draw_info->viewbox; clone_info->affine=draw_info->affine; clone_info->gravity=draw_info->gravity; clone_info->fill=draw_info->fill; clone_info->stroke=draw_info->stroke; clone_info->stroke_width=draw_info->stroke_width; if (draw_info->fill_pattern != (Image *) NULL) clone_info->fill_pattern=CloneImage(draw_info->fill_pattern,0,0,MagickTrue, exception); if (draw_info->stroke_pattern != (Image *) NULL) clone_info->stroke_pattern=CloneImage(draw_info->stroke_pattern,0,0, MagickTrue,exception); clone_info->stroke_antialias=draw_info->stroke_antialias; clone_info->text_antialias=draw_info->text_antialias; clone_info->fill_rule=draw_info->fill_rule; clone_info->linecap=draw_info->linecap; clone_info->linejoin=draw_info->linejoin; clone_info->miterlimit=draw_info->miterlimit; clone_info->dash_offset=draw_info->dash_offset; clone_info->decorate=draw_info->decorate; clone_info->compose=draw_info->compose; if (draw_info->text != (char *) NULL) (void) CloneString(&clone_info->text,draw_info->text); if (draw_info->font != (char *) NULL) (void) CloneString(&clone_info->font,draw_info->font); if (draw_info->metrics != (char *) NULL) (void) CloneString(&clone_info->metrics,draw_info->metrics); if (draw_info->family != (char *) NULL) (void) CloneString(&clone_info->family,draw_info->family); clone_info->style=draw_info->style; clone_info->stretch=draw_info->stretch; clone_info->weight=draw_info->weight; if (draw_info->encoding != (char *) NULL) (void) CloneString(&clone_info->encoding,draw_info->encoding); clone_info->pointsize=draw_info->pointsize; clone_info->kerning=draw_info->kerning; clone_info->interline_spacing=draw_info->interline_spacing; clone_info->interword_spacing=draw_info->interword_spacing; clone_info->direction=draw_info->direction; if (draw_info->density != (char *) NULL) (void) CloneString(&clone_info->density,draw_info->density); clone_info->align=draw_info->align; clone_info->undercolor=draw_info->undercolor; clone_info->border_color=draw_info->border_color; if (draw_info->server_name != (char *) NULL) (void) CloneString(&clone_info->server_name,draw_info->server_name); if (draw_info->dash_pattern != (double *) NULL) { ssize_t x; for (x=0; fabs(draw_info->dash_pattern[x]) >= MagickEpsilon; x++) ; clone_info->dash_pattern=(double *) AcquireQuantumMemory((size_t) (2*x+2), sizeof(*clone_info->dash_pattern)); if (clone_info->dash_pattern == (double *) NULL) ThrowFatalException(ResourceLimitFatalError, "UnableToAllocateDashPattern"); (void) memset(clone_info->dash_pattern,0,(size_t) (2*x+2)* sizeof(*clone_info->dash_pattern)); (void) memcpy(clone_info->dash_pattern,draw_info->dash_pattern,(size_t) (x+1)*sizeof(*clone_info->dash_pattern)); } clone_info->gradient=draw_info->gradient; if (draw_info->gradient.stops != (StopInfo *) NULL) { size_t number_stops; number_stops=clone_info->gradient.number_stops; clone_info->gradient.stops=(StopInfo *) AcquireQuantumMemory((size_t) number_stops,sizeof(*clone_info->gradient.stops)); if (clone_info->gradient.stops == (StopInfo *) NULL) ThrowFatalException(ResourceLimitFatalError, "UnableToAllocateDashPattern"); (void) memcpy(clone_info->gradient.stops,draw_info->gradient.stops, (size_t) number_stops*sizeof(*clone_info->gradient.stops)); } clone_info->bounds=draw_info->bounds; clone_info->fill_alpha=draw_info->fill_alpha; clone_info->stroke_alpha=draw_info->stroke_alpha; clone_info->element_reference=draw_info->element_reference; clone_info->clip_path=draw_info->clip_path; clone_info->clip_units=draw_info->clip_units; if (draw_info->clip_mask != (char *) NULL) (void) CloneString(&clone_info->clip_mask,draw_info->clip_mask); if (draw_info->clipping_mask != (Image *) NULL) clone_info->clipping_mask=CloneImage(draw_info->clipping_mask,0,0, MagickTrue,exception); if (draw_info->composite_mask != (Image *) NULL) clone_info->composite_mask=CloneImage(draw_info->composite_mask,0,0, MagickTrue,exception); clone_info->render=draw_info->render; clone_info->debug=IsEventLogging(); exception=DestroyExceptionInfo(exception); return(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o n v e r t P a t h T o P o l y g o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConvertPathToPolygon() converts a path to the more efficient sorted % rendering form. % % The format of the ConvertPathToPolygon method is: % % PolygonInfo *ConvertPathToPolygon(const PathInfo *path_info, % ExceptionInfo *excetion) % % A description of each parameter follows: % % o ConvertPathToPolygon() returns the path in a more efficient sorted % rendering form of type PolygonInfo. % % o draw_info: Specifies a pointer to an DrawInfo structure. % % o path_info: Specifies a pointer to an PathInfo structure. % % */ static PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info) { ssize_t i; if (polygon_info->edges != (EdgeInfo *) NULL) { for (i=0; i < (ssize_t) polygon_info->number_edges; i++) if (polygon_info->edges[i].points != (PointInfo *) NULL) polygon_info->edges[i].points=(PointInfo *) RelinquishMagickMemory(polygon_info->edges[i].points); polygon_info->edges=(EdgeInfo *) RelinquishMagickMemory( polygon_info->edges); } return((PolygonInfo *) RelinquishMagickMemory(polygon_info)); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int DrawCompareEdges(const void *p_edge,const void *q_edge) { #define DrawCompareEdge(p,q) \ { \ if (((p)-(q)) < 0.0) \ return(-1); \ if (((p)-(q)) > 0.0) \ return(1); \ } const PointInfo *p, *q; /* Edge sorting for right-handed coordinate system. */ p=((const EdgeInfo *) p_edge)->points; q=((const EdgeInfo *) q_edge)->points; DrawCompareEdge(p[0].y,q[0].y); DrawCompareEdge(p[0].x,q[0].x); DrawCompareEdge((p[1].x-p[0].x)*(q[1].y-q[0].y),(p[1].y-p[0].y)* (q[1].x-q[0].x)); DrawCompareEdge(p[1].y,q[1].y); DrawCompareEdge(p[1].x,q[1].x); return(0); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static void LogPolygonInfo(const PolygonInfo *polygon_info) { EdgeInfo *p; ssize_t i, j; (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin active-edge"); p=polygon_info->edges; for (i=0; i < (ssize_t) polygon_info->number_edges; i++) { (void) LogMagickEvent(DrawEvent,GetMagickModule()," edge %.20g:", (double) i); (void) LogMagickEvent(DrawEvent,GetMagickModule()," direction: %s", p->direction != MagickFalse ? "down" : "up"); (void) LogMagickEvent(DrawEvent,GetMagickModule()," ghostline: %s", p->ghostline != MagickFalse ? "transparent" : "opaque"); (void) LogMagickEvent(DrawEvent,GetMagickModule(), " bounds: %g,%g - %g,%g",p->bounds.x1,p->bounds.y1, p->bounds.x2,p->bounds.y2); for (j=0; j < (ssize_t) p->number_points; j++) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %g,%g", p->points[j].x,p->points[j].y); p++; } (void) LogMagickEvent(DrawEvent,GetMagickModule()," end active-edge"); } static void ReversePoints(PointInfo *points,const size_t number_points) { PointInfo point; ssize_t i; for (i=0; i < (ssize_t) (number_points >> 1); i++) { point=points[i]; points[i]=points[number_points-(i+1)]; points[number_points-(i+1)]=point; } } static PolygonInfo *ConvertPathToPolygon(const PathInfo *path_info, ExceptionInfo *exception) { long direction, next_direction; PointInfo point, *points; PolygonInfo *polygon_info; SegmentInfo bounds; ssize_t i, n; MagickBooleanType ghostline; size_t edge, number_edges, number_points; /* Convert a path to the more efficient sorted rendering form. */ polygon_info=(PolygonInfo *) AcquireMagickMemory(sizeof(*polygon_info)); if (polygon_info == (PolygonInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return((PolygonInfo *) NULL); } number_edges=16; polygon_info->edges=(EdgeInfo *) AcquireQuantumMemory(number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonInfo(polygon_info)); } (void) memset(polygon_info->edges,0,number_edges* sizeof(*polygon_info->edges)); direction=0; edge=0; ghostline=MagickFalse; n=0; number_points=0; points=(PointInfo *) NULL; (void) memset(&point,0,sizeof(point)); (void) memset(&bounds,0,sizeof(bounds)); polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=0.0; polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) direction; polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->number_edges=0; for (i=0; path_info[i].code != EndCode; i++) { if ((path_info[i].code == MoveToCode) || (path_info[i].code == OpenCode) || (path_info[i].code == GhostlineCode)) { /* Move to. */ if ((points != (PointInfo *) NULL) && (n >= 2)) { if (edge == number_edges) { number_edges<<=1; polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory( polygon_info->edges,(size_t) number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); points=(PointInfo *) RelinquishMagickMemory(points); return(DestroyPolygonInfo(polygon_info)); } } polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=(-1.0); polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) (direction > 0); if (direction < 0) ReversePoints(points,(size_t) n); polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->edges[edge].bounds.y1=points[0].y; polygon_info->edges[edge].bounds.y2=points[n-1].y; points=(PointInfo *) NULL; ghostline=MagickFalse; edge++; polygon_info->number_edges=edge; } if (points == (PointInfo *) NULL) { number_points=16; points=(PointInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*points)); if (points == (PointInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonInfo(polygon_info)); } } ghostline=path_info[i].code == GhostlineCode ? MagickTrue : MagickFalse; point=path_info[i].point; points[0]=point; bounds.x1=point.x; bounds.x2=point.x; direction=0; n=1; continue; } /* Line to. */ next_direction=((path_info[i].point.y > point.y) || ((fabs(path_info[i].point.y-point.y) < MagickEpsilon) && (path_info[i].point.x > point.x))) ? 1 : -1; if ((points != (PointInfo *) NULL) && (direction != 0) && (direction != next_direction)) { /* New edge. */ point=points[n-1]; if (edge == number_edges) { number_edges<<=1; polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory( polygon_info->edges,(size_t) number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); points=(PointInfo *) RelinquishMagickMemory(points); return(DestroyPolygonInfo(polygon_info)); } } polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=(-1.0); polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) (direction > 0); if (direction < 0) ReversePoints(points,(size_t) n); polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->edges[edge].bounds.y1=points[0].y; polygon_info->edges[edge].bounds.y2=points[n-1].y; polygon_info->number_edges=edge+1; points=(PointInfo *) NULL; number_points=16; points=(PointInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*points)); if (points == (PointInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonInfo(polygon_info)); } n=1; ghostline=MagickFalse; points[0]=point; bounds.x1=point.x; bounds.x2=point.x; edge++; } direction=next_direction; if (points == (PointInfo *) NULL) continue; if (n == (ssize_t) number_points) { number_points<<=1; points=(PointInfo *) ResizeQuantumMemory(points,(size_t) number_points, sizeof(*points)); if (points == (PointInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonInfo(polygon_info)); } } point=path_info[i].point; points[n]=point; if (point.x < bounds.x1) bounds.x1=point.x; if (point.x > bounds.x2) bounds.x2=point.x; n++; } if (points != (PointInfo *) NULL) { if (n < 2) points=(PointInfo *) RelinquishMagickMemory(points); else { if (edge == number_edges) { number_edges<<=1; polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory( polygon_info->edges,(size_t) number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonInfo(polygon_info)); } } polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=(-1.0); polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) (direction > 0); if (direction < 0) ReversePoints(points,(size_t) n); polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->edges[edge].bounds.y1=points[0].y; polygon_info->edges[edge].bounds.y2=points[n-1].y; points=(PointInfo *) NULL; ghostline=MagickFalse; edge++; polygon_info->number_edges=edge; } } polygon_info->number_edges=edge; polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(polygon_info->edges, polygon_info->number_edges,sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonInfo(polygon_info)); } for (i=0; i < (ssize_t) polygon_info->number_edges; i++) { EdgeInfo *edge_info; edge_info=polygon_info->edges+i; edge_info->points=(PointInfo *) ResizeQuantumMemory(edge_info->points, edge_info->number_points,sizeof(*edge_info->points)); if (edge_info->points == (PointInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonInfo(polygon_info)); } } qsort(polygon_info->edges,(size_t) polygon_info->number_edges, sizeof(*polygon_info->edges),DrawCompareEdges); if (IsEventLogging() != MagickFalse) LogPolygonInfo(polygon_info); return(polygon_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o n v e r t P r i m i t i v e T o P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConvertPrimitiveToPath() converts a PrimitiveInfo structure into a vector % path structure. % % The format of the ConvertPrimitiveToPath method is: % % PathInfo *ConvertPrimitiveToPath(const DrawInfo *draw_info, % const PrimitiveInfo *primitive_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o ConvertPrimitiveToPath() returns a vector path structure of type % PathInfo. % % o draw_info: a structure of type DrawInfo. % % o primitive_info: Specifies a pointer to an PrimitiveInfo structure. % */ static void LogPathInfo(const PathInfo *path_info) { const PathInfo *p; (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin vector-path"); for (p=path_info; p->code != EndCode; p++) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " %g,%g %s",p->point.x,p->point.y,p->code == GhostlineCode ? "moveto ghostline" : p->code == OpenCode ? "moveto open" : p->code == MoveToCode ? "moveto" : p->code == LineToCode ? "lineto" : "?"); (void) LogMagickEvent(DrawEvent,GetMagickModule()," end vector-path"); } static PathInfo *ConvertPrimitiveToPath(const PrimitiveInfo *primitive_info, ExceptionInfo *exception) { MagickBooleanType closed_subpath; PathInfo *path_info; PathInfoCode code; PointInfo p, q; ssize_t i, n; ssize_t coordinates, start; /* Converts a PrimitiveInfo structure into a vector path structure. */ switch (primitive_info->primitive) { case AlphaPrimitive: case ColorPrimitive: case ImagePrimitive: case PointPrimitive: case TextPrimitive: return((PathInfo *) NULL); default: break; } for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ; path_info=(PathInfo *) AcquireQuantumMemory((size_t) (3UL*i+1UL), sizeof(*path_info)); if (path_info == (PathInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return((PathInfo *) NULL); } coordinates=0; closed_subpath=MagickFalse; n=0; p.x=(-1.0); p.y=(-1.0); q.x=(-1.0); q.y=(-1.0); start=0; for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) { code=LineToCode; if (coordinates <= 0) { /* New subpath. */ coordinates=(ssize_t) primitive_info[i].coordinates; p=primitive_info[i].point; start=n; code=MoveToCode; closed_subpath=primitive_info[i].closed_subpath; } coordinates--; if ((code == MoveToCode) || (coordinates <= 0) || (fabs(q.x-primitive_info[i].point.x) >= MagickEpsilon) || (fabs(q.y-primitive_info[i].point.y) >= MagickEpsilon)) { /* Eliminate duplicate points. */ path_info[n].code=code; path_info[n].point=primitive_info[i].point; q=primitive_info[i].point; n++; } if (coordinates > 0) continue; /* next point in current subpath */ if (closed_subpath != MagickFalse) { closed_subpath=MagickFalse; continue; } /* Mark the p point as open if the subpath is not closed. */ path_info[start].code=OpenCode; path_info[n].code=GhostlineCode; path_info[n].point=primitive_info[i].point; n++; path_info[n].code=LineToCode; path_info[n].point=p; n++; } path_info[n].code=EndCode; path_info[n].point.x=0.0; path_info[n].point.y=0.0; if (IsEventLogging() != MagickFalse) LogPathInfo(path_info); path_info=(PathInfo *) ResizeQuantumMemory(path_info,(size_t) (n+1), sizeof(*path_info)); return(path_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyDrawInfo() deallocates memory associated with an DrawInfo structure. % % The format of the DestroyDrawInfo method is: % % DrawInfo *DestroyDrawInfo(DrawInfo *draw_info) % % A description of each parameter follows: % % o draw_info: the draw info. % */ MagickExport DrawInfo *DestroyDrawInfo(DrawInfo *draw_info) { assert(draw_info != (DrawInfo *) NULL); if (draw_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(draw_info->signature == MagickCoreSignature); if (draw_info->id != (char *) NULL) draw_info->id=DestroyString(draw_info->id); if (draw_info->primitive != (char *) NULL) draw_info->primitive=DestroyString(draw_info->primitive); if (draw_info->text != (char *) NULL) draw_info->text=DestroyString(draw_info->text); if (draw_info->geometry != (char *) NULL) draw_info->geometry=DestroyString(draw_info->geometry); if (draw_info->fill_pattern != (Image *) NULL) draw_info->fill_pattern=DestroyImage(draw_info->fill_pattern); if (draw_info->stroke_pattern != (Image *) NULL) draw_info->stroke_pattern=DestroyImage(draw_info->stroke_pattern); if (draw_info->font != (char *) NULL) draw_info->font=DestroyString(draw_info->font); if (draw_info->metrics != (char *) NULL) draw_info->metrics=DestroyString(draw_info->metrics); if (draw_info->family != (char *) NULL) draw_info->family=DestroyString(draw_info->family); if (draw_info->encoding != (char *) NULL) draw_info->encoding=DestroyString(draw_info->encoding); if (draw_info->density != (char *) NULL) draw_info->density=DestroyString(draw_info->density); if (draw_info->server_name != (char *) NULL) draw_info->server_name=(char *) RelinquishMagickMemory(draw_info->server_name); if (draw_info->dash_pattern != (double *) NULL) draw_info->dash_pattern=(double *) RelinquishMagickMemory( draw_info->dash_pattern); if (draw_info->gradient.stops != (StopInfo *) NULL) draw_info->gradient.stops=(StopInfo *) RelinquishMagickMemory( draw_info->gradient.stops); if (draw_info->clip_mask != (char *) NULL) draw_info->clip_mask=DestroyString(draw_info->clip_mask); if (draw_info->clipping_mask != (Image *) NULL) draw_info->clipping_mask=DestroyImage(draw_info->clipping_mask); if (draw_info->composite_mask != (Image *) NULL) draw_info->composite_mask=DestroyImage(draw_info->composite_mask); draw_info->signature=(~MagickCoreSignature); draw_info=(DrawInfo *) RelinquishMagickMemory(draw_info); return(draw_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w A f f i n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawAffineImage() composites the source over the destination image as % dictated by the affine transform. % % The format of the DrawAffineImage method is: % % MagickBooleanType DrawAffineImage(Image *image,const Image *source, % const AffineMatrix *affine,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o source: the source image. % % o affine: the affine transform. % % o exception: return any errors or warnings in this structure. % */ static SegmentInfo AffineEdge(const Image *image,const AffineMatrix *affine, const double y,const SegmentInfo *edge) { double intercept, z; double x; SegmentInfo inverse_edge; /* Determine left and right edges. */ inverse_edge.x1=edge->x1; inverse_edge.y1=edge->y1; inverse_edge.x2=edge->x2; inverse_edge.y2=edge->y2; z=affine->ry*y+affine->tx; if (affine->sx >= MagickEpsilon) { intercept=(-z/affine->sx); x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z+(double) image->columns)/affine->sx; x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if (affine->sx < -MagickEpsilon) { intercept=(-z+(double) image->columns)/affine->sx; x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z/affine->sx); x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->columns)) { inverse_edge.x2=edge->x1; return(inverse_edge); } /* Determine top and bottom edges. */ z=affine->sy*y+affine->ty; if (affine->rx >= MagickEpsilon) { intercept=(-z/affine->rx); x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z+(double) image->rows)/affine->rx; x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if (affine->rx < -MagickEpsilon) { intercept=(-z+(double) image->rows)/affine->rx; x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z/affine->rx); x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->rows)) { inverse_edge.x2=edge->x2; return(inverse_edge); } return(inverse_edge); } static AffineMatrix InverseAffineMatrix(const AffineMatrix *affine) { AffineMatrix inverse_affine; double determinant; determinant=PerceptibleReciprocal(affine->sx*affine->sy-affine->rx* affine->ry); inverse_affine.sx=determinant*affine->sy; inverse_affine.rx=determinant*(-affine->rx); inverse_affine.ry=determinant*(-affine->ry); inverse_affine.sy=determinant*affine->sx; inverse_affine.tx=(-affine->tx)*inverse_affine.sx-affine->ty* inverse_affine.ry; inverse_affine.ty=(-affine->tx)*inverse_affine.rx-affine->ty* inverse_affine.sy; return(inverse_affine); } MagickExport MagickBooleanType DrawAffineImage(Image *image, const Image *source,const AffineMatrix *affine,ExceptionInfo *exception) { AffineMatrix inverse_affine; CacheView *image_view, *source_view; MagickBooleanType status; PixelInfo zero; PointInfo extent[4], min, max; ssize_t i; SegmentInfo edge; ssize_t start, stop, y; /* Determine bounding box. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(source != (const Image *) NULL); assert(source->signature == MagickCoreSignature); assert(affine != (AffineMatrix *) NULL); extent[0].x=0.0; extent[0].y=0.0; extent[1].x=(double) source->columns-1.0; extent[1].y=0.0; extent[2].x=(double) source->columns-1.0; extent[2].y=(double) source->rows-1.0; extent[3].x=0.0; extent[3].y=(double) source->rows-1.0; for (i=0; i < 4; i++) { PointInfo point; point=extent[i]; extent[i].x=point.x*affine->sx+point.y*affine->ry+affine->tx; extent[i].y=point.x*affine->rx+point.y*affine->sy+affine->ty; } min=extent[0]; max=extent[0]; for (i=1; i < 4; i++) { if (min.x > extent[i].x) min.x=extent[i].x; if (min.y > extent[i].y) min.y=extent[i].y; if (max.x < extent[i].x) max.x=extent[i].x; if (max.y < extent[i].y) max.y=extent[i].y; } /* Affine transform image. */ if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; edge.x1=MagickMax(min.x,0.0); edge.y1=MagickMax(min.y,0.0); edge.x2=MagickMin(max.x,(double) image->columns-1.0); edge.y2=MagickMin(max.y,(double) image->rows-1.0); inverse_affine=InverseAffineMatrix(affine); GetPixelInfo(image,&zero); start=CastDoubleToLong(ceil(edge.y1-0.5)); stop=CastDoubleToLong(floor(edge.y2+0.5)); source_view=AcquireVirtualCacheView(source,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(source,image,stop-start,1) #endif for (y=start; y <= stop; y++) { PixelInfo composite, pixel; PointInfo point; ssize_t x; Quantum *magick_restrict q; SegmentInfo inverse_edge; ssize_t x_offset; if (status == MagickFalse) continue; inverse_edge=AffineEdge(source,&inverse_affine,(double) y,&edge); if (inverse_edge.x2 < inverse_edge.x1) continue; q=GetCacheViewAuthenticPixels(image_view,CastDoubleToLong( ceil(inverse_edge.x1-0.5)),y,(size_t) CastDoubleToLong(floor( inverse_edge.x2+0.5)-ceil(inverse_edge.x1-0.5)+1),1,exception); if (q == (Quantum *) NULL) continue; pixel=zero; composite=zero; x_offset=0; for (x=CastDoubleToLong(ceil(inverse_edge.x1-0.5)); x <= CastDoubleToLong(floor(inverse_edge.x2+0.5)); x++) { point.x=(double) x*inverse_affine.sx+y*inverse_affine.ry+ inverse_affine.tx; point.y=(double) x*inverse_affine.rx+y*inverse_affine.sy+ inverse_affine.ty; status=InterpolatePixelInfo(source,source_view,UndefinedInterpolatePixel, point.x,point.y,&pixel,exception); if (status == MagickFalse) break; GetPixelInfoPixel(image,q,&composite); CompositePixelInfoOver(&pixel,pixel.alpha,&composite,composite.alpha, &composite); SetPixelViaPixelInfo(image,&composite,q); x_offset++; q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w B o u n d i n g R e c t a n g l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawBoundingRectangles() draws the bounding rectangles on the image. This % is only useful for developers debugging the rendering algorithm. % % The format of the DrawBoundingRectangles method is: % % MagickBooleanType DrawBoundingRectangles(Image *image, % const DrawInfo *draw_info,PolygonInfo *polygon_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o polygon_info: Specifies a pointer to a PolygonInfo structure. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType DrawBoundingRectangles(Image *image, const DrawInfo *draw_info,const PolygonInfo *polygon_info, ExceptionInfo *exception) { double mid; DrawInfo *clone_info; MagickStatusType status; PointInfo end, resolution, start; PrimitiveInfo primitive_info[6]; ssize_t i; SegmentInfo bounds; ssize_t coordinates; (void) memset(primitive_info,0,sizeof(primitive_info)); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); status=QueryColorCompliance("#000F",AllCompliance,&clone_info->fill, exception); if (status == MagickFalse) { clone_info=DestroyDrawInfo(clone_info); return(MagickFalse); } resolution.x=96.0; resolution.y=96.0; if (clone_info->density != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(clone_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == MagickFalse) resolution.y=resolution.x; } mid=(resolution.x/96.0)*ExpandAffine(&clone_info->affine)* clone_info->stroke_width/2.0; bounds.x1=0.0; bounds.y1=0.0; bounds.x2=0.0; bounds.y2=0.0; if (polygon_info != (PolygonInfo *) NULL) { bounds=polygon_info->edges[0].bounds; for (i=1; i < (ssize_t) polygon_info->number_edges; i++) { if (polygon_info->edges[i].bounds.x1 < (double) bounds.x1) bounds.x1=polygon_info->edges[i].bounds.x1; if (polygon_info->edges[i].bounds.y1 < (double) bounds.y1) bounds.y1=polygon_info->edges[i].bounds.y1; if (polygon_info->edges[i].bounds.x2 > (double) bounds.x2) bounds.x2=polygon_info->edges[i].bounds.x2; if (polygon_info->edges[i].bounds.y2 > (double) bounds.y2) bounds.y2=polygon_info->edges[i].bounds.y2; } bounds.x1-=mid; bounds.x1=bounds.x1 < 0.0 ? 0.0 : bounds.x1 >= (double) image->columns ? (double) image->columns-1 : bounds.x1; bounds.y1-=mid; bounds.y1=bounds.y1 < 0.0 ? 0.0 : bounds.y1 >= (double) image->rows ? (double) image->rows-1 : bounds.y1; bounds.x2+=mid; bounds.x2=bounds.x2 < 0.0 ? 0.0 : bounds.x2 >= (double) image->columns ? (double) image->columns-1 : bounds.x2; bounds.y2+=mid; bounds.y2=bounds.y2 < 0.0 ? 0.0 : bounds.y2 >= (double) image->rows ? (double) image->rows-1 : bounds.y2; for (i=0; i < (ssize_t) polygon_info->number_edges; i++) { if (polygon_info->edges[i].direction != 0) status=QueryColorCompliance("#f00",AllCompliance,&clone_info->stroke, exception); else status=QueryColorCompliance("#0f0",AllCompliance,&clone_info->stroke, exception); if (status == MagickFalse) break; start.x=(double) (polygon_info->edges[i].bounds.x1-mid); start.y=(double) (polygon_info->edges[i].bounds.y1-mid); end.x=(double) (polygon_info->edges[i].bounds.x2+mid); end.y=(double) (polygon_info->edges[i].bounds.y2+mid); primitive_info[0].primitive=RectanglePrimitive; status&=TraceRectangle(primitive_info,start,end); primitive_info[0].method=ReplaceMethod; coordinates=(ssize_t) primitive_info[0].coordinates; primitive_info[coordinates].primitive=UndefinedPrimitive; status=DrawPrimitive(image,clone_info,primitive_info,exception); if (status == MagickFalse) break; } if (i < (ssize_t) polygon_info->number_edges) { clone_info=DestroyDrawInfo(clone_info); return(status == 0 ? MagickFalse : MagickTrue); } } status=QueryColorCompliance("#00f",AllCompliance,&clone_info->stroke, exception); if (status == MagickFalse) { clone_info=DestroyDrawInfo(clone_info); return(MagickFalse); } start.x=(double) (bounds.x1-mid); start.y=(double) (bounds.y1-mid); end.x=(double) (bounds.x2+mid); end.y=(double) (bounds.y2+mid); primitive_info[0].primitive=RectanglePrimitive; status&=TraceRectangle(primitive_info,start,end); primitive_info[0].method=ReplaceMethod; coordinates=(ssize_t) primitive_info[0].coordinates; primitive_info[coordinates].primitive=UndefinedPrimitive; status=DrawPrimitive(image,clone_info,primitive_info,exception); clone_info=DestroyDrawInfo(clone_info); return(status == 0 ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w C l i p P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawClipPath() draws the clip path on the image mask. % % The format of the DrawClipPath method is: % % MagickBooleanType DrawClipPath(Image *image,const DrawInfo *draw_info, % const char *id,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o id: the clip path id. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType DrawClipPath(Image *image, const DrawInfo *draw_info,const char *id,ExceptionInfo *exception) { const char *clip_path; Image *clipping_mask; MagickBooleanType status; clip_path=GetImageArtifact(image,id); if (clip_path == (const char *) NULL) return(MagickFalse); clipping_mask=DrawClippingMask(image,draw_info,draw_info->clip_mask,clip_path, exception); if (clipping_mask == (Image *) NULL) return(MagickFalse); status=SetImageMask(image,WritePixelMask,clipping_mask,exception); clipping_mask=DestroyImage(clipping_mask); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w C l i p p i n g M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawClippingMask() draws the clip path and returns it as an image clipping % mask. % % The format of the DrawClippingMask method is: % % Image *DrawClippingMask(Image *image,const DrawInfo *draw_info, % const char *id,const char *clip_path,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o id: the clip path id. % % o clip_path: the clip path. % % o exception: return any errors or warnings in this structure. % */ static Image *DrawClippingMask(Image *image,const DrawInfo *draw_info, const char *id,const char *clip_path,ExceptionInfo *exception) { DrawInfo *clone_info; Image *clip_mask, *separate_mask; MagickStatusType status; /* Draw a clip path. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); clip_mask=AcquireImage((const ImageInfo *) NULL,exception); status=SetImageExtent(clip_mask,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImage(clip_mask)); status=SetImageMask(clip_mask,WritePixelMask,(Image *) NULL,exception); status=QueryColorCompliance("#0000",AllCompliance, &clip_mask->background_color,exception); clip_mask->background_color.alpha=(MagickRealType) TransparentAlpha; clip_mask->background_color.alpha_trait=BlendPixelTrait; status=SetImageBackgroundColor(clip_mask,exception); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin clip-path %s", id); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->primitive,clip_path); status=QueryColorCompliance("#ffffff",AllCompliance,&clone_info->fill, exception); if (clone_info->clip_mask != (char *) NULL) clone_info->clip_mask=DestroyString(clone_info->clip_mask); status=QueryColorCompliance("#00000000",AllCompliance,&clone_info->stroke, exception); clone_info->stroke_width=0.0; clone_info->alpha=OpaqueAlpha; clone_info->clip_path=MagickTrue; status=RenderMVGContent(clip_mask,clone_info,0,exception); clone_info=DestroyDrawInfo(clone_info); separate_mask=SeparateImage(clip_mask,AlphaChannel,exception); if (separate_mask != (Image *) NULL) { clip_mask=DestroyImage(clip_mask); clip_mask=separate_mask; status=NegateImage(clip_mask,MagickFalse,exception); if (status == MagickFalse) clip_mask=DestroyImage(clip_mask); } if (status == MagickFalse) clip_mask=DestroyImage(clip_mask); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end clip-path"); return(clip_mask); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w C o m p o s i t e M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawCompositeMask() draws the mask path and returns it as an image mask. % % The format of the DrawCompositeMask method is: % % Image *DrawCompositeMask(Image *image,const DrawInfo *draw_info, % const char *id,const char *mask_path,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o id: the mask path id. % % o mask_path: the mask path. % % o exception: return any errors or warnings in this structure. % */ static Image *DrawCompositeMask(Image *image,const DrawInfo *draw_info, const char *id,const char *mask_path,ExceptionInfo *exception) { Image *composite_mask, *separate_mask; DrawInfo *clone_info; MagickStatusType status; /* Draw a mask path. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); composite_mask=AcquireImage((const ImageInfo *) NULL,exception); status=SetImageExtent(composite_mask,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImage(composite_mask)); status=SetImageMask(composite_mask,CompositePixelMask,(Image *) NULL, exception); status=QueryColorCompliance("#0000",AllCompliance, &composite_mask->background_color,exception); composite_mask->background_color.alpha=(MagickRealType) TransparentAlpha; composite_mask->background_color.alpha_trait=BlendPixelTrait; (void) SetImageBackgroundColor(composite_mask,exception); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin mask-path %s", id); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->primitive,mask_path); status=QueryColorCompliance("#ffffff",AllCompliance,&clone_info->fill, exception); status=QueryColorCompliance("#00000000",AllCompliance,&clone_info->stroke, exception); clone_info->stroke_width=0.0; clone_info->alpha=OpaqueAlpha; status=RenderMVGContent(composite_mask,clone_info,0,exception); clone_info=DestroyDrawInfo(clone_info); separate_mask=SeparateImage(composite_mask,AlphaChannel,exception); if (separate_mask != (Image *) NULL) { composite_mask=DestroyImage(composite_mask); composite_mask=separate_mask; status=NegateImage(composite_mask,MagickFalse,exception); if (status == MagickFalse) composite_mask=DestroyImage(composite_mask); } if (status == MagickFalse) composite_mask=DestroyImage(composite_mask); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end mask-path"); return(composite_mask); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w D a s h P o l y g o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawDashPolygon() draws a dashed polygon (line, rectangle, ellipse) on the % image while respecting the dash offset and dash pattern attributes. % % The format of the DrawDashPolygon method is: % % MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info, % const PrimitiveInfo *primitive_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info, const PrimitiveInfo *primitive_info,Image *image,ExceptionInfo *exception) { double length, maximum_length, offset, scale, total_length; DrawInfo *clone_info; MagickStatusType status; PrimitiveInfo *dash_polygon; double dx, dy; ssize_t i; size_t number_vertices; ssize_t j, n; assert(draw_info != (const DrawInfo *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-dash"); for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ; number_vertices=(size_t) i; dash_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t) (2UL*number_vertices+32UL),sizeof(*dash_polygon)); if (dash_polygon == (PrimitiveInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } (void) memset(dash_polygon,0,(2UL*number_vertices+32UL)* sizeof(*dash_polygon)); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->miterlimit=0; dash_polygon[0]=primitive_info[0]; scale=ExpandAffine(&draw_info->affine); length=scale*draw_info->dash_pattern[0]; offset=fabs(draw_info->dash_offset) >= MagickEpsilon ? scale*draw_info->dash_offset : 0.0; j=1; for (n=0; offset > 0.0; j=0) { if (draw_info->dash_pattern[n] <= 0.0) break; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); if (offset > length) { offset-=length; n++; length=scale*draw_info->dash_pattern[n]; continue; } if (offset < length) { length-=offset; offset=0.0; break; } offset=0.0; n++; } status=MagickTrue; maximum_length=0.0; total_length=0.0; for (i=1; (i < (ssize_t) number_vertices) && (length >= 0.0); i++) { dx=primitive_info[i].point.x-primitive_info[i-1].point.x; dy=primitive_info[i].point.y-primitive_info[i-1].point.y; maximum_length=hypot(dx,dy); if (maximum_length > (double) (MaxBezierCoordinates >> 2)) continue; if (fabs(length) < MagickEpsilon) { if (fabs(draw_info->dash_pattern[n]) >= MagickEpsilon) n++; if (fabs(draw_info->dash_pattern[n]) < MagickEpsilon) n=0; length=scale*draw_info->dash_pattern[n]; } for (total_length=0.0; (length >= 0.0) && (maximum_length >= (total_length+length)); ) { total_length+=length; if ((n & 0x01) != 0) { dash_polygon[0]=primitive_info[0]; dash_polygon[0].point.x=(double) (primitive_info[i-1].point.x+dx* total_length*PerceptibleReciprocal(maximum_length)); dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy* total_length*PerceptibleReciprocal(maximum_length)); j=1; } else { if ((j+1) > (ssize_t) number_vertices) break; dash_polygon[j]=primitive_info[i-1]; dash_polygon[j].point.x=(double) (primitive_info[i-1].point.x+dx* total_length*PerceptibleReciprocal(maximum_length)); dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy* total_length*PerceptibleReciprocal(maximum_length)); dash_polygon[j].coordinates=1; j++; dash_polygon[0].coordinates=(size_t) j; dash_polygon[j].primitive=UndefinedPrimitive; status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception); if (status == MagickFalse) break; } if (fabs(draw_info->dash_pattern[n]) >= MagickEpsilon) n++; if (fabs(draw_info->dash_pattern[n]) < MagickEpsilon) n=0; length=scale*draw_info->dash_pattern[n]; } length-=(maximum_length-total_length); if ((n & 0x01) != 0) continue; dash_polygon[j]=primitive_info[i]; dash_polygon[j].coordinates=1; j++; } if ((status != MagickFalse) && (total_length < maximum_length) && ((n & 0x01) == 0) && (j > 1)) { dash_polygon[j]=primitive_info[i-1]; dash_polygon[j].point.x+=MagickEpsilon; dash_polygon[j].point.y+=MagickEpsilon; dash_polygon[j].coordinates=1; j++; dash_polygon[0].coordinates=(size_t) j; dash_polygon[j].primitive=UndefinedPrimitive; status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception); } dash_polygon=(PrimitiveInfo *) RelinquishMagickMemory(dash_polygon); clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-dash"); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w G r a d i e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawGradientImage() draws a linear gradient on the image. % % The format of the DrawGradientImage method is: % % MagickBooleanType DrawGradientImage(Image *image, % const DrawInfo *draw_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o exception: return any errors or warnings in this structure. % */ static inline double GetStopColorOffset(const GradientInfo *gradient, const ssize_t x,const ssize_t y) { switch (gradient->type) { case UndefinedGradient: case LinearGradient: { double gamma, length, offset, scale; PointInfo p, q; const SegmentInfo *gradient_vector; gradient_vector=(&gradient->gradient_vector); p.x=gradient_vector->x2-gradient_vector->x1; p.y=gradient_vector->y2-gradient_vector->y1; q.x=(double) x-gradient_vector->x1; q.y=(double) y-gradient_vector->y1; length=sqrt(q.x*q.x+q.y*q.y); gamma=sqrt(p.x*p.x+p.y*p.y)*length; gamma=PerceptibleReciprocal(gamma); scale=p.x*q.x+p.y*q.y; offset=gamma*scale*length; return(offset); } case RadialGradient: { PointInfo v; if (gradient->spread == RepeatSpread) { v.x=(double) x-gradient->center.x; v.y=(double) y-gradient->center.y; return(sqrt(v.x*v.x+v.y*v.y)); } v.x=(double) (((x-gradient->center.x)*cos(DegreesToRadians( gradient->angle)))+((y-gradient->center.y)*sin(DegreesToRadians( gradient->angle))))*PerceptibleReciprocal(gradient->radii.x); v.y=(double) (((x-gradient->center.x)*sin(DegreesToRadians( gradient->angle)))-((y-gradient->center.y)*cos(DegreesToRadians( gradient->angle))))*PerceptibleReciprocal(gradient->radii.y); return(sqrt(v.x*v.x+v.y*v.y)); } } return(0.0); } static int StopInfoCompare(const void *x,const void *y) { StopInfo *stop_1, *stop_2; stop_1=(StopInfo *) x; stop_2=(StopInfo *) y; if (stop_1->offset > stop_2->offset) return(1); if (fabs(stop_1->offset-stop_2->offset) <= MagickEpsilon) return(0); return(-1); } MagickExport MagickBooleanType DrawGradientImage(Image *image, const DrawInfo *draw_info,ExceptionInfo *exception) { CacheView *image_view; const GradientInfo *gradient; const SegmentInfo *gradient_vector; double length; MagickBooleanType status; PixelInfo zero; PointInfo point; RectangleInfo bounding_box; ssize_t y; /* Draw linear or radial gradient on image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); gradient=(&draw_info->gradient); qsort(gradient->stops,gradient->number_stops,sizeof(StopInfo), StopInfoCompare); gradient_vector=(&gradient->gradient_vector); point.x=gradient_vector->x2-gradient_vector->x1; point.y=gradient_vector->y2-gradient_vector->y1; length=sqrt(point.x*point.x+point.y*point.y); bounding_box=gradient->bounding_box; status=MagickTrue; GetPixelInfo(image,&zero); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,bounding_box.height-bounding_box.y,1) #endif for (y=bounding_box.y; y < (ssize_t) bounding_box.height; y++) { double alpha, offset; PixelInfo composite, pixel; Quantum *magick_restrict q; ssize_t i, x; ssize_t j; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } pixel=zero; composite=zero; offset=GetStopColorOffset(gradient,0,y); if (gradient->type != RadialGradient) offset*=PerceptibleReciprocal(length); for (x=bounding_box.x; x < (ssize_t) bounding_box.width; x++) { GetPixelInfoPixel(image,q,&pixel); switch (gradient->spread) { case UndefinedSpread: case PadSpread: { if ((x != CastDoubleToLong(ceil(gradient_vector->x1-0.5))) || (y != CastDoubleToLong(ceil(gradient_vector->y1-0.5)))) { offset=GetStopColorOffset(gradient,x,y); if (gradient->type != RadialGradient) offset*=PerceptibleReciprocal(length); } for (i=0; i < (ssize_t) gradient->number_stops; i++) if (offset < gradient->stops[i].offset) break; if ((offset < 0.0) || (i == 0)) composite=gradient->stops[0].color; else if ((offset > 1.0) || (i == (ssize_t) gradient->number_stops)) composite=gradient->stops[gradient->number_stops-1].color; else { j=i; i--; alpha=(offset-gradient->stops[i].offset)/ (gradient->stops[j].offset-gradient->stops[i].offset); CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha, &gradient->stops[j].color,alpha,&composite); } break; } case ReflectSpread: { if ((x != CastDoubleToLong(ceil(gradient_vector->x1-0.5))) || (y != CastDoubleToLong(ceil(gradient_vector->y1-0.5)))) { offset=GetStopColorOffset(gradient,x,y); if (gradient->type != RadialGradient) offset*=PerceptibleReciprocal(length); } if (offset < 0.0) offset=(-offset); if ((ssize_t) fmod(offset,2.0) == 0) offset=fmod(offset,1.0); else offset=1.0-fmod(offset,1.0); for (i=0; i < (ssize_t) gradient->number_stops; i++) if (offset < gradient->stops[i].offset) break; if (i == 0) composite=gradient->stops[0].color; else if (i == (ssize_t) gradient->number_stops) composite=gradient->stops[gradient->number_stops-1].color; else { j=i; i--; alpha=(offset-gradient->stops[i].offset)/ (gradient->stops[j].offset-gradient->stops[i].offset); CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha, &gradient->stops[j].color,alpha,&composite); } break; } case RepeatSpread: { double repeat; MagickBooleanType antialias; antialias=MagickFalse; repeat=0.0; if ((x != CastDoubleToLong(ceil(gradient_vector->x1-0.5))) || (y != CastDoubleToLong(ceil(gradient_vector->y1-0.5)))) { offset=GetStopColorOffset(gradient,x,y); if (gradient->type == LinearGradient) { repeat=fmod(offset,length); if (repeat < 0.0) repeat=length-fmod(-repeat,length); else repeat=fmod(offset,length); antialias=(repeat < length) && ((repeat+1.0) > length) ? MagickTrue : MagickFalse; offset=PerceptibleReciprocal(length)*repeat; } else { repeat=fmod(offset,gradient->radius); if (repeat < 0.0) repeat=gradient->radius-fmod(-repeat,gradient->radius); else repeat=fmod(offset,gradient->radius); antialias=repeat+1.0 > gradient->radius ? MagickTrue : MagickFalse; offset=repeat*PerceptibleReciprocal(gradient->radius); } } for (i=0; i < (ssize_t) gradient->number_stops; i++) if (offset < gradient->stops[i].offset) break; if (i == 0) composite=gradient->stops[0].color; else if (i == (ssize_t) gradient->number_stops) composite=gradient->stops[gradient->number_stops-1].color; else { j=i; i--; alpha=(offset-gradient->stops[i].offset)/ (gradient->stops[j].offset-gradient->stops[i].offset); if (antialias != MagickFalse) { if (gradient->type == LinearGradient) alpha=length-repeat; else alpha=gradient->radius-repeat; i=0; j=(ssize_t) gradient->number_stops-1L; } CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha, &gradient->stops[j].color,alpha,&composite); } break; } } CompositePixelInfoOver(&composite,composite.alpha,&pixel,pixel.alpha, &pixel); SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawImage() draws a graphic primitive on your image. The primitive % may be represented as a string or filename. Precede the filename with an % "at" sign (@) and the contents of the file are drawn on the image. You % can affect how text is drawn by setting one or more members of the draw % info structure. % % The format of the DrawImage method is: % % MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType CheckPrimitiveExtent(MVGInfo *mvg_info, const double pad) { double extent; size_t quantum; /* Check if there is enough storage for drawing pimitives. */ quantum=sizeof(**mvg_info->primitive_info); extent=(double) mvg_info->offset+pad+(PrimitiveExtentPad+1)*quantum; if (extent <= (double) *mvg_info->extent) return(MagickTrue); if (extent == (double) CastDoubleToLong(extent)) { *mvg_info->primitive_info=(PrimitiveInfo *) ResizeQuantumMemory( *mvg_info->primitive_info,(size_t) (extent+1),quantum); if (*mvg_info->primitive_info != (PrimitiveInfo *) NULL) { ssize_t i; *mvg_info->extent=(size_t) extent; for (i=mvg_info->offset+1; i <= (ssize_t) extent; i++) { (*mvg_info->primitive_info)[i].primitive=UndefinedPrimitive; (*mvg_info->primitive_info)[i].text=(char *) NULL; } return(MagickTrue); } } /* Reallocation failed, allocate a primitive to facilitate unwinding. */ (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); if (*mvg_info->primitive_info != (PrimitiveInfo *) NULL) *mvg_info->primitive_info=(PrimitiveInfo *) RelinquishMagickMemory( *mvg_info->primitive_info); *mvg_info->primitive_info=(PrimitiveInfo *) AcquireCriticalMemory((size_t) ( (PrimitiveExtentPad+1)*quantum)); (void) memset(*mvg_info->primitive_info,0,(size_t) ((PrimitiveExtentPad+1)* quantum)); *mvg_info->extent=1; mvg_info->offset=0; return(MagickFalse); } static inline double GetDrawValue(const char *magick_restrict string, char **magick_restrict sentinal) { char **magick_restrict q; double value; q=sentinal; value=InterpretLocaleValue(string,q); sentinal=q; return(value); } static int MVGMacroCompare(const void *target,const void *source) { const char *p, *q; p=(const char *) target; q=(const char *) source; return(strcmp(p,q)); } static SplayTreeInfo *GetMVGMacros(const char *primitive) { char *macro, *token; const char *q; size_t extent; SplayTreeInfo *macros; /* Scan graphic primitives for definitions and classes. */ if (primitive == (const char *) NULL) return((SplayTreeInfo *) NULL); macros=NewSplayTree(MVGMacroCompare,RelinquishMagickMemory, RelinquishMagickMemory); macro=AcquireString(primitive); token=AcquireString(primitive); extent=strlen(token)+MagickPathExtent; for (q=primitive; *q != '\0'; ) { if (GetNextToken(q,&q,extent,token) < 1) break; if (*token == '\0') break; if (LocaleCompare("push",token) == 0) { const char *end, *start; (void) GetNextToken(q,&q,extent,token); if (*q == '"') { char name[MagickPathExtent]; const char *p; ssize_t n; /* Named macro (e.g. push graphic-context "wheel"). */ (void) GetNextToken(q,&q,extent,token); start=q; end=q; (void) CopyMagickString(name,token,MagickPathExtent); n=1; for (p=q; *p != '\0'; ) { if (GetNextToken(p,&p,extent,token) < 1) break; if (*token == '\0') break; if (LocaleCompare(token,"pop") == 0) { end=p-strlen(token)-1; n--; } if (LocaleCompare(token,"push") == 0) n++; if ((n == 0) && (end > start)) { /* Extract macro. */ (void) GetNextToken(p,&p,extent,token); (void) CopyMagickString(macro,start,(size_t) (end-start)); (void) AddValueToSplayTree(macros,ConstantString(name), ConstantString(macro)); break; } } } } } token=DestroyString(token); macro=DestroyString(macro); return(macros); } static inline MagickBooleanType IsPoint(const char *point) { char *p; double value; value=GetDrawValue(point,&p); return((fabs(value) < MagickEpsilon) && (p == point) ? MagickFalse : MagickTrue); } static inline MagickBooleanType TracePoint(PrimitiveInfo *primitive_info, const PointInfo point) { primitive_info->coordinates=1; primitive_info->closed_subpath=MagickFalse; primitive_info->point=point; return(MagickTrue); } static MagickBooleanType RenderMVGContent(Image *image, const DrawInfo *draw_info,const size_t depth,ExceptionInfo *exception) { #define RenderImageTag "Render/Image" AffineMatrix affine, current; char keyword[MagickPathExtent], geometry[MagickPathExtent], *next_token, pattern[MagickPathExtent], *primitive, *token; const char *q; double angle, coordinates, cursor, factor, primitive_extent; DrawInfo *clone_info, **graphic_context; MagickBooleanType proceed; MagickStatusType status; MVGInfo mvg_info; PointInfo point; PrimitiveInfo *primitive_info; PrimitiveType primitive_type; const char *p; ssize_t i, x; SegmentInfo bounds; size_t extent, number_points, number_stops; SplayTreeInfo *macros; ssize_t defsDepth, j, k, n, symbolDepth; StopInfo *stops; TypeMetric metrics; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if (depth > MagickMaxRecursionDepth) ThrowBinaryException(DrawError,"VectorGraphicsNestedTooDeeply", image->filename); if ((draw_info->primitive == (char *) NULL) || (*draw_info->primitive == '\0')) return(MagickFalse); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"begin draw-image"); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (image->alpha_trait == UndefinedPixelTrait) { status=SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); if (status == MagickFalse) return(MagickFalse); } if ((*draw_info->primitive == '@') && (strlen(draw_info->primitive) > 1) && (*(draw_info->primitive+1) != '-') && (depth == 0)) primitive=FileToString(draw_info->primitive+1,~0UL,exception); else primitive=AcquireString(draw_info->primitive); if (primitive == (char *) NULL) return(MagickFalse); primitive_extent=(double) strlen(primitive); (void) SetImageArtifact(image,"mvg:vector-graphics",primitive); n=0; number_stops=0; stops=(StopInfo *) NULL; /* Allocate primitive info memory. */ graphic_context=(DrawInfo **) AcquireMagickMemory(sizeof(*graphic_context)); if (graphic_context == (DrawInfo **) NULL) { primitive=DestroyString(primitive); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } number_points=(size_t) PrimitiveExtentPad; primitive_info=(PrimitiveInfo *) AcquireQuantumMemory((size_t) (number_points+1),sizeof(*primitive_info)); if (primitive_info == (PrimitiveInfo *) NULL) { primitive=DestroyString(primitive); for ( ; n >= 0; n--) graphic_context[n]=DestroyDrawInfo(graphic_context[n]); graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) memset(primitive_info,0,(size_t) (number_points+1)* sizeof(*primitive_info)); (void) memset(&mvg_info,0,sizeof(mvg_info)); mvg_info.primitive_info=(&primitive_info); mvg_info.extent=(&number_points); mvg_info.exception=exception; graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,draw_info); graphic_context[n]->viewbox=image->page; if ((image->page.width == 0) || (image->page.height == 0)) { graphic_context[n]->viewbox.width=image->columns; graphic_context[n]->viewbox.height=image->rows; } token=AcquireString(primitive); extent=strlen(token)+MagickPathExtent; defsDepth=0; symbolDepth=0; cursor=0.0; macros=GetMVGMacros(primitive); status=MagickTrue; for (q=primitive; *q != '\0'; ) { /* Interpret graphic primitive. */ if (GetNextToken(q,&q,MagickPathExtent,keyword) < 1) break; if (*keyword == '\0') break; if (*keyword == '#') { /* Comment. */ while ((*q != '\n') && (*q != '\0')) q++; continue; } p=q-strlen(keyword)-1; primitive_type=UndefinedPrimitive; current=graphic_context[n]->affine; GetAffineMatrix(&affine); *token='\0'; switch (*keyword) { case ';': break; case 'a': case 'A': { if (LocaleCompare("affine",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); affine.sx=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.rx=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.ry=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.sy=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.tx=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.ty=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("alpha",keyword) == 0) { primitive_type=AlphaPrimitive; break; } if (LocaleCompare("arc",keyword) == 0) { primitive_type=ArcPrimitive; break; } status=MagickFalse; break; } case 'b': case 'B': { if (LocaleCompare("bezier",keyword) == 0) { primitive_type=BezierPrimitive; break; } if (LocaleCompare("border-color",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->border_color,exception); break; } status=MagickFalse; break; } case 'c': case 'C': { if (LocaleCompare("class",keyword) == 0) { const char *mvg_class; (void) GetNextToken(q,&q,extent,token); if (*token == '\0') { status=MagickFalse; break; } if (LocaleCompare(token,graphic_context[n]->id) == 0) break; mvg_class=(const char *) GetValueFromSplayTree(macros,token); if ((mvg_class != (const char *) NULL) && (p > primitive)) { char *elements; ssize_t offset; /* Inject class elements in stream. */ offset=(ssize_t) (p-primitive); elements=AcquireString(primitive); elements[offset]='\0'; (void) ConcatenateString(&elements,mvg_class); (void) ConcatenateString(&elements,"\n"); (void) ConcatenateString(&elements,q); primitive=DestroyString(primitive); primitive=elements; q=primitive+offset; } break; } if (LocaleCompare("clip-path",keyword) == 0) { const char *clip_path; /* Take a node from within the MVG document, and duplicate it here. */ (void) GetNextToken(q,&q,extent,token); if (*token == '\0') { status=MagickFalse; break; } (void) CloneString(&graphic_context[n]->clip_mask,token); clip_path=(const char *) GetValueFromSplayTree(macros,token); if (clip_path != (const char *) NULL) { if (graphic_context[n]->clipping_mask != (Image *) NULL) graphic_context[n]->clipping_mask= DestroyImage(graphic_context[n]->clipping_mask); graphic_context[n]->clipping_mask=DrawClippingMask(image, graphic_context[n],token,clip_path,exception); if (graphic_context[n]->compliance != SVGCompliance) { clip_path=(const char *) GetValueFromSplayTree(macros, graphic_context[n]->clip_mask); if (clip_path != (const char *) NULL) (void) SetImageArtifact(image, graphic_context[n]->clip_mask,clip_path); status&=DrawClipPath(image,graphic_context[n], graphic_context[n]->clip_mask,exception); } } break; } if (LocaleCompare("clip-rule",keyword) == 0) { ssize_t fill_rule; (void) GetNextToken(q,&q,extent,token); fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse, token); if (fill_rule == -1) { status=MagickFalse; break; } graphic_context[n]->fill_rule=(FillRule) fill_rule; break; } if (LocaleCompare("clip-units",keyword) == 0) { ssize_t clip_units; (void) GetNextToken(q,&q,extent,token); clip_units=ParseCommandOption(MagickClipPathOptions,MagickFalse, token); if (clip_units == -1) { status=MagickFalse; break; } graphic_context[n]->clip_units=(ClipPathUnits) clip_units; if (clip_units == ObjectBoundingBox) { GetAffineMatrix(&current); affine.sx=draw_info->bounds.x2; affine.sy=draw_info->bounds.y2; affine.tx=draw_info->bounds.x1; affine.ty=draw_info->bounds.y1; break; } break; } if (LocaleCompare("circle",keyword) == 0) { primitive_type=CirclePrimitive; break; } if (LocaleCompare("color",keyword) == 0) { primitive_type=ColorPrimitive; break; } if (LocaleCompare("compliance",keyword) == 0) { /* MVG compliance associates a clipping mask with an image; SVG compliance associates a clipping mask with a graphics context. */ (void) GetNextToken(q,&q,extent,token); graphic_context[n]->compliance=(ComplianceType) ParseCommandOption( MagickComplianceOptions,MagickFalse,token); break; } if (LocaleCompare("currentColor",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); break; } status=MagickFalse; break; } case 'd': case 'D': { if (LocaleCompare("decorate",keyword) == 0) { ssize_t decorate; (void) GetNextToken(q,&q,extent,token); decorate=ParseCommandOption(MagickDecorateOptions,MagickFalse, token); if (decorate == -1) { status=MagickFalse; break; } graphic_context[n]->decorate=(DecorationType) decorate; break; } if (LocaleCompare("density",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->density,token); break; } if (LocaleCompare("direction",keyword) == 0) { ssize_t direction; (void) GetNextToken(q,&q,extent,token); direction=ParseCommandOption(MagickDirectionOptions,MagickFalse, token); if (direction == -1) status=MagickFalse; else graphic_context[n]->direction=(DirectionType) direction; break; } status=MagickFalse; break; } case 'e': case 'E': { if (LocaleCompare("ellipse",keyword) == 0) { primitive_type=EllipsePrimitive; break; } if (LocaleCompare("encoding",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->encoding,token); break; } status=MagickFalse; break; } case 'f': case 'F': { if (LocaleCompare("fill",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; (void) FormatLocaleString(pattern,MagickPathExtent,"%s",token); if (GetImageArtifact(image,pattern) != (const char *) NULL) (void) DrawPatternPath(image,draw_info,token, &graphic_context[n]->fill_pattern,exception); else { status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->fill,exception); if (graphic_context[n]->fill_alpha != OpaqueAlpha) graphic_context[n]->fill.alpha=graphic_context[n]->fill_alpha; } break; } if (LocaleCompare("fill-opacity",keyword) == 0) { double opacity; (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; opacity=MagickMin(MagickMax(factor* GetDrawValue(token,&next_token),0.0),1.0); if (token == next_token) ThrowPointExpectedException(token,exception); if (graphic_context[n]->compliance == SVGCompliance) graphic_context[n]->fill_alpha*=opacity; else graphic_context[n]->fill_alpha=QuantumRange*opacity; if (graphic_context[n]->fill.alpha != TransparentAlpha) graphic_context[n]->fill.alpha=graphic_context[n]->fill_alpha; else graphic_context[n]->fill.alpha=(MagickRealType) ClampToQuantum(QuantumRange*(1.0-opacity)); break; } if (LocaleCompare("fill-rule",keyword) == 0) { ssize_t fill_rule; (void) GetNextToken(q,&q,extent,token); fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse, token); if (fill_rule == -1) { status=MagickFalse; break; } graphic_context[n]->fill_rule=(FillRule) fill_rule; break; } if (LocaleCompare("font",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->font,token); if (LocaleCompare("none",token) == 0) graphic_context[n]->font=(char *) RelinquishMagickMemory( graphic_context[n]->font); break; } if (LocaleCompare("font-family",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->family,token); break; } if (LocaleCompare("font-size",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->pointsize=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("font-stretch",keyword) == 0) { ssize_t stretch; (void) GetNextToken(q,&q,extent,token); stretch=ParseCommandOption(MagickStretchOptions,MagickFalse,token); if (stretch == -1) { status=MagickFalse; break; } graphic_context[n]->stretch=(StretchType) stretch; break; } if (LocaleCompare("font-style",keyword) == 0) { ssize_t style; (void) GetNextToken(q,&q,extent,token); style=ParseCommandOption(MagickStyleOptions,MagickFalse,token); if (style == -1) { status=MagickFalse; break; } graphic_context[n]->style=(StyleType) style; break; } if (LocaleCompare("font-weight",keyword) == 0) { ssize_t weight; (void) GetNextToken(q,&q,extent,token); weight=ParseCommandOption(MagickWeightOptions,MagickFalse,token); if (weight == -1) weight=(ssize_t) StringToUnsignedLong(token); graphic_context[n]->weight=(size_t) weight; break; } status=MagickFalse; break; } case 'g': case 'G': { if (LocaleCompare("gradient-units",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("gravity",keyword) == 0) { ssize_t gravity; (void) GetNextToken(q,&q,extent,token); gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,token); if (gravity == -1) { status=MagickFalse; break; } graphic_context[n]->gravity=(GravityType) gravity; break; } status=MagickFalse; break; } case 'i': case 'I': { if (LocaleCompare("image",keyword) == 0) { ssize_t compose; primitive_type=ImagePrimitive; (void) GetNextToken(q,&q,extent,token); compose=ParseCommandOption(MagickComposeOptions,MagickFalse,token); if (compose == -1) { status=MagickFalse; break; } graphic_context[n]->compose=(CompositeOperator) compose; break; } if (LocaleCompare("interline-spacing",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->interline_spacing=GetDrawValue(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("interword-spacing",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->interword_spacing=GetDrawValue(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } status=MagickFalse; break; } case 'k': case 'K': { if (LocaleCompare("kerning",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->kerning=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } status=MagickFalse; break; } case 'l': case 'L': { if (LocaleCompare("letter-spacing",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); if (IsPoint(token) == MagickFalse) break; clone_info=CloneDrawInfo((ImageInfo *) NULL,graphic_context[n]); clone_info->text=AcquireString(" "); status&=GetTypeMetrics(image,clone_info,&metrics,exception); graphic_context[n]->kerning=metrics.width* GetDrawValue(token,&next_token); clone_info=DestroyDrawInfo(clone_info); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("line",keyword) == 0) { primitive_type=LinePrimitive; break; } status=MagickFalse; break; } case 'm': case 'M': { if (LocaleCompare("mask",keyword) == 0) { const char *mask_path; /* Take a node from within the MVG document, and duplicate it here. */ (void) GetNextToken(q,&q,extent,token); mask_path=(const char *) GetValueFromSplayTree(macros,token); if (mask_path != (const char *) NULL) { if (graphic_context[n]->composite_mask != (Image *) NULL) graphic_context[n]->composite_mask= DestroyImage(graphic_context[n]->composite_mask); graphic_context[n]->composite_mask=DrawCompositeMask(image, graphic_context[n],token,mask_path,exception); if (graphic_context[n]->compliance != SVGCompliance) status=SetImageMask(image,CompositePixelMask, graphic_context[n]->composite_mask,exception); } break; } status=MagickFalse; break; } case 'o': case 'O': { if (LocaleCompare("offset",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("opacity",keyword) == 0) { double opacity; (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; opacity=MagickMin(MagickMax(factor* GetDrawValue(token,&next_token),0.0),1.0); if (token == next_token) ThrowPointExpectedException(token,exception); if (graphic_context[n]->compliance == SVGCompliance) { graphic_context[n]->fill_alpha*=opacity; graphic_context[n]->stroke_alpha*=opacity; } else { graphic_context[n]->fill_alpha=QuantumRange*opacity; graphic_context[n]->stroke_alpha=QuantumRange*opacity; } break; } status=MagickFalse; break; } case 'p': case 'P': { if (LocaleCompare("path",keyword) == 0) { primitive_type=PathPrimitive; break; } if (LocaleCompare("point",keyword) == 0) { primitive_type=PointPrimitive; break; } if (LocaleCompare("polyline",keyword) == 0) { primitive_type=PolylinePrimitive; break; } if (LocaleCompare("polygon",keyword) == 0) { primitive_type=PolygonPrimitive; break; } if (LocaleCompare("pop",keyword) == 0) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare("class",token) == 0) break; if (LocaleCompare("clip-path",token) == 0) break; if (LocaleCompare("defs",token) == 0) { defsDepth--; graphic_context[n]->render=defsDepth > 0 ? MagickFalse : MagickTrue; break; } if (LocaleCompare("gradient",token) == 0) break; if (LocaleCompare("graphic-context",token) == 0) { if (n <= 0) { (void) ThrowMagickException(exception,GetMagickModule(), DrawError,"UnbalancedGraphicContextPushPop","`%s'",token); status=MagickFalse; n=0; break; } if ((graphic_context[n]->clip_mask != (char *) NULL) && (graphic_context[n]->compliance != SVGCompliance)) if (LocaleCompare(graphic_context[n]->clip_mask, graphic_context[n-1]->clip_mask) != 0) status=SetImageMask(image,WritePixelMask,(Image *) NULL, exception); graphic_context[n]=DestroyDrawInfo(graphic_context[n]); n--; break; } if (LocaleCompare("mask",token) == 0) break; if (LocaleCompare("pattern",token) == 0) break; if (LocaleCompare("symbol",token) == 0) { symbolDepth--; graphic_context[n]->render=symbolDepth > 0 ? MagickFalse : MagickTrue; break; } status=MagickFalse; break; } if (LocaleCompare("push",keyword) == 0) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare("class",token) == 0) { /* Class context. */ for (p=q; *q != '\0'; ) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare(token,"pop") != 0) continue; (void) GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"class") != 0) continue; break; } (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("clip-path",token) == 0) { (void) GetNextToken(q,&q,extent,token); for (p=q; *q != '\0'; ) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare(token,"pop") != 0) continue; (void) GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"clip-path") != 0) continue; break; } if ((q == (char *) NULL) || (p == (char *) NULL) || ((q-4) < p)) { status=MagickFalse; break; } (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("defs",token) == 0) { defsDepth++; graphic_context[n]->render=defsDepth > 0 ? MagickFalse : MagickTrue; break; } if (LocaleCompare("gradient",token) == 0) { char key[2*MagickPathExtent], name[MagickPathExtent], type[MagickPathExtent]; SegmentInfo segment; (void) GetNextToken(q,&q,extent,token); (void) CopyMagickString(name,token,MagickPathExtent); (void) GetNextToken(q,&q,extent,token); (void) CopyMagickString(type,token,MagickPathExtent); (void) GetNextToken(q,&q,extent,token); segment.x1=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); segment.y1=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); segment.x2=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); segment.y2=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); if (LocaleCompare(type,"radial") == 0) { (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); } for (p=q; *q != '\0'; ) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare(token,"pop") != 0) continue; (void) GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"gradient") != 0) continue; break; } if ((q == (char *) NULL) || (p == (char *) NULL) || ((q-4) < p)) { status=MagickFalse; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); bounds.x1=graphic_context[n]->affine.sx*segment.x1+ graphic_context[n]->affine.ry*segment.y1+ graphic_context[n]->affine.tx; bounds.y1=graphic_context[n]->affine.rx*segment.x1+ graphic_context[n]->affine.sy*segment.y1+ graphic_context[n]->affine.ty; bounds.x2=graphic_context[n]->affine.sx*segment.x2+ graphic_context[n]->affine.ry*segment.y2+ graphic_context[n]->affine.tx; bounds.y2=graphic_context[n]->affine.rx*segment.x2+ graphic_context[n]->affine.sy*segment.y2+ graphic_context[n]->affine.ty; (void) FormatLocaleString(key,MagickPathExtent,"%s",name); (void) SetImageArtifact(image,key,token); (void) FormatLocaleString(key,MagickPathExtent,"%s-type",name); (void) SetImageArtifact(image,key,type); (void) FormatLocaleString(key,MagickPathExtent,"%s-geometry", name); (void) FormatLocaleString(geometry,MagickPathExtent, "%gx%g%+.15g%+.15g", MagickMax(fabs(bounds.x2-bounds.x1+1.0),1.0), MagickMax(fabs(bounds.y2-bounds.y1+1.0),1.0), bounds.x1,bounds.y1); (void) SetImageArtifact(image,key,geometry); (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("graphic-context",token) == 0) { n++; graphic_context=(DrawInfo **) ResizeQuantumMemory( graphic_context,(size_t) (n+1),sizeof(*graphic_context)); if (graphic_context == (DrawInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL, graphic_context[n-1]); if (*q == '"') { (void) GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->id,token); } break; } if (LocaleCompare("mask",token) == 0) { (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("pattern",token) == 0) { char key[2*MagickPathExtent], name[MagickPathExtent]; RectangleInfo bounds; (void) GetNextToken(q,&q,extent,token); (void) CopyMagickString(name,token,MagickPathExtent); (void) GetNextToken(q,&q,extent,token); bounds.x=CastDoubleToLong(ceil(GetDrawValue(token, &next_token)-0.5)); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); bounds.y=CastDoubleToLong(ceil(GetDrawValue(token, &next_token)-0.5)); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); bounds.width=(size_t) CastDoubleToLong(floor(GetDrawValue( token,&next_token)+0.5)); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); bounds.height=(size_t) floor(GetDrawValue(token,&next_token)+ 0.5); if (token == next_token) ThrowPointExpectedException(token,exception); for (p=q; *q != '\0'; ) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare(token,"pop") != 0) continue; (void) GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"pattern") != 0) continue; break; } if ((q == (char *) NULL) || (p == (char *) NULL) || ((q-4) < p)) { status=MagickFalse; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); (void) FormatLocaleString(key,MagickPathExtent,"%s",name); (void) SetImageArtifact(image,key,token); (void) FormatLocaleString(key,MagickPathExtent,"%s-geometry", name); (void) FormatLocaleString(geometry,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) bounds.width,(double) bounds.height,(double) bounds.x,(double) bounds.y); (void) SetImageArtifact(image,key,geometry); (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("symbol",token) == 0) { symbolDepth++; graphic_context[n]->render=symbolDepth > 0 ? MagickFalse : MagickTrue; break; } status=MagickFalse; break; } status=MagickFalse; break; } case 'r': case 'R': { if (LocaleCompare("rectangle",keyword) == 0) { primitive_type=RectanglePrimitive; break; } if (LocaleCompare("rotate",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); angle=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); affine.sx=cos(DegreesToRadians(fmod((double) angle,360.0))); affine.rx=sin(DegreesToRadians(fmod((double) angle,360.0))); affine.ry=(-sin(DegreesToRadians(fmod((double) angle,360.0)))); affine.sy=cos(DegreesToRadians(fmod((double) angle,360.0))); break; } if (LocaleCompare("roundRectangle",keyword) == 0) { primitive_type=RoundRectanglePrimitive; break; } status=MagickFalse; break; } case 's': case 'S': { if (LocaleCompare("scale",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); affine.sx=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.sy=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("skewX",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); angle=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); affine.ry=sin(DegreesToRadians(angle)); break; } if (LocaleCompare("skewY",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); angle=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); affine.rx=(-tan(DegreesToRadians(angle)/2.0)); break; } if (LocaleCompare("stop-color",keyword) == 0) { PixelInfo stop_color; number_stops++; if (number_stops == 1) stops=(StopInfo *) AcquireQuantumMemory(2,sizeof(*stops)); else if (number_stops > 2) stops=(StopInfo *) ResizeQuantumMemory(stops,number_stops, sizeof(*stops)); if (stops == (StopInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } (void) GetNextToken(q,&q,extent,token); status&=QueryColorCompliance(token,AllCompliance,&stop_color, exception); stops[number_stops-1].color=stop_color; (void) GetNextToken(q,&q,extent,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; stops[number_stops-1].offset=factor*GetDrawValue(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("stroke",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; (void) FormatLocaleString(pattern,MagickPathExtent,"%s",token); if (GetImageArtifact(image,pattern) != (const char *) NULL) (void) DrawPatternPath(image,draw_info,token, &graphic_context[n]->stroke_pattern,exception); else { status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->stroke,exception); if (graphic_context[n]->stroke_alpha != OpaqueAlpha) graphic_context[n]->stroke.alpha= graphic_context[n]->stroke_alpha; } break; } if (LocaleCompare("stroke-antialias",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->stroke_antialias=StringToLong(token) != 0 ? MagickTrue : MagickFalse; break; } if (LocaleCompare("stroke-dasharray",keyword) == 0) { if (graphic_context[n]->dash_pattern != (double *) NULL) graphic_context[n]->dash_pattern=(double *) RelinquishMagickMemory(graphic_context[n]->dash_pattern); if (IsPoint(q) != MagickFalse) { const char *r; r=q; (void) GetNextToken(r,&r,extent,token); if (*token == ',') (void) GetNextToken(r,&r,extent,token); for (x=0; IsPoint(token) != MagickFalse; x++) { (void) GetNextToken(r,&r,extent,token); if (*token == ',') (void) GetNextToken(r,&r,extent,token); } graphic_context[n]->dash_pattern=(double *) AcquireQuantumMemory((size_t) (2*x+2), sizeof(*graphic_context[n]->dash_pattern)); if (graphic_context[n]->dash_pattern == (double *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); status=MagickFalse; break; } (void) memset(graphic_context[n]->dash_pattern,0,(size_t) (2*x+2)*sizeof(*graphic_context[n]->dash_pattern)); for (j=0; j < x; j++) { (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); graphic_context[n]->dash_pattern[j]=GetDrawValue(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); if (graphic_context[n]->dash_pattern[j] < 0.0) status=MagickFalse; } if ((x & 0x01) != 0) for ( ; j < (2*x); j++) graphic_context[n]->dash_pattern[j]= graphic_context[n]->dash_pattern[j-x]; graphic_context[n]->dash_pattern[j]=0.0; break; } (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("stroke-dashoffset",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->dash_offset=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("stroke-linecap",keyword) == 0) { ssize_t linecap; (void) GetNextToken(q,&q,extent,token); linecap=ParseCommandOption(MagickLineCapOptions,MagickFalse,token); if (linecap == -1) { status=MagickFalse; break; } graphic_context[n]->linecap=(LineCap) linecap; break; } if (LocaleCompare("stroke-linejoin",keyword) == 0) { ssize_t linejoin; (void) GetNextToken(q,&q,extent,token); linejoin=ParseCommandOption(MagickLineJoinOptions,MagickFalse, token); if (linejoin == -1) { status=MagickFalse; break; } graphic_context[n]->linejoin=(LineJoin) linejoin; break; } if (LocaleCompare("stroke-miterlimit",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->miterlimit=StringToUnsignedLong(token); break; } if (LocaleCompare("stroke-opacity",keyword) == 0) { double opacity; (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; opacity=MagickMin(MagickMax(factor* GetDrawValue(token,&next_token),0.0),1.0); if (token == next_token) ThrowPointExpectedException(token,exception); if (graphic_context[n]->compliance == SVGCompliance) graphic_context[n]->stroke_alpha*=opacity; else graphic_context[n]->stroke_alpha=QuantumRange*opacity; if (graphic_context[n]->stroke.alpha != TransparentAlpha) graphic_context[n]->stroke.alpha=graphic_context[n]->stroke_alpha; else graphic_context[n]->stroke.alpha=(MagickRealType) ClampToQuantum(QuantumRange*(1.0-opacity)); break; } if (LocaleCompare("stroke-width",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; graphic_context[n]->stroke_width=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } status=MagickFalse; break; } case 't': case 'T': { if (LocaleCompare("text",keyword) == 0) { primitive_type=TextPrimitive; cursor=0.0; break; } if (LocaleCompare("text-align",keyword) == 0) { ssize_t align; (void) GetNextToken(q,&q,extent,token); align=ParseCommandOption(MagickAlignOptions,MagickFalse,token); if (align == -1) { status=MagickFalse; break; } graphic_context[n]->align=(AlignType) align; break; } if (LocaleCompare("text-anchor",keyword) == 0) { ssize_t align; (void) GetNextToken(q,&q,extent,token); align=ParseCommandOption(MagickAlignOptions,MagickFalse,token); if (align == -1) { status=MagickFalse; break; } graphic_context[n]->align=(AlignType) align; break; } if (LocaleCompare("text-antialias",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->text_antialias=StringToLong(token) != 0 ? MagickTrue : MagickFalse; break; } if (LocaleCompare("text-undercolor",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->undercolor,exception); break; } if (LocaleCompare("translate",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); affine.tx=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.ty=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); cursor=0.0; break; } status=MagickFalse; break; } case 'u': case 'U': { if (LocaleCompare("use",keyword) == 0) { const char *use; /* Get a macro from the MVG document, and "use" it here. */ (void) GetNextToken(q,&q,extent,token); use=(const char *) GetValueFromSplayTree(macros,token); if (use != (const char *) NULL) { clone_info=CloneDrawInfo((ImageInfo *) NULL,graphic_context[n]); (void) CloneString(&clone_info->primitive,use); status=RenderMVGContent(image,clone_info,depth+1,exception); clone_info=DestroyDrawInfo(clone_info); } break; } status=MagickFalse; break; } case 'v': case 'V': { if (LocaleCompare("viewbox",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.x=CastDoubleToLong(ceil( GetDrawValue(token,&next_token)-0.5)); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.y=CastDoubleToLong(ceil( GetDrawValue(token,&next_token)-0.5)); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.width=(size_t) CastDoubleToLong( floor(GetDrawValue(token,&next_token)+0.5)); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.height=(size_t) CastDoubleToLong( floor(GetDrawValue(token,&next_token)+0.5)); if (token == next_token) ThrowPointExpectedException(token,exception); break; } status=MagickFalse; break; } case 'w': case 'W': { if (LocaleCompare("word-spacing",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->interword_spacing=GetDrawValue(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } status=MagickFalse; break; } default: { status=MagickFalse; break; } } if (status == MagickFalse) break; if ((fabs(affine.sx-1.0) >= MagickEpsilon) || (fabs(affine.rx) >= MagickEpsilon) || (fabs(affine.ry) >= MagickEpsilon) || (fabs(affine.sy-1.0) >= MagickEpsilon) || (fabs(affine.tx) >= MagickEpsilon) || (fabs(affine.ty) >= MagickEpsilon)) { graphic_context[n]->affine.sx=current.sx*affine.sx+current.ry*affine.rx; graphic_context[n]->affine.rx=current.rx*affine.sx+current.sy*affine.rx; graphic_context[n]->affine.ry=current.sx*affine.ry+current.ry*affine.sy; graphic_context[n]->affine.sy=current.rx*affine.ry+current.sy*affine.sy; graphic_context[n]->affine.tx=current.sx*affine.tx+current.ry*affine.ty+ current.tx; graphic_context[n]->affine.ty=current.rx*affine.tx+current.sy*affine.ty+ current.ty; } if (primitive_type == UndefinedPrimitive) { if (*q == '\0') { if (number_stops > 1) { GradientType type; type=LinearGradient; if (draw_info->gradient.type == RadialGradient) type=RadialGradient; (void) GradientImage(image,type,PadSpread,stops,number_stops, exception); } if (number_stops > 0) stops=(StopInfo *) RelinquishMagickMemory(stops); } if ((image->debug != MagickFalse) && (q > p)) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p-1),p); continue; } /* Parse the primitive attributes. */ for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) if ((primitive_info[i].primitive == TextPrimitive) || (primitive_info[i].primitive == ImagePrimitive)) if (primitive_info[i].text != (char *) NULL) primitive_info[i].text=DestroyString(primitive_info[i].text); i=0; mvg_info.offset=i; j=0; primitive_info[0].point.x=0.0; primitive_info[0].point.y=0.0; primitive_info[0].coordinates=0; primitive_info[0].method=FloodfillMethod; primitive_info[0].closed_subpath=MagickFalse; for (x=0; *q != '\0'; x++) { /* Define points. */ if (IsPoint(q) == MagickFalse) break; (void) GetNextToken(q,&q,extent,token); point.x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); point.y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,(const char **) NULL,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); primitive_info[i].primitive=primitive_type; primitive_info[i].point=point; primitive_info[i].coordinates=0; primitive_info[i].method=FloodfillMethod; primitive_info[i].closed_subpath=MagickFalse; i++; mvg_info.offset=i; if (i < (ssize_t) number_points) continue; status&=CheckPrimitiveExtent(&mvg_info,(double) number_points); } if (status == MagickFalse) break; if ((primitive_info[j].primitive == TextPrimitive) || (primitive_info[j].primitive == ImagePrimitive)) if (primitive_info[j].text != (char *) NULL) primitive_info[j].text=DestroyString(primitive_info[j].text); primitive_info[j].primitive=primitive_type; primitive_info[j].coordinates=(size_t) x; primitive_info[j].method=FloodfillMethod; primitive_info[j].closed_subpath=MagickFalse; /* Circumscribe primitive within a circle. */ bounds.x1=primitive_info[j].point.x; bounds.y1=primitive_info[j].point.y; bounds.x2=primitive_info[j].point.x; bounds.y2=primitive_info[j].point.y; for (k=1; k < (ssize_t) primitive_info[j].coordinates; k++) { point=primitive_info[j+k].point; if (point.x < bounds.x1) bounds.x1=point.x; if (point.y < bounds.y1) bounds.y1=point.y; if (point.x > bounds.x2) bounds.x2=point.x; if (point.y > bounds.y2) bounds.y2=point.y; } /* Speculate how many points our primitive might consume. */ coordinates=(double) primitive_info[j].coordinates; switch (primitive_type) { case RectanglePrimitive: { coordinates*=5.0; break; } case RoundRectanglePrimitive: { double alpha, beta, radius; alpha=bounds.x2-bounds.x1; beta=bounds.y2-bounds.y1; radius=hypot(alpha,beta); coordinates*=5.0; coordinates+=2.0*((size_t) ceil((double) MagickPI*radius))+6.0* BezierQuantum+360.0; break; } case BezierPrimitive: { coordinates=(BezierQuantum*(double) primitive_info[j].coordinates); break; } case PathPrimitive: { char *s, *t; (void) GetNextToken(q,&q,extent,token); coordinates=1.0; t=token; for (s=token; *s != '\0'; s=t) { double value; value=GetDrawValue(s,&t); (void) value; if (s == t) { t++; continue; } coordinates++; } for (s=token; *s != '\0'; s++) if (strspn(s,"AaCcQqSsTt") != 0) coordinates+=(20.0*BezierQuantum)+360.0; break; } default: break; } if (status == MagickFalse) break; if (((size_t) (i+coordinates)) >= number_points) { /* Resize based on speculative points required by primitive. */ number_points+=coordinates+1; if (number_points < (size_t) coordinates) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } mvg_info.offset=i; status&=CheckPrimitiveExtent(&mvg_info,(double) number_points); } status&=CheckPrimitiveExtent(&mvg_info,PrimitiveExtentPad); if (status == MagickFalse) break; mvg_info.offset=j; switch (primitive_type) { case PointPrimitive: default: { if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } status&=TracePoint(primitive_info+j,primitive_info[j].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case LinePrimitive: { double dx, dy, maximum_length; if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } dx=primitive_info[i].point.x-primitive_info[i-1].point.x; dy=primitive_info[i].point.y-primitive_info[i-1].point.y; maximum_length=hypot(dx,dy); if (maximum_length > (MaxBezierCoordinates/100.0)) ThrowPointExpectedException(keyword,exception); status&=TraceLine(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case RectanglePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } status&=TraceRectangle(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case RoundRectanglePrimitive: { if (primitive_info[j].coordinates != 3) { status=MagickFalse; break; } if ((primitive_info[j+2].point.x < 0.0) || (primitive_info[j+2].point.y < 0.0)) { status=MagickFalse; break; } if ((primitive_info[j+1].point.x-primitive_info[j].point.x) < 0.0) { status=MagickFalse; break; } if ((primitive_info[j+1].point.y-primitive_info[j].point.y) < 0.0) { status=MagickFalse; break; } status&=TraceRoundRectangle(&mvg_info,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case ArcPrimitive: { if (primitive_info[j].coordinates != 3) { status=MagickFalse; break; } status&=TraceArc(&mvg_info,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case EllipsePrimitive: { if (primitive_info[j].coordinates != 3) { status=MagickFalse; break; } if ((primitive_info[j+1].point.x < 0.0) || (primitive_info[j+1].point.y < 0.0)) { status=MagickFalse; break; } status&=TraceEllipse(&mvg_info,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case CirclePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } status&=TraceCircle(&mvg_info,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case PolylinePrimitive: { if (primitive_info[j].coordinates < 1) { status=MagickFalse; break; } break; } case PolygonPrimitive: { if (primitive_info[j].coordinates < 3) { status=MagickFalse; break; } primitive_info[i]=primitive_info[j]; primitive_info[i].coordinates=0; primitive_info[j].coordinates++; primitive_info[j].closed_subpath=MagickTrue; i++; break; } case BezierPrimitive: { if (primitive_info[j].coordinates < 3) { status=MagickFalse; break; } status&=TraceBezier(&mvg_info,primitive_info[j].coordinates); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case PathPrimitive: { coordinates=(double) TracePath(&mvg_info,token,exception); if (coordinates < 0.0) { status=MagickFalse; break; } i=(ssize_t) (j+coordinates); break; } case AlphaPrimitive: case ColorPrimitive: { ssize_t method; if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } (void) GetNextToken(q,&q,extent,token); method=ParseCommandOption(MagickMethodOptions,MagickFalse,token); if (method == -1) { status=MagickFalse; break; } primitive_info[j].method=(PaintMethod) method; break; } case TextPrimitive: { char geometry[MagickPathExtent]; if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } if (*token != ',') (void) GetNextToken(q,&q,extent,token); (void) CloneString(&primitive_info[j].text,token); /* Compute text cursor offset. */ clone_info=CloneDrawInfo((ImageInfo *) NULL,graphic_context[n]); if ((fabs(mvg_info.point.x-primitive_info->point.x) < MagickEpsilon) && (fabs(mvg_info.point.y-primitive_info->point.y) < MagickEpsilon)) { mvg_info.point=primitive_info->point; primitive_info->point.x+=cursor; } else { mvg_info.point=primitive_info->point; cursor=0.0; } (void) FormatLocaleString(geometry,MagickPathExtent,"%+f%+f", primitive_info->point.x,primitive_info->point.y); clone_info->render=MagickFalse; clone_info->text=AcquireString(token); status&=GetTypeMetrics(image,clone_info,&metrics,exception); clone_info=DestroyDrawInfo(clone_info); cursor+=metrics.width; if (graphic_context[n]->compliance != SVGCompliance) cursor=0.0; break; } case ImagePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } (void) GetNextToken(q,&q,extent,token); (void) CloneString(&primitive_info[j].text,token); break; } } mvg_info.offset=i; if (status == 0) break; primitive_info[i].primitive=UndefinedPrimitive; if ((image->debug != MagickFalse) && (q > p)) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p-1), p); /* Sanity check. */ status&=CheckPrimitiveExtent(&mvg_info,ExpandAffine( &graphic_context[n]->affine)); if (status == 0) break; status&=CheckPrimitiveExtent(&mvg_info,(double) graphic_context[n]->stroke_width); if (status == 0) break; if (i == 0) continue; /* Transform points. */ for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) { point=primitive_info[i].point; primitive_info[i].point.x=graphic_context[n]->affine.sx*point.x+ graphic_context[n]->affine.ry*point.y+graphic_context[n]->affine.tx; primitive_info[i].point.y=graphic_context[n]->affine.rx*point.x+ graphic_context[n]->affine.sy*point.y+graphic_context[n]->affine.ty; point=primitive_info[i].point; if (point.x < graphic_context[n]->bounds.x1) graphic_context[n]->bounds.x1=point.x; if (point.y < graphic_context[n]->bounds.y1) graphic_context[n]->bounds.y1=point.y; if (point.x > graphic_context[n]->bounds.x2) graphic_context[n]->bounds.x2=point.x; if (point.y > graphic_context[n]->bounds.y2) graphic_context[n]->bounds.y2=point.y; if (primitive_info[i].primitive == ImagePrimitive) break; if (i >= (ssize_t) number_points) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); } if (graphic_context[n]->render != MagickFalse) { if ((n != 0) && (graphic_context[n]->compliance != SVGCompliance) && (graphic_context[n]->clip_mask != (char *) NULL) && (LocaleCompare(graphic_context[n]->clip_mask, graphic_context[n-1]->clip_mask) != 0)) { const char *clip_path; clip_path=(const char *) GetValueFromSplayTree(macros, graphic_context[n]->clip_mask); if (clip_path != (const char *) NULL) (void) SetImageArtifact(image,graphic_context[n]->clip_mask, clip_path); status&=DrawClipPath(image,graphic_context[n], graphic_context[n]->clip_mask,exception); } status&=DrawPrimitive(image,graphic_context[n],primitive_info, exception); } proceed=SetImageProgress(image,RenderImageTag,q-primitive,(MagickSizeType) primitive_extent); if (proceed == MagickFalse) break; if (status == 0) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end draw-image"); /* Relinquish resources. */ macros=DestroySplayTree(macros); token=DestroyString(token); if (primitive_info != (PrimitiveInfo *) NULL) { for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) if ((primitive_info[i].primitive == TextPrimitive) || (primitive_info[i].primitive == ImagePrimitive)) if (primitive_info[i].text != (char *) NULL) primitive_info[i].text=DestroyString(primitive_info[i].text); primitive_info=(PrimitiveInfo *) RelinquishMagickMemory(primitive_info); } primitive=DestroyString(primitive); if (stops != (StopInfo *) NULL) stops=(StopInfo *) RelinquishMagickMemory(stops); for ( ; n >= 0; n--) graphic_context[n]=DestroyDrawInfo(graphic_context[n]); graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context); if (status == MagickFalse) ThrowBinaryException(DrawError,"NonconformingDrawingPrimitiveDefinition", keyword); return(status != 0 ? MagickTrue : MagickFalse); } MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info, ExceptionInfo *exception) { return(RenderMVGContent(image,draw_info,0,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w P a t t e r n P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawPatternPath() draws a pattern. % % The format of the DrawPatternPath method is: % % MagickBooleanType DrawPatternPath(Image *image,const DrawInfo *draw_info, % const char *name,Image **pattern,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o name: the pattern name. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType DrawPatternPath(Image *image, const DrawInfo *draw_info,const char *name,Image **pattern, ExceptionInfo *exception) { char property[MagickPathExtent]; const char *geometry, *path, *type; DrawInfo *clone_info; ImageInfo *image_info; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); assert(name != (const char *) NULL); (void) FormatLocaleString(property,MagickPathExtent,"%s",name); path=GetImageArtifact(image,property); if (path == (const char *) NULL) return(MagickFalse); (void) FormatLocaleString(property,MagickPathExtent,"%s-geometry",name); geometry=GetImageArtifact(image,property); if (geometry == (const char *) NULL) return(MagickFalse); if ((*pattern) != (Image *) NULL) *pattern=DestroyImage(*pattern); image_info=AcquireImageInfo(); image_info->size=AcquireString(geometry); *pattern=AcquireImage(image_info,exception); image_info=DestroyImageInfo(image_info); (void) QueryColorCompliance("#00000000",AllCompliance, &(*pattern)->background_color,exception); (void) SetImageBackgroundColor(*pattern,exception); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), "begin pattern-path %s %s",name,geometry); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); if (clone_info->fill_pattern != (Image *) NULL) clone_info->fill_pattern=DestroyImage(clone_info->fill_pattern); if (clone_info->stroke_pattern != (Image *) NULL) clone_info->stroke_pattern=DestroyImage(clone_info->stroke_pattern); (void) FormatLocaleString(property,MagickPathExtent,"%s-type",name); type=GetImageArtifact(image,property); if (type != (const char *) NULL) clone_info->gradient.type=(GradientType) ParseCommandOption( MagickGradientOptions,MagickFalse,type); (void) CloneString(&clone_info->primitive,path); status=RenderMVGContent(*pattern,clone_info,0,exception); clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end pattern-path"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w P o l y g o n P r i m i t i v e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawPolygonPrimitive() draws a polygon on the image. % % The format of the DrawPolygonPrimitive method is: % % MagickBooleanType DrawPolygonPrimitive(Image *image, % const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % % o exception: return any errors or warnings in this structure. % */ static PolygonInfo **DestroyPolygonThreadSet(PolygonInfo **polygon_info) { ssize_t i; assert(polygon_info != (PolygonInfo **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (polygon_info[i] != (PolygonInfo *) NULL) polygon_info[i]=DestroyPolygonInfo(polygon_info[i]); polygon_info=(PolygonInfo **) RelinquishMagickMemory(polygon_info); return(polygon_info); } static PolygonInfo **AcquirePolygonThreadSet( const PrimitiveInfo *primitive_info,ExceptionInfo *exception) { PathInfo *magick_restrict path_info; PolygonInfo **polygon_info; ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); polygon_info=(PolygonInfo **) AcquireQuantumMemory(number_threads, sizeof(*polygon_info)); if (polygon_info == (PolygonInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return((PolygonInfo **) NULL); } (void) memset(polygon_info,0,number_threads*sizeof(*polygon_info)); path_info=ConvertPrimitiveToPath(primitive_info,exception); if (path_info == (PathInfo *) NULL) return(DestroyPolygonThreadSet(polygon_info)); polygon_info[0]=ConvertPathToPolygon(path_info,exception); if (polygon_info[0] == (PolygonInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonThreadSet(polygon_info)); } for (i=1; i < (ssize_t) number_threads; i++) { EdgeInfo *edge_info; ssize_t j; polygon_info[i]=(PolygonInfo *) AcquireMagickMemory( sizeof(*polygon_info[i])); if (polygon_info[i] == (PolygonInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonThreadSet(polygon_info)); } polygon_info[i]->number_edges=0; edge_info=polygon_info[0]->edges; polygon_info[i]->edges=(EdgeInfo *) AcquireQuantumMemory( polygon_info[0]->number_edges,sizeof(*edge_info)); if (polygon_info[i]->edges == (EdgeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonThreadSet(polygon_info)); } (void) memcpy(polygon_info[i]->edges,edge_info, polygon_info[0]->number_edges*sizeof(*edge_info)); for (j=0; j < (ssize_t) polygon_info[i]->number_edges; j++) polygon_info[i]->edges[j].points=(PointInfo *) NULL; polygon_info[i]->number_edges=polygon_info[0]->number_edges; for (j=0; j < (ssize_t) polygon_info[i]->number_edges; j++) { edge_info=polygon_info[0]->edges+j; polygon_info[i]->edges[j].points=(PointInfo *) AcquireQuantumMemory( edge_info->number_points,sizeof(*edge_info)); if (polygon_info[i]->edges[j].points == (PointInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonThreadSet(polygon_info)); } (void) memcpy(polygon_info[i]->edges[j].points,edge_info->points, edge_info->number_points*sizeof(*edge_info->points)); } } path_info=(PathInfo *) RelinquishMagickMemory(path_info); return(polygon_info); } static size_t DestroyEdge(PolygonInfo *polygon_info,const ssize_t edge) { assert(edge < (ssize_t) polygon_info->number_edges); polygon_info->edges[edge].points=(PointInfo *) RelinquishMagickMemory( polygon_info->edges[edge].points); polygon_info->number_edges--; if (edge < (ssize_t) polygon_info->number_edges) (void) memmove(polygon_info->edges+edge,polygon_info->edges+edge+1, (size_t) (polygon_info->number_edges-edge)*sizeof(*polygon_info->edges)); return(polygon_info->number_edges); } static double GetFillAlpha(PolygonInfo *polygon_info,const double mid, const MagickBooleanType fill,const FillRule fill_rule,const ssize_t x, const ssize_t y,double *stroke_alpha) { double alpha, beta, distance, subpath_alpha; PointInfo delta; const PointInfo *q; EdgeInfo *p; ssize_t i; ssize_t j, winding_number; /* Compute fill & stroke opacity for this (x,y) point. */ *stroke_alpha=0.0; subpath_alpha=0.0; p=polygon_info->edges; for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++) { if ((double) y <= (p->bounds.y1-mid-0.5)) break; if ((double) y > (p->bounds.y2+mid+0.5)) { (void) DestroyEdge(polygon_info,j); continue; } if (((double) x <= (p->bounds.x1-mid-0.5)) || ((double) x > (p->bounds.x2+mid+0.5))) continue; i=(ssize_t) MagickMax((double) p->highwater,1.0); for ( ; i < (ssize_t) p->number_points; i++) { if ((double) y <= (p->points[i-1].y-mid-0.5)) break; if ((double) y > (p->points[i].y+mid+0.5)) continue; if (p->scanline != (double) y) { p->scanline=(double) y; p->highwater=(size_t) i; } /* Compute distance between a point and an edge. */ q=p->points+i-1; delta.x=(q+1)->x-q->x; delta.y=(q+1)->y-q->y; beta=delta.x*(x-q->x)+delta.y*(y-q->y); if (beta <= 0.0) { delta.x=(double) x-q->x; delta.y=(double) y-q->y; distance=delta.x*delta.x+delta.y*delta.y; } else { alpha=delta.x*delta.x+delta.y*delta.y; if (beta >= alpha) { delta.x=(double) x-(q+1)->x; delta.y=(double) y-(q+1)->y; distance=delta.x*delta.x+delta.y*delta.y; } else { alpha=PerceptibleReciprocal(alpha); beta=delta.x*(y-q->y)-delta.y*(x-q->x)+MagickEpsilon; distance=alpha*beta*beta; } } /* Compute stroke & subpath opacity. */ beta=0.0; if (p->ghostline == MagickFalse) { alpha=mid+0.5; if ((*stroke_alpha < 1.0) && (distance <= ((alpha+0.25)*(alpha+0.25)))) { alpha=mid-0.5; if (distance <= ((alpha+0.25)*(alpha+0.25))) *stroke_alpha=1.0; else { beta=1.0; if (fabs(distance-1.0) >= MagickEpsilon) beta=sqrt((double) distance); alpha=beta-mid-0.5; if (*stroke_alpha < ((alpha-0.25)*(alpha-0.25))) *stroke_alpha=(alpha-0.25)*(alpha-0.25); } } } if ((fill == MagickFalse) || (distance > 1.0) || (subpath_alpha >= 1.0)) continue; if (distance <= 0.0) { subpath_alpha=1.0; continue; } if (distance > 1.0) continue; if (fabs(beta) < MagickEpsilon) { beta=1.0; if (fabs(distance-1.0) >= MagickEpsilon) beta=sqrt(distance); } alpha=beta-1.0; if (subpath_alpha < (alpha*alpha)) subpath_alpha=alpha*alpha; } } /* Compute fill opacity. */ if (fill == MagickFalse) return(0.0); if (subpath_alpha >= 1.0) return(1.0); /* Determine winding number. */ winding_number=0; p=polygon_info->edges; for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++) { if ((double) y <= p->bounds.y1) break; if (((double) y > p->bounds.y2) || ((double) x <= p->bounds.x1)) continue; if ((double) x > p->bounds.x2) { winding_number+=p->direction ? 1 : -1; continue; } i=(ssize_t) MagickMax((double) p->highwater,1.0); for ( ; i < (ssize_t) (p->number_points-1); i++) if ((double) y <= p->points[i].y) break; q=p->points+i-1; if ((((q+1)->x-q->x)*(y-q->y)) <= (((q+1)->y-q->y)*(x-q->x))) winding_number+=p->direction ? 1 : -1; } if (fill_rule != NonZeroRule) { if ((MagickAbsoluteValue(winding_number) & 0x01) != 0) return(1.0); } else if (MagickAbsoluteValue(winding_number) != 0) return(1.0); return(subpath_alpha); } static MagickBooleanType DrawPolygonPrimitive(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, ExceptionInfo *exception) { CacheView *image_view; const char *artifact; MagickBooleanType fill, status; double mid; PolygonInfo **magick_restrict polygon_info; EdgeInfo *p; ssize_t i; SegmentInfo bounds; ssize_t start_y, stop_y, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); assert(primitive_info != (PrimitiveInfo *) NULL); if (primitive_info->coordinates <= 1) return(MagickTrue); /* Compute bounding box. */ polygon_info=AcquirePolygonThreadSet(primitive_info,exception); if (polygon_info == (PolygonInfo **) NULL) return(MagickFalse); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-polygon"); fill=(primitive_info->method == FillToBorderMethod) || (primitive_info->method == FloodfillMethod) ? MagickTrue : MagickFalse; mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0; bounds=polygon_info[0]->edges[0].bounds; artifact=GetImageArtifact(image,"draw:render-bounding-rectangles"); if (IsStringTrue(artifact) != MagickFalse) (void) DrawBoundingRectangles(image,draw_info,polygon_info[0],exception); for (i=1; i < (ssize_t) polygon_info[0]->number_edges; i++) { p=polygon_info[0]->edges+i; if (p->bounds.x1 < bounds.x1) bounds.x1=p->bounds.x1; if (p->bounds.y1 < bounds.y1) bounds.y1=p->bounds.y1; if (p->bounds.x2 > bounds.x2) bounds.x2=p->bounds.x2; if (p->bounds.y2 > bounds.y2) bounds.y2=p->bounds.y2; } bounds.x1-=(mid+1.0); bounds.y1-=(mid+1.0); bounds.x2+=(mid+1.0); bounds.y2+=(mid+1.0); if ((bounds.x1 >= (double) image->columns) || (bounds.y1 >= (double) image->rows) || (bounds.x2 <= 0.0) || (bounds.y2 <= 0.0)) { polygon_info=DestroyPolygonThreadSet(polygon_info); return(MagickTrue); /* virtual polygon */ } bounds.x1=bounds.x1 < 0.0 ? 0.0 : bounds.x1 >= (double) image->columns-1.0 ? (double) image->columns-1.0 : bounds.x1; bounds.y1=bounds.y1 < 0.0 ? 0.0 : bounds.y1 >= (double) image->rows-1.0 ? (double) image->rows-1.0 : bounds.y1; bounds.x2=bounds.x2 < 0.0 ? 0.0 : bounds.x2 >= (double) image->columns-1.0 ? (double) image->columns-1.0 : bounds.x2; bounds.y2=bounds.y2 < 0.0 ? 0.0 : bounds.y2 >= (double) image->rows-1.0 ? (double) image->rows-1.0 : bounds.y2; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); if ((primitive_info->coordinates == 1) || (polygon_info[0]->number_edges == 0)) { /* Draw point. */ start_y=CastDoubleToLong(ceil(bounds.y1-0.5)); stop_y=CastDoubleToLong(floor(bounds.y2+0.5)); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,stop_y-start_y+1,1) #endif for (y=start_y; y <= stop_y; y++) { MagickBooleanType sync; PixelInfo pixel; ssize_t x; Quantum *magick_restrict q; ssize_t start_x, stop_x; if (status == MagickFalse) continue; start_x=CastDoubleToLong(ceil(bounds.x1-0.5)); stop_x=CastDoubleToLong(floor(bounds.x2+0.5)); x=start_x; q=GetCacheViewAuthenticPixels(image_view,x,y,(size_t) (stop_x-x+1),1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } GetPixelInfo(image,&pixel); for ( ; x <= stop_x; x++) { if ((x == CastDoubleToLong(ceil(primitive_info->point.x-0.5))) && (y == CastDoubleToLong(ceil(primitive_info->point.y-0.5)))) { GetFillColor(draw_info,x-start_x,y-start_y,&pixel,exception); SetPixelViaPixelInfo(image,&pixel,q); } q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); polygon_info=DestroyPolygonThreadSet(polygon_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " end draw-polygon"); return(status); } /* Draw polygon or line. */ start_y=CastDoubleToLong(ceil(bounds.y1-0.5)); stop_y=CastDoubleToLong(floor(bounds.y2+0.5)); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,stop_y-start_y+1,1) #endif for (y=start_y; y <= stop_y; y++) { const int id = GetOpenMPThreadId(); Quantum *magick_restrict q; ssize_t x; ssize_t start_x, stop_x; if (status == MagickFalse) continue; start_x=CastDoubleToLong(ceil(bounds.x1-0.5)); stop_x=CastDoubleToLong(floor(bounds.x2+0.5)); q=GetCacheViewAuthenticPixels(image_view,start_x,y,(size_t) (stop_x-start_x+ 1),1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=start_x; x <= stop_x; x++) { double fill_alpha, stroke_alpha; PixelInfo fill_color, stroke_color; /* Fill and/or stroke. */ fill_alpha=GetFillAlpha(polygon_info[id],mid,fill,draw_info->fill_rule, x,y,&stroke_alpha); if (draw_info->stroke_antialias == MagickFalse) { fill_alpha=fill_alpha > 0.5 ? 1.0 : 0.0; stroke_alpha=stroke_alpha > 0.5 ? 1.0 : 0.0; } GetFillColor(draw_info,x-start_x,y-start_y,&fill_color,exception); CompositePixelOver(image,&fill_color,fill_alpha*fill_color.alpha,q, (double) GetPixelAlpha(image,q),q); GetStrokeColor(draw_info,x-start_x,y-start_y,&stroke_color,exception); CompositePixelOver(image,&stroke_color,stroke_alpha*stroke_color.alpha,q, (double) GetPixelAlpha(image,q),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); polygon_info=DestroyPolygonThreadSet(polygon_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-polygon"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w P r i m i t i v e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawPrimitive() draws a primitive (line, rectangle, ellipse) on the image. % % The format of the DrawPrimitive method is: % % MagickBooleanType DrawPrimitive(Image *image,const DrawInfo *draw_info, % PrimitiveInfo *primitive_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % % o exception: return any errors or warnings in this structure. % */ static void LogPrimitiveInfo(const PrimitiveInfo *primitive_info) { const char *methods[] = { "point", "replace", "floodfill", "filltoborder", "reset", "?" }; PointInfo p, point, q; ssize_t i, x; ssize_t coordinates, y; x=CastDoubleToLong(ceil(primitive_info->point.x-0.5)); y=CastDoubleToLong(ceil(primitive_info->point.y-0.5)); switch (primitive_info->primitive) { case AlphaPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "AlphaPrimitive %.20g,%.20g %s",(double) x,(double) y, methods[primitive_info->method]); return; } case ColorPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "ColorPrimitive %.20g,%.20g %s",(double) x,(double) y, methods[primitive_info->method]); return; } case ImagePrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "ImagePrimitive %.20g,%.20g",(double) x,(double) y); return; } case PointPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "PointPrimitive %.20g,%.20g %s",(double) x,(double) y, methods[primitive_info->method]); return; } case TextPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "TextPrimitive %.20g,%.20g",(double) x,(double) y); return; } default: break; } coordinates=0; p=primitive_info[0].point; q.x=(-1.0); q.y=(-1.0); for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) { point=primitive_info[i].point; if (coordinates <= 0) { coordinates=(ssize_t) primitive_info[i].coordinates; (void) LogMagickEvent(DrawEvent,GetMagickModule(), " begin open (%.20g)",(double) coordinates); p=point; } point=primitive_info[i].point; if ((fabs(q.x-point.x) >= MagickEpsilon) || (fabs(q.y-point.y) >= MagickEpsilon)) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " %.20g: %.18g,%.18g",(double) coordinates,point.x,point.y); else (void) LogMagickEvent(DrawEvent,GetMagickModule(), " %.20g: %g %g (duplicate)",(double) coordinates,point.x,point.y); q=point; coordinates--; if (coordinates > 0) continue; if ((fabs(p.x-point.x) >= MagickEpsilon) || (fabs(p.y-point.y) >= MagickEpsilon)) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end last (%.20g)", (double) coordinates); else (void) LogMagickEvent(DrawEvent,GetMagickModule()," end open (%.20g)", (double) coordinates); } } MagickExport MagickBooleanType DrawPrimitive(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, ExceptionInfo *exception) { CacheView *image_view; MagickStatusType status; ssize_t i, x; ssize_t y; if (image->debug != MagickFalse) { (void) LogMagickEvent(DrawEvent,GetMagickModule(), " begin draw-primitive"); (void) LogMagickEvent(DrawEvent,GetMagickModule(), " affine: %g,%g,%g,%g,%g,%g",draw_info->affine.sx, draw_info->affine.rx,draw_info->affine.ry,draw_info->affine.sy, draw_info->affine.tx,draw_info->affine.ty); } status=MagickTrue; if ((IsGrayColorspace(image->colorspace) != MagickFalse) && ((IsPixelInfoGray(&draw_info->fill) == MagickFalse) || (IsPixelInfoGray(&draw_info->stroke) == MagickFalse))) status&=SetImageColorspace(image,sRGBColorspace,exception); if (draw_info->compliance == SVGCompliance) { status&=SetImageMask(image,WritePixelMask,draw_info->clipping_mask, exception); status&=SetImageMask(image,CompositePixelMask,draw_info->composite_mask, exception); } x=CastDoubleToLong(ceil(primitive_info->point.x-0.5)); y=CastDoubleToLong(ceil(primitive_info->point.y-0.5)); image_view=AcquireAuthenticCacheView(image,exception); switch (primitive_info->primitive) { case AlphaPrimitive: { if (image->alpha_trait == UndefinedPixelTrait) status&=SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); switch (primitive_info->method) { case PointMethod: default: { PixelInfo pixel; Quantum *q; q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); if (q == (Quantum *) NULL) break; GetFillColor(draw_info,x,y,&pixel,exception); SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); status&=SyncCacheViewAuthenticPixels(image_view,exception); break; } case ReplaceMethod: { PixelInfo pixel, target; status&=GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target, exception); GetPixelInfo(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetPixelInfoPixel(image,q,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse) { q+=GetPixelChannels(image); continue; } GetFillColor(draw_info,x,y,&pixel,exception); SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); q+=GetPixelChannels(image); } status&=SyncCacheViewAuthenticPixels(image_view,exception); if (status == MagickFalse) break; } break; } case FloodfillMethod: case FillToBorderMethod: { ChannelType channel_mask; PixelInfo target; status&=GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y, &target,exception); if (primitive_info->method == FillToBorderMethod) { target.red=(double) draw_info->border_color.red; target.green=(double) draw_info->border_color.green; target.blue=(double) draw_info->border_color.blue; } channel_mask=SetImageChannelMask(image,AlphaChannel); status&=FloodfillPaintImage(image,draw_info,&target,x,y, primitive_info->method == FloodfillMethod ? MagickFalse : MagickTrue,exception); (void) SetImageChannelMask(image,channel_mask); break; } case ResetMethod: { PixelInfo pixel; for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetFillColor(draw_info,x,y,&pixel,exception); SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); q+=GetPixelChannels(image); } status&=SyncCacheViewAuthenticPixels(image_view,exception); if (status == MagickFalse) break; } break; } } break; } case ColorPrimitive: { switch (primitive_info->method) { case PointMethod: default: { PixelInfo pixel; Quantum *q; q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); if (q == (Quantum *) NULL) break; GetPixelInfo(image,&pixel); GetFillColor(draw_info,x,y,&pixel,exception); SetPixelViaPixelInfo(image,&pixel,q); status&=SyncCacheViewAuthenticPixels(image_view,exception); break; } case ReplaceMethod: { PixelInfo pixel, target; status&=GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target, exception); for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetPixelInfoPixel(image,q,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse) { q+=GetPixelChannels(image); continue; } GetFillColor(draw_info,x,y,&pixel,exception); SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } status&=SyncCacheViewAuthenticPixels(image_view,exception); if (status == MagickFalse) break; } break; } case FloodfillMethod: case FillToBorderMethod: { PixelInfo target; status&=GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y, &target,exception); if (primitive_info->method == FillToBorderMethod) { target.red=(double) draw_info->border_color.red; target.green=(double) draw_info->border_color.green; target.blue=(double) draw_info->border_color.blue; } status&=FloodfillPaintImage(image,draw_info,&target,x,y, primitive_info->method == FloodfillMethod ? MagickFalse : MagickTrue,exception); break; } case ResetMethod: { PixelInfo pixel; GetPixelInfo(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetFillColor(draw_info,x,y,&pixel,exception); SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } status&=SyncCacheViewAuthenticPixels(image_view,exception); if (status == MagickFalse) break; } break; } } break; } case ImagePrimitive: { AffineMatrix affine; char composite_geometry[MagickPathExtent]; Image *composite_image, *composite_images; ImageInfo *clone_info; RectangleInfo geometry; ssize_t x1, y1; if (primitive_info->text == (char *) NULL) break; clone_info=AcquireImageInfo(); composite_images=(Image *) NULL; if (LocaleNCompare(primitive_info->text,"data:",5) == 0) composite_images=ReadInlineImage(clone_info,primitive_info->text, exception); else if (*primitive_info->text != '\0') { (void) CopyMagickString(clone_info->filename,primitive_info->text, MagickPathExtent); status&=SetImageInfo(clone_info,0,exception); (void) CopyMagickString(clone_info->filename,primitive_info->text, MagickPathExtent); if (clone_info->size != (char *) NULL) clone_info->size=DestroyString(clone_info->size); if (clone_info->extract != (char *) NULL) clone_info->extract=DestroyString(clone_info->extract); if ((LocaleCompare(clone_info->magick,"file") == 0) || (LocaleCompare(clone_info->magick,"https") == 0) || (LocaleCompare(clone_info->magick,"http") == 0) || (LocaleCompare(clone_info->magick,"mpri") == 0) || (IsPathAccessible(clone_info->filename) != MagickFalse)) composite_images=ReadImage(clone_info,exception); } clone_info=DestroyImageInfo(clone_info); if (composite_images == (Image *) NULL) { status=MagickFalse; break; } composite_image=RemoveFirstImageFromList(&composite_images); composite_images=DestroyImageList(composite_images); (void) SetImageProgressMonitor(composite_image,(MagickProgressMonitor) NULL,(void *) NULL); x1=CastDoubleToLong(ceil(primitive_info[1].point.x-0.5)); y1=CastDoubleToLong(ceil(primitive_info[1].point.y-0.5)); if (((x1 != 0L) && (x1 != (ssize_t) composite_image->columns)) || ((y1 != 0L) && (y1 != (ssize_t) composite_image->rows))) { /* Resize image. */ (void) FormatLocaleString(composite_geometry,MagickPathExtent, "%gx%g!",primitive_info[1].point.x,primitive_info[1].point.y); composite_image->filter=image->filter; status&=TransformImage(&composite_image,(char *) NULL, composite_geometry,exception); } if (composite_image->alpha_trait == UndefinedPixelTrait) status&=SetImageAlphaChannel(composite_image,OpaqueAlphaChannel, exception); if (draw_info->alpha != OpaqueAlpha) status&=SetImageAlpha(composite_image,draw_info->alpha,exception); SetGeometry(image,&geometry); image->gravity=draw_info->gravity; geometry.x=x; geometry.y=y; (void) FormatLocaleString(composite_geometry,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns,(double) composite_image->rows,(double) geometry.x,(double) geometry.y); (void) ParseGravityGeometry(image,composite_geometry,&geometry,exception); affine=draw_info->affine; affine.tx=(double) geometry.x; affine.ty=(double) geometry.y; composite_image->interpolate=image->interpolate; if ((draw_info->compose == OverCompositeOp) || (draw_info->compose == SrcOverCompositeOp)) status&=DrawAffineImage(image,composite_image,&affine,exception); else status&=CompositeImage(image,composite_image,draw_info->compose, MagickTrue,geometry.x,geometry.y,exception); composite_image=DestroyImage(composite_image); break; } case PointPrimitive: { PixelInfo fill_color; Quantum *q; if ((y < 0) || (y >= (ssize_t) image->rows)) break; if ((x < 0) || (x >= (ssize_t) image->columns)) break; q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); if (q == (Quantum *) NULL) break; GetFillColor(draw_info,x,y,&fill_color,exception); CompositePixelOver(image,&fill_color,(double) fill_color.alpha,q,(double) GetPixelAlpha(image,q),q); status&=SyncCacheViewAuthenticPixels(image_view,exception); break; } case TextPrimitive: { char geometry[MagickPathExtent]; DrawInfo *clone_info; if (primitive_info->text == (char *) NULL) break; clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->text,primitive_info->text); (void) FormatLocaleString(geometry,MagickPathExtent,"%+f%+f", primitive_info->point.x,primitive_info->point.y); (void) CloneString(&clone_info->geometry,geometry); status&=AnnotateImage(image,clone_info,exception); clone_info=DestroyDrawInfo(clone_info); break; } default: { double mid, scale; DrawInfo *clone_info; if (IsEventLogging() != MagickFalse) LogPrimitiveInfo(primitive_info); scale=ExpandAffine(&draw_info->affine); if ((draw_info->dash_pattern != (double *) NULL) && (fabs(draw_info->dash_pattern[0]) >= MagickEpsilon) && (fabs(scale*draw_info->stroke_width) >= MagickEpsilon) && (draw_info->stroke.alpha != (Quantum) TransparentAlpha)) { /* Draw dash polygon. */ clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->stroke_width=0.0; clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; status&=DrawPolygonPrimitive(image,clone_info,primitive_info, exception); clone_info=DestroyDrawInfo(clone_info); if (status != MagickFalse) status&=DrawDashPolygon(draw_info,primitive_info,image,exception); break; } mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0; if ((mid > 1.0) && ((draw_info->stroke.alpha != (Quantum) TransparentAlpha) || (draw_info->stroke_pattern != (Image *) NULL))) { double x, y; MagickBooleanType closed_path; /* Draw strokes while respecting line cap/join attributes. */ closed_path=primitive_info[0].closed_subpath; i=(ssize_t) primitive_info[0].coordinates; x=fabs(primitive_info[i-1].point.x-primitive_info[0].point.x); y=fabs(primitive_info[i-1].point.y-primitive_info[0].point.y); if ((x < MagickEpsilon) && (y < MagickEpsilon)) closed_path=MagickTrue; if ((((draw_info->linecap == RoundCap) || (closed_path != MagickFalse)) && (draw_info->linejoin == RoundJoin)) || (primitive_info[i].primitive != UndefinedPrimitive)) { status&=DrawPolygonPrimitive(image,draw_info,primitive_info, exception); break; } clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->stroke_width=0.0; clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; status&=DrawPolygonPrimitive(image,clone_info,primitive_info, exception); clone_info=DestroyDrawInfo(clone_info); if (status != MagickFalse) status&=DrawStrokePolygon(image,draw_info,primitive_info,exception); break; } status&=DrawPolygonPrimitive(image,draw_info,primitive_info,exception); break; } } image_view=DestroyCacheView(image_view); if (draw_info->compliance == SVGCompliance) { status&=SetImageMask(image,WritePixelMask,(Image *) NULL,exception); status&=SetImageMask(image,CompositePixelMask,(Image *) NULL,exception); } if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-primitive"); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w S t r o k e P o l y g o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawStrokePolygon() draws a stroked polygon (line, rectangle, ellipse) on % the image while respecting the line cap and join attributes. % % The format of the DrawStrokePolygon method is: % % MagickBooleanType DrawStrokePolygon(Image *image, % const DrawInfo *draw_info,const PrimitiveInfo *primitive_info) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % % */ static MagickBooleanType DrawRoundLinecap(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, ExceptionInfo *exception) { PrimitiveInfo linecap[5]; ssize_t i; for (i=0; i < 4; i++) linecap[i]=(*primitive_info); linecap[0].coordinates=4; linecap[1].point.x+=2.0*MagickEpsilon; linecap[2].point.x+=2.0*MagickEpsilon; linecap[2].point.y+=2.0*MagickEpsilon; linecap[3].point.y+=2.0*MagickEpsilon; linecap[4].primitive=UndefinedPrimitive; return(DrawPolygonPrimitive(image,draw_info,linecap,exception)); } static MagickBooleanType DrawStrokePolygon(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, ExceptionInfo *exception) { DrawInfo *clone_info; MagickBooleanType closed_path; MagickStatusType status; PrimitiveInfo *stroke_polygon; const PrimitiveInfo *p, *q; /* Draw stroked polygon. */ if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " begin draw-stroke-polygon"); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->fill=draw_info->stroke; if (clone_info->fill_pattern != (Image *) NULL) clone_info->fill_pattern=DestroyImage(clone_info->fill_pattern); if (clone_info->stroke_pattern != (Image *) NULL) clone_info->fill_pattern=CloneImage(clone_info->stroke_pattern,0,0, MagickTrue,exception); clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; clone_info->stroke_width=0.0; clone_info->fill_rule=NonZeroRule; status=MagickTrue; for (p=primitive_info; p->primitive != UndefinedPrimitive; p+=p->coordinates) { if (p->coordinates == 1) continue; stroke_polygon=TraceStrokePolygon(draw_info,p,exception); if (stroke_polygon == (PrimitiveInfo *) NULL) { status=0; break; } status&=DrawPolygonPrimitive(image,clone_info,stroke_polygon,exception); stroke_polygon=(PrimitiveInfo *) RelinquishMagickMemory(stroke_polygon); if (status == 0) break; q=p+p->coordinates-1; closed_path=p->closed_subpath; if ((draw_info->linecap == RoundCap) && (closed_path == MagickFalse)) { status&=DrawRoundLinecap(image,draw_info,p,exception); status&=DrawRoundLinecap(image,draw_info,q,exception); } } clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " end draw-stroke-polygon"); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A f f i n e M a t r i x % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAffineMatrix() returns an AffineMatrix initialized to the identity % matrix. % % The format of the GetAffineMatrix method is: % % void GetAffineMatrix(AffineMatrix *affine_matrix) % % A description of each parameter follows: % % o affine_matrix: the affine matrix. % */ MagickExport void GetAffineMatrix(AffineMatrix *affine_matrix) { (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(affine_matrix != (AffineMatrix *) NULL); (void) memset(affine_matrix,0,sizeof(*affine_matrix)); affine_matrix->sx=1.0; affine_matrix->sy=1.0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetDrawInfo() initializes draw_info to default values from image_info. % % The format of the GetDrawInfo method is: % % void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info) % % A description of each parameter follows: % % o image_info: the image info.. % % o draw_info: the draw info. % */ MagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info) { char *next_token; const char *option; ExceptionInfo *exception; ImageInfo *clone_info; /* Initialize draw attributes. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(draw_info != (DrawInfo *) NULL); (void) memset(draw_info,0,sizeof(*draw_info)); clone_info=CloneImageInfo(image_info); GetAffineMatrix(&draw_info->affine); exception=AcquireExceptionInfo(); (void) QueryColorCompliance("#000F",AllCompliance,&draw_info->fill, exception); (void) QueryColorCompliance("#FFF0",AllCompliance,&draw_info->stroke, exception); draw_info->stroke_antialias=clone_info->antialias; draw_info->stroke_width=1.0; draw_info->fill_rule=EvenOddRule; draw_info->alpha=OpaqueAlpha; draw_info->fill_alpha=OpaqueAlpha; draw_info->stroke_alpha=OpaqueAlpha; draw_info->linecap=ButtCap; draw_info->linejoin=MiterJoin; draw_info->miterlimit=10; draw_info->decorate=NoDecoration; draw_info->pointsize=12.0; draw_info->undercolor.alpha=(MagickRealType) TransparentAlpha; draw_info->compose=OverCompositeOp; draw_info->render=MagickTrue; draw_info->clip_path=MagickFalse; draw_info->debug=IsEventLogging(); if (clone_info->font != (char *) NULL) draw_info->font=AcquireString(clone_info->font); if (clone_info->density != (char *) NULL) draw_info->density=AcquireString(clone_info->density); draw_info->text_antialias=clone_info->antialias; if (fabs(clone_info->pointsize) >= MagickEpsilon) draw_info->pointsize=clone_info->pointsize; draw_info->border_color=clone_info->border_color; if (clone_info->server_name != (char *) NULL) draw_info->server_name=AcquireString(clone_info->server_name); option=GetImageOption(clone_info,"direction"); if (option != (const char *) NULL) draw_info->direction=(DirectionType) ParseCommandOption( MagickDirectionOptions,MagickFalse,option); else draw_info->direction=UndefinedDirection; option=GetImageOption(clone_info,"encoding"); if (option != (const char *) NULL) (void) CloneString(&draw_info->encoding,option); option=GetImageOption(clone_info,"family"); if (option != (const char *) NULL) (void) CloneString(&draw_info->family,option); option=GetImageOption(clone_info,"fill"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->fill, exception); option=GetImageOption(clone_info,"gravity"); if (option != (const char *) NULL) draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,option); option=GetImageOption(clone_info,"interline-spacing"); if (option != (const char *) NULL) draw_info->interline_spacing=GetDrawValue(option,&next_token); option=GetImageOption(clone_info,"interword-spacing"); if (option != (const char *) NULL) draw_info->interword_spacing=GetDrawValue(option,&next_token); option=GetImageOption(clone_info,"kerning"); if (option != (const char *) NULL) draw_info->kerning=GetDrawValue(option,&next_token); option=GetImageOption(clone_info,"stroke"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->stroke, exception); option=GetImageOption(clone_info,"strokewidth"); if (option != (const char *) NULL) draw_info->stroke_width=GetDrawValue(option,&next_token); option=GetImageOption(clone_info,"style"); if (option != (const char *) NULL) draw_info->style=(StyleType) ParseCommandOption(MagickStyleOptions, MagickFalse,option); option=GetImageOption(clone_info,"undercolor"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->undercolor, exception); option=GetImageOption(clone_info,"weight"); if (option != (const char *) NULL) { ssize_t weight; weight=ParseCommandOption(MagickWeightOptions,MagickFalse,option); if (weight == -1) weight=(ssize_t) StringToUnsignedLong(option); draw_info->weight=(size_t) weight; } exception=DestroyExceptionInfo(exception); draw_info->signature=MagickCoreSignature; clone_info=DestroyImageInfo(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P e r m u t a t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Permutate() returns the permuation of the (n,k). % % The format of the Permutate method is: % % void Permutate(ssize_t n,ssize_t k) % % A description of each parameter follows: % % o n: % % o k: % % */ static inline double Permutate(const ssize_t n,const ssize_t k) { double r; ssize_t i; r=1.0; for (i=k+1; i <= n; i++) r*=i; for (i=1; i <= (n-k); i++) r/=i; return(r); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + T r a c e P r i m i t i v e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TracePrimitive is a collection of methods for generating graphic % primitives such as arcs, ellipses, paths, etc. % */ static MagickBooleanType TraceArc(MVGInfo *mvg_info,const PointInfo start, const PointInfo end,const PointInfo degrees) { PointInfo center, radius; center.x=0.5*(end.x+start.x); center.y=0.5*(end.y+start.y); radius.x=fabs(center.x-start.x); radius.y=fabs(center.y-start.y); return(TraceEllipse(mvg_info,center,radius,degrees)); } static MagickBooleanType TraceArcPath(MVGInfo *mvg_info,const PointInfo start, const PointInfo end,const PointInfo arc,const double angle, const MagickBooleanType large_arc,const MagickBooleanType sweep) { double alpha, beta, delta, factor, gamma, theta; MagickStatusType status; PointInfo center, points[3], radii; double cosine, sine; PrimitiveInfo *primitive_info; PrimitiveInfo *p; ssize_t i; size_t arc_segments; ssize_t offset; offset=mvg_info->offset; primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; primitive_info->coordinates=0; if ((fabs(start.x-end.x) < MagickEpsilon) && (fabs(start.y-end.y) < MagickEpsilon)) return(TracePoint(primitive_info,end)); radii.x=fabs(arc.x); radii.y=fabs(arc.y); if ((radii.x < MagickEpsilon) || (radii.y < MagickEpsilon)) return(TraceLine(primitive_info,start,end)); cosine=cos(DegreesToRadians(fmod((double) angle,360.0))); sine=sin(DegreesToRadians(fmod((double) angle,360.0))); center.x=(double) (cosine*(end.x-start.x)/2+sine*(end.y-start.y)/2); center.y=(double) (cosine*(end.y-start.y)/2-sine*(end.x-start.x)/2); delta=(center.x*center.x)/(radii.x*radii.x)+(center.y*center.y)/ (radii.y*radii.y); if (delta < MagickEpsilon) return(TraceLine(primitive_info,start,end)); if (delta > 1.0) { radii.x*=sqrt((double) delta); radii.y*=sqrt((double) delta); } points[0].x=(double) (cosine*start.x/radii.x+sine*start.y/radii.x); points[0].y=(double) (cosine*start.y/radii.y-sine*start.x/radii.y); points[1].x=(double) (cosine*end.x/radii.x+sine*end.y/radii.x); points[1].y=(double) (cosine*end.y/radii.y-sine*end.x/radii.y); alpha=points[1].x-points[0].x; beta=points[1].y-points[0].y; if (fabs(alpha*alpha+beta*beta) < MagickEpsilon) return(TraceLine(primitive_info,start,end)); factor=PerceptibleReciprocal(alpha*alpha+beta*beta)-0.25; if (factor <= 0.0) factor=0.0; else { factor=sqrt((double) factor); if (sweep == large_arc) factor=(-factor); } center.x=(double) ((points[0].x+points[1].x)/2-factor*beta); center.y=(double) ((points[0].y+points[1].y)/2+factor*alpha); alpha=atan2(points[0].y-center.y,points[0].x-center.x); theta=atan2(points[1].y-center.y,points[1].x-center.x)-alpha; if ((theta < 0.0) && (sweep != MagickFalse)) theta+=2.0*MagickPI; else if ((theta > 0.0) && (sweep == MagickFalse)) theta-=2.0*MagickPI; arc_segments=(size_t) CastDoubleToLong(ceil(fabs((double) (theta/(0.5* MagickPI+MagickEpsilon))))); status=MagickTrue; p=primitive_info; for (i=0; i < (ssize_t) arc_segments; i++) { beta=0.5*((alpha+(i+1)*theta/arc_segments)-(alpha+i*theta/arc_segments)); gamma=(8.0/3.0)*sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))* sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))/ sin(fmod((double) beta,DegreesToRadians(360.0))); points[0].x=(double) (center.x+cos(fmod((double) (alpha+(double) i*theta/ arc_segments),DegreesToRadians(360.0)))-gamma*sin(fmod((double) (alpha+ (double) i*theta/arc_segments),DegreesToRadians(360.0)))); points[0].y=(double) (center.y+sin(fmod((double) (alpha+(double) i*theta/ arc_segments),DegreesToRadians(360.0)))+gamma*cos(fmod((double) (alpha+ (double) i*theta/arc_segments),DegreesToRadians(360.0)))); points[2].x=(double) (center.x+cos(fmod((double) (alpha+(double) (i+1)* theta/arc_segments),DegreesToRadians(360.0)))); points[2].y=(double) (center.y+sin(fmod((double) (alpha+(double) (i+1)* theta/arc_segments),DegreesToRadians(360.0)))); points[1].x=(double) (points[2].x+gamma*sin(fmod((double) (alpha+(double) (i+1)*theta/arc_segments),DegreesToRadians(360.0)))); points[1].y=(double) (points[2].y-gamma*cos(fmod((double) (alpha+(double) (i+1)*theta/arc_segments),DegreesToRadians(360.0)))); p->point.x=(p == primitive_info) ? start.x : (p-1)->point.x; p->point.y=(p == primitive_info) ? start.y : (p-1)->point.y; (p+1)->point.x=(double) (cosine*radii.x*points[0].x-sine*radii.y* points[0].y); (p+1)->point.y=(double) (sine*radii.x*points[0].x+cosine*radii.y* points[0].y); (p+2)->point.x=(double) (cosine*radii.x*points[1].x-sine*radii.y* points[1].y); (p+2)->point.y=(double) (sine*radii.x*points[1].x+cosine*radii.y* points[1].y); (p+3)->point.x=(double) (cosine*radii.x*points[2].x-sine*radii.y* points[2].y); (p+3)->point.y=(double) (sine*radii.x*points[2].x+cosine*radii.y* points[2].y); if (i == (ssize_t) (arc_segments-1)) (p+3)->point=end; status&=TraceBezier(mvg_info,4); if (status == 0) break; p=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=p->coordinates; p+=p->coordinates; } if (status == 0) return(MagickFalse); mvg_info->offset=offset; primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } return(MagickTrue); } static MagickBooleanType TraceBezier(MVGInfo *mvg_info, const size_t number_coordinates) { double alpha, *coefficients, weight; PointInfo end, point, *points; PrimitiveInfo *primitive_info; PrimitiveInfo *p; ssize_t i, j; size_t control_points, quantum; /* Allocate coefficients. */ primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; quantum=number_coordinates; for (i=0; i < (ssize_t) number_coordinates; i++) { for (j=i+1; j < (ssize_t) number_coordinates; j++) { alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x); if (alpha > (double) MAGICK_SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y); if (alpha > (double) MAGICK_SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; } } primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; quantum=MagickMin(quantum/number_coordinates,BezierQuantum); coefficients=(double *) AcquireQuantumMemory(number_coordinates, sizeof(*coefficients)); points=(PointInfo *) AcquireQuantumMemory(quantum,number_coordinates* sizeof(*points)); if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL)) { if (points != (PointInfo *) NULL) points=(PointInfo *) RelinquishMagickMemory(points); if (coefficients != (double *) NULL) coefficients=(double *) RelinquishMagickMemory(coefficients); (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } control_points=quantum*number_coordinates; if (CheckPrimitiveExtent(mvg_info,(double) control_points+1) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; /* Compute bezier points. */ end=primitive_info[number_coordinates-1].point; for (i=0; i < (ssize_t) number_coordinates; i++) coefficients[i]=Permutate((ssize_t) number_coordinates-1,i); weight=0.0; for (i=0; i < (ssize_t) control_points; i++) { p=primitive_info; point.x=0.0; point.y=0.0; alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0); for (j=0; j < (ssize_t) number_coordinates; j++) { point.x+=alpha*coefficients[j]*p->point.x; point.y+=alpha*coefficients[j]*p->point.y; alpha*=weight/(1.0-weight); p++; } points[i]=point; weight+=1.0/control_points; } /* Bezier curves are just short segmented polys. */ p=primitive_info; for (i=0; i < (ssize_t) control_points; i++) { if (TracePoint(p,points[i]) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; } if (TracePoint(p,end) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickTrue); } static MagickBooleanType TraceCircle(MVGInfo *mvg_info,const PointInfo start, const PointInfo end) { double alpha, beta, radius; PointInfo offset, degrees; alpha=end.x-start.x; beta=end.y-start.y; radius=hypot((double) alpha,(double) beta); offset.x=(double) radius; offset.y=(double) radius; degrees.x=0.0; degrees.y=360.0; return(TraceEllipse(mvg_info,start,offset,degrees)); } static MagickBooleanType TraceEllipse(MVGInfo *mvg_info,const PointInfo center, const PointInfo radii,const PointInfo arc) { double coordinates, delta, step, x, y; PointInfo angle, point; PrimitiveInfo *primitive_info; PrimitiveInfo *p; ssize_t i; /* Ellipses are just short segmented polys. */ primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; primitive_info->coordinates=0; if ((fabs(radii.x) < MagickEpsilon) || (fabs(radii.y) < MagickEpsilon)) return(MagickTrue); delta=2.0*PerceptibleReciprocal(MagickMax(radii.x,radii.y)); step=MagickPI/8.0; if ((delta >= 0.0) && (delta < (MagickPI/8.0))) step=MagickPI/4.0/(MagickPI*PerceptibleReciprocal(delta)/2.0); angle.x=DegreesToRadians(arc.x); y=arc.y; while (y < arc.x) y+=360.0; angle.y=DegreesToRadians(y); coordinates=ceil((angle.y-angle.x)/step+1.0); if (CheckPrimitiveExtent(mvg_info,coordinates) == MagickFalse) return(MagickFalse); primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; for (p=primitive_info; angle.x < angle.y; angle.x+=step) { point.x=cos(fmod(angle.x,DegreesToRadians(360.0)))*radii.x+center.x; point.y=sin(fmod(angle.x,DegreesToRadians(360.0)))*radii.y+center.y; if (TracePoint(p,point) == MagickFalse) return(MagickFalse); p+=p->coordinates; } point.x=cos(fmod(angle.y,DegreesToRadians(360.0)))*radii.x+center.x; point.y=sin(fmod(angle.y,DegreesToRadians(360.0)))*radii.y+center.y; if (TracePoint(p,point) == MagickFalse) return(MagickFalse); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; x=fabs(primitive_info[0].point.x- primitive_info[primitive_info->coordinates-1].point.x); y=fabs(primitive_info[0].point.y- primitive_info[primitive_info->coordinates-1].point.y); if ((x < MagickEpsilon) && (y < MagickEpsilon)) primitive_info->closed_subpath=MagickTrue; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } return(MagickTrue); } static MagickBooleanType TraceLine(PrimitiveInfo *primitive_info, const PointInfo start,const PointInfo end) { if (TracePoint(primitive_info,start) == MagickFalse) return(MagickFalse); if ((fabs(start.x-end.x) < MagickEpsilon) && (fabs(start.y-end.y) < MagickEpsilon)) { primitive_info->primitive=PointPrimitive; primitive_info->coordinates=1; return(MagickTrue); } if (TracePoint(primitive_info+1,end) == MagickFalse) return(MagickFalse); (primitive_info+1)->primitive=primitive_info->primitive; primitive_info->coordinates=2; primitive_info->closed_subpath=MagickFalse; return(MagickTrue); } static ssize_t TracePath(MVGInfo *mvg_info,const char *path, ExceptionInfo *exception) { char *next_token, token[MagickPathExtent]; const char *p; double x, y; int attribute, last_attribute; MagickBooleanType status; PointInfo end = {0.0, 0.0}, points[4] = { {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0} }, point = {0.0, 0.0}, start = {0.0, 0.0}; PrimitiveInfo *primitive_info; PrimitiveType primitive_type; PrimitiveInfo *q; ssize_t i; size_t number_coordinates, z_count; ssize_t subpath_offset; subpath_offset=mvg_info->offset; primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; status=MagickTrue; attribute=0; number_coordinates=0; z_count=0; primitive_type=primitive_info->primitive; q=primitive_info; for (p=path; *p != '\0'; ) { if (status == MagickFalse) break; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == '\0') break; last_attribute=attribute; attribute=(int) (*p++); switch (attribute) { case 'a': case 'A': { double angle = 0.0; MagickBooleanType large_arc = MagickFalse, sweep = MagickFalse; PointInfo arc = {0.0, 0.0}; /* Elliptical arc. */ do { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); arc.x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); arc.y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); angle=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); large_arc=StringToLong(token) != 0 ? MagickTrue : MagickFalse; (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); sweep=StringToLong(token) != 0 ? MagickTrue : MagickFalse; if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); end.x=(double) (attribute == (int) 'A' ? x : point.x+x); end.y=(double) (attribute == (int) 'A' ? y : point.y+y); if (TraceArcPath(mvg_info,point,end,arc,angle,large_arc,sweep) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=q->coordinates; q+=q->coordinates; point=end; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'c': case 'C': { /* Cubic Bézier curve. */ do { points[0]=point; for (i=1; i < 4; i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); end.x=(double) (attribute == (int) 'C' ? x : point.x+x); end.y=(double) (attribute == (int) 'C' ? y : point.y+y); points[i]=end; } for (i=0; i < 4; i++) (q+i)->point=points[i]; if (TraceBezier(mvg_info,4) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=q->coordinates; q+=q->coordinates; point=end; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'H': case 'h': { do { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); point.x=(double) (attribute == (int) 'H' ? x: point.x+x); if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(-1); mvg_info->offset+=q->coordinates; q+=q->coordinates; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'l': case 'L': { /* Line to. */ do { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); point.x=(double) (attribute == (int) 'L' ? x : point.x+x); point.y=(double) (attribute == (int) 'L' ? y : point.y+y); if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(-1); mvg_info->offset+=q->coordinates; q+=q->coordinates; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'M': case 'm': { /* Move to. */ if (mvg_info->offset != subpath_offset) { primitive_info=(*mvg_info->primitive_info)+subpath_offset; primitive_info->coordinates=(size_t) (q-primitive_info); number_coordinates+=primitive_info->coordinates; primitive_info=q; subpath_offset=mvg_info->offset; } i=0; do { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); point.x=(double) (attribute == (int) 'M' ? x : point.x+x); point.y=(double) (attribute == (int) 'M' ? y : point.y+y); if (i == 0) start=point; i++; if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(-1); mvg_info->offset+=q->coordinates; q+=q->coordinates; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'q': case 'Q': { /* Quadratic Bézier curve. */ do { points[0]=point; for (i=1; i < 3; i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); if (*p == ',') p++; end.x=(double) (attribute == (int) 'Q' ? x : point.x+x); end.y=(double) (attribute == (int) 'Q' ? y : point.y+y); points[i]=end; } for (i=0; i < 3; i++) (q+i)->point=points[i]; if (TraceBezier(mvg_info,3) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=q->coordinates; q+=q->coordinates; point=end; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 's': case 'S': { /* Cubic Bézier curve. */ do { points[0]=points[3]; points[1].x=2.0*points[3].x-points[2].x; points[1].y=2.0*points[3].y-points[2].y; for (i=2; i < 4; i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); if (*p == ',') p++; end.x=(double) (attribute == (int) 'S' ? x : point.x+x); end.y=(double) (attribute == (int) 'S' ? y : point.y+y); points[i]=end; } if (strchr("CcSs",last_attribute) == (char *) NULL) { points[0]=point; points[1]=point; } for (i=0; i < 4; i++) (q+i)->point=points[i]; if (TraceBezier(mvg_info,4) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=q->coordinates; q+=q->coordinates; point=end; last_attribute=attribute; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 't': case 'T': { /* Quadratic Bézier curve. */ do { points[0]=points[2]; points[1].x=2.0*points[2].x-points[1].x; points[1].y=2.0*points[2].y-points[1].y; for (i=2; i < 3; i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); end.x=(double) (attribute == (int) 'T' ? x : point.x+x); end.y=(double) (attribute == (int) 'T' ? y : point.y+y); points[i]=end; } if (status == MagickFalse) break; if (strchr("QqTt",last_attribute) == (char *) NULL) { points[0]=point; points[1]=point; } for (i=0; i < 3; i++) (q+i)->point=points[i]; if (TraceBezier(mvg_info,3) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=q->coordinates; q+=q->coordinates; point=end; last_attribute=attribute; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'v': case 'V': { /* Line to. */ do { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); point.y=(double) (attribute == (int) 'V' ? y : point.y+y); if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(-1); mvg_info->offset+=q->coordinates; q+=q->coordinates; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'z': case 'Z': { /* Close path. */ point=start; if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(-1); mvg_info->offset+=q->coordinates; q+=q->coordinates; primitive_info=(*mvg_info->primitive_info)+subpath_offset; primitive_info->coordinates=(size_t) (q-primitive_info); primitive_info->closed_subpath=MagickTrue; number_coordinates+=primitive_info->coordinates; primitive_info=q; subpath_offset=mvg_info->offset; z_count++; break; } default: { ThrowPointExpectedException(token,exception); break; } } } if (status == MagickFalse) return(-1); primitive_info=(*mvg_info->primitive_info)+subpath_offset; primitive_info->coordinates=(size_t) (q-primitive_info); number_coordinates+=primitive_info->coordinates; for (i=0; i < (ssize_t) number_coordinates; i++) { q--; q->primitive=primitive_type; if (z_count > 1) q->method=FillToBorderMethod; } q=primitive_info; return((ssize_t) number_coordinates); } static MagickBooleanType TraceRectangle(PrimitiveInfo *primitive_info, const PointInfo start,const PointInfo end) { PointInfo point; PrimitiveInfo *p; ssize_t i; p=primitive_info; if (TracePoint(p,start) == MagickFalse) return(MagickFalse); p+=p->coordinates; point.x=start.x; point.y=end.y; if (TracePoint(p,point) == MagickFalse) return(MagickFalse); p+=p->coordinates; if (TracePoint(p,end) == MagickFalse) return(MagickFalse); p+=p->coordinates; point.x=end.x; point.y=start.y; if (TracePoint(p,point) == MagickFalse) return(MagickFalse); p+=p->coordinates; if (TracePoint(p,start) == MagickFalse) return(MagickFalse); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickTrue; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } return(MagickTrue); } static MagickBooleanType TraceRoundRectangle(MVGInfo *mvg_info, const PointInfo start,const PointInfo end,PointInfo arc) { PointInfo degrees, point, segment; PrimitiveInfo *primitive_info; PrimitiveInfo *p; ssize_t i; ssize_t offset; offset=mvg_info->offset; segment.x=fabs(end.x-start.x); segment.y=fabs(end.y-start.y); if ((segment.x < MagickEpsilon) || (segment.y < MagickEpsilon)) { (*mvg_info->primitive_info+mvg_info->offset)->coordinates=0; return(MagickTrue); } if (arc.x > (0.5*segment.x)) arc.x=0.5*segment.x; if (arc.y > (0.5*segment.y)) arc.y=0.5*segment.y; point.x=start.x+segment.x-arc.x; point.y=start.y+arc.y; degrees.x=270.0; degrees.y=360.0; if (TraceEllipse(mvg_info,point,arc,degrees) == MagickFalse) return(MagickFalse); p=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=p->coordinates; point.x=start.x+segment.x-arc.x; point.y=start.y+segment.y-arc.y; degrees.x=0.0; degrees.y=90.0; if (TraceEllipse(mvg_info,point,arc,degrees) == MagickFalse) return(MagickFalse); p=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=p->coordinates; point.x=start.x+arc.x; point.y=start.y+segment.y-arc.y; degrees.x=90.0; degrees.y=180.0; if (TraceEllipse(mvg_info,point,arc,degrees) == MagickFalse) return(MagickFalse); p=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=p->coordinates; point.x=start.x+arc.x; point.y=start.y+arc.y; degrees.x=180.0; degrees.y=270.0; if (TraceEllipse(mvg_info,point,arc,degrees) == MagickFalse) return(MagickFalse); p=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=p->coordinates; if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(MagickFalse); p=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(p,(*mvg_info->primitive_info+offset)->point) == MagickFalse) return(MagickFalse); p+=p->coordinates; mvg_info->offset=offset; primitive_info=(*mvg_info->primitive_info)+offset; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickTrue; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } return(MagickTrue); } static MagickBooleanType TraceSquareLinecap(PrimitiveInfo *primitive_info, const size_t number_vertices,const double offset) { double distance; double dx, dy; ssize_t i; ssize_t j; dx=0.0; dy=0.0; for (i=1; i < (ssize_t) number_vertices; i++) { dx=primitive_info[0].point.x-primitive_info[i].point.x; dy=primitive_info[0].point.y-primitive_info[i].point.y; if ((fabs((double) dx) >= MagickEpsilon) || (fabs((double) dy) >= MagickEpsilon)) break; } if (i == (ssize_t) number_vertices) i=(ssize_t) number_vertices-1L; distance=hypot((double) dx,(double) dy); primitive_info[0].point.x=(double) (primitive_info[i].point.x+ dx*(distance+offset)/distance); primitive_info[0].point.y=(double) (primitive_info[i].point.y+ dy*(distance+offset)/distance); for (j=(ssize_t) number_vertices-2; j >= 0; j--) { dx=primitive_info[number_vertices-1].point.x-primitive_info[j].point.x; dy=primitive_info[number_vertices-1].point.y-primitive_info[j].point.y; if ((fabs((double) dx) >= MagickEpsilon) || (fabs((double) dy) >= MagickEpsilon)) break; } distance=hypot((double) dx,(double) dy); primitive_info[number_vertices-1].point.x=(double) (primitive_info[j].point.x+ dx*(distance+offset)/distance); primitive_info[number_vertices-1].point.y=(double) (primitive_info[j].point.y+ dy*(distance+offset)/distance); return(MagickTrue); } static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *draw_info, const PrimitiveInfo *primitive_info,ExceptionInfo *exception) { #define MaxStrokePad (6*BezierQuantum+360) #define CheckPathExtent(pad_p,pad_q) \ { \ if ((pad_p) > MaxBezierCoordinates) \ stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); \ else \ if ((ssize_t) (p+(pad_p)) >= (ssize_t) extent_p) \ { \ if (~extent_p < (pad_p)) \ stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); \ else \ { \ extent_p+=(pad_p); \ stroke_p=(PointInfo *) ResizeQuantumMemory(stroke_p,extent_p+ \ MaxStrokePad,sizeof(*stroke_p)); \ } \ } \ if ((pad_q) > MaxBezierCoordinates) \ stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); \ else \ if ((ssize_t) (q+(pad_q)) >= (ssize_t) extent_q) \ { \ if (~extent_q < (pad_q)) \ stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); \ else \ { \ extent_q+=(pad_q); \ stroke_q=(PointInfo *) ResizeQuantumMemory(stroke_q,extent_q+ \ MaxStrokePad,sizeof(*stroke_q)); \ } \ } \ if ((stroke_p == (PointInfo *) NULL) || (stroke_q == (PointInfo *) NULL)) \ { \ if (stroke_p != (PointInfo *) NULL) \ stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); \ if (stroke_q != (PointInfo *) NULL) \ stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); \ polygon_primitive=(PrimitiveInfo *) \ RelinquishMagickMemory(polygon_primitive); \ (void) ThrowMagickException(exception,GetMagickModule(), \ ResourceLimitError,"MemoryAllocationFailed","`%s'",""); \ return((PrimitiveInfo *) NULL); \ } \ } typedef struct _StrokeSegment { double p, q; } StrokeSegment; double delta_theta, dot_product, mid, miterlimit; MagickBooleanType closed_path; PointInfo box_p[5], box_q[5], center, offset, *stroke_p, *stroke_q; PrimitiveInfo *polygon_primitive, *stroke_polygon; ssize_t i; size_t arc_segments, extent_p, extent_q, number_vertices; ssize_t j, n, p, q; StrokeSegment dx = {0.0, 0.0}, dy = {0.0, 0.0}, inverse_slope = {0.0, 0.0}, slope = {0.0, 0.0}, theta = {0.0, 0.0}; /* Allocate paths. */ number_vertices=primitive_info->coordinates; polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_vertices+2UL,sizeof(*polygon_primitive)); if (polygon_primitive == (PrimitiveInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return((PrimitiveInfo *) NULL); } (void) memcpy(polygon_primitive,primitive_info,(size_t) number_vertices* sizeof(*polygon_primitive)); offset.x=primitive_info[number_vertices-1].point.x-primitive_info[0].point.x; offset.y=primitive_info[number_vertices-1].point.y-primitive_info[0].point.y; closed_path=(fabs(offset.x) < MagickEpsilon) && (fabs(offset.y) < MagickEpsilon) ? MagickTrue : MagickFalse; if (((draw_info->linejoin == RoundJoin) || (draw_info->linejoin == MiterJoin)) && (closed_path != MagickFalse)) { polygon_primitive[number_vertices]=primitive_info[1]; number_vertices++; } polygon_primitive[number_vertices].primitive=UndefinedPrimitive; /* Compute the slope for the first line segment, p. */ dx.p=0.0; dy.p=0.0; for (n=1; n < (ssize_t) number_vertices; n++) { dx.p=polygon_primitive[n].point.x-polygon_primitive[0].point.x; dy.p=polygon_primitive[n].point.y-polygon_primitive[0].point.y; if ((fabs(dx.p) >= MagickEpsilon) || (fabs(dy.p) >= MagickEpsilon)) break; } if (n == (ssize_t) number_vertices) { if ((draw_info->linecap != RoundCap) || (closed_path != MagickFalse)) { /* Zero length subpath. */ stroke_polygon=(PrimitiveInfo *) AcquireCriticalMemory( sizeof(*stroke_polygon)); stroke_polygon[0]=polygon_primitive[0]; stroke_polygon[0].coordinates=0; polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory( polygon_primitive); return(stroke_polygon); } n=(ssize_t) number_vertices-1L; } extent_p=2*number_vertices; extent_q=2*number_vertices; stroke_p=(PointInfo *) AcquireQuantumMemory((size_t) extent_p+MaxStrokePad, sizeof(*stroke_p)); stroke_q=(PointInfo *) AcquireQuantumMemory((size_t) extent_q+MaxStrokePad, sizeof(*stroke_q)); if ((stroke_p == (PointInfo *) NULL) || (stroke_q == (PointInfo *) NULL)) { if (stroke_p != (PointInfo *) NULL) stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); if (stroke_q != (PointInfo *) NULL) stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return((PrimitiveInfo *) NULL); } slope.p=0.0; inverse_slope.p=0.0; if (fabs(dx.p) < MagickEpsilon) { if (dx.p >= 0.0) slope.p=dy.p < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon; else slope.p=dy.p < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon; } else if (fabs(dy.p) < MagickEpsilon) { if (dy.p >= 0.0) inverse_slope.p=dx.p < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon; else inverse_slope.p=dx.p < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon; } else { slope.p=dy.p/dx.p; inverse_slope.p=(-1.0/slope.p); } mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0; miterlimit=(double) (draw_info->miterlimit*draw_info->miterlimit*mid*mid); if ((draw_info->linecap == SquareCap) && (closed_path == MagickFalse)) (void) TraceSquareLinecap(polygon_primitive,number_vertices,mid); offset.x=sqrt((double) (mid*mid/(inverse_slope.p*inverse_slope.p+1.0))); offset.y=(double) (offset.x*inverse_slope.p); if ((dy.p*offset.x-dx.p*offset.y) > 0.0) { box_p[0].x=polygon_primitive[0].point.x-offset.x; box_p[0].y=polygon_primitive[0].point.y-offset.x*inverse_slope.p; box_p[1].x=polygon_primitive[n].point.x-offset.x; box_p[1].y=polygon_primitive[n].point.y-offset.x*inverse_slope.p; box_q[0].x=polygon_primitive[0].point.x+offset.x; box_q[0].y=polygon_primitive[0].point.y+offset.x*inverse_slope.p; box_q[1].x=polygon_primitive[n].point.x+offset.x; box_q[1].y=polygon_primitive[n].point.y+offset.x*inverse_slope.p; } else { box_p[0].x=polygon_primitive[0].point.x+offset.x; box_p[0].y=polygon_primitive[0].point.y+offset.y; box_p[1].x=polygon_primitive[n].point.x+offset.x; box_p[1].y=polygon_primitive[n].point.y+offset.y; box_q[0].x=polygon_primitive[0].point.x-offset.x; box_q[0].y=polygon_primitive[0].point.y-offset.y; box_q[1].x=polygon_primitive[n].point.x-offset.x; box_q[1].y=polygon_primitive[n].point.y-offset.y; } /* Create strokes for the line join attribute: bevel, miter, round. */ p=0; q=0; stroke_q[p++]=box_q[0]; stroke_p[q++]=box_p[0]; for (i=(ssize_t) n+1; i < (ssize_t) number_vertices; i++) { /* Compute the slope for this line segment, q. */ dx.q=polygon_primitive[i].point.x-polygon_primitive[n].point.x; dy.q=polygon_primitive[i].point.y-polygon_primitive[n].point.y; dot_product=dx.q*dx.q+dy.q*dy.q; if (dot_product < 0.25) continue; slope.q=0.0; inverse_slope.q=0.0; if (fabs(dx.q) < MagickEpsilon) { if (dx.q >= 0.0) slope.q=dy.q < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon; else slope.q=dy.q < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon; } else if (fabs(dy.q) < MagickEpsilon) { if (dy.q >= 0.0) inverse_slope.q=dx.q < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon; else inverse_slope.q=dx.q < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon; } else { slope.q=dy.q/dx.q; inverse_slope.q=(-1.0/slope.q); } offset.x=sqrt((double) (mid*mid/(inverse_slope.q*inverse_slope.q+1.0))); offset.y=(double) (offset.x*inverse_slope.q); dot_product=dy.q*offset.x-dx.q*offset.y; if (dot_product > 0.0) { box_p[2].x=polygon_primitive[n].point.x-offset.x; box_p[2].y=polygon_primitive[n].point.y-offset.y; box_p[3].x=polygon_primitive[i].point.x-offset.x; box_p[3].y=polygon_primitive[i].point.y-offset.y; box_q[2].x=polygon_primitive[n].point.x+offset.x; box_q[2].y=polygon_primitive[n].point.y+offset.y; box_q[3].x=polygon_primitive[i].point.x+offset.x; box_q[3].y=polygon_primitive[i].point.y+offset.y; } else { box_p[2].x=polygon_primitive[n].point.x+offset.x; box_p[2].y=polygon_primitive[n].point.y+offset.y; box_p[3].x=polygon_primitive[i].point.x+offset.x; box_p[3].y=polygon_primitive[i].point.y+offset.y; box_q[2].x=polygon_primitive[n].point.x-offset.x; box_q[2].y=polygon_primitive[n].point.y-offset.y; box_q[3].x=polygon_primitive[i].point.x-offset.x; box_q[3].y=polygon_primitive[i].point.y-offset.y; } if (fabs((double) (slope.p-slope.q)) < MagickEpsilon) { box_p[4]=box_p[1]; box_q[4]=box_q[1]; } else { box_p[4].x=(double) ((slope.p*box_p[0].x-box_p[0].y-slope.q*box_p[3].x+ box_p[3].y)/(slope.p-slope.q)); box_p[4].y=(double) (slope.p*(box_p[4].x-box_p[0].x)+box_p[0].y); box_q[4].x=(double) ((slope.p*box_q[0].x-box_q[0].y-slope.q*box_q[3].x+ box_q[3].y)/(slope.p-slope.q)); box_q[4].y=(double) (slope.p*(box_q[4].x-box_q[0].x)+box_q[0].y); } CheckPathExtent(MaxStrokePad,MaxStrokePad); dot_product=dx.q*dy.p-dx.p*dy.q; if (dot_product <= 0.0) switch (draw_info->linejoin) { case BevelJoin: { stroke_q[q++]=box_q[1]; stroke_q[q++]=box_q[2]; dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) stroke_p[p++]=box_p[4]; else { stroke_p[p++]=box_p[1]; stroke_p[p++]=box_p[2]; } break; } case MiterJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) { stroke_q[q++]=box_q[4]; stroke_p[p++]=box_p[4]; } else { stroke_q[q++]=box_q[1]; stroke_q[q++]=box_q[2]; stroke_p[p++]=box_p[1]; stroke_p[p++]=box_p[2]; } break; } case RoundJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) stroke_p[p++]=box_p[4]; else { stroke_p[p++]=box_p[1]; stroke_p[p++]=box_p[2]; } center=polygon_primitive[n].point; theta.p=atan2(box_q[1].y-center.y,box_q[1].x-center.x); theta.q=atan2(box_q[2].y-center.y,box_q[2].x-center.x); if (theta.q < theta.p) theta.q+=2.0*MagickPI; arc_segments=(size_t) CastDoubleToLong(ceil((double) ((theta. q-theta.p)/(2.0*sqrt(PerceptibleReciprocal(mid)))))); CheckPathExtent(MaxStrokePad,arc_segments+MaxStrokePad); stroke_q[q].x=box_q[1].x; stroke_q[q].y=box_q[1].y; q++; for (j=1; j < (ssize_t) arc_segments; j++) { delta_theta=(double) (j*(theta.q-theta.p)/arc_segments); stroke_q[q].x=(double) (center.x+mid*cos(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); stroke_q[q].y=(double) (center.y+mid*sin(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); q++; } stroke_q[q++]=box_q[2]; break; } default: break; } else switch (draw_info->linejoin) { case BevelJoin: { stroke_p[p++]=box_p[1]; stroke_p[p++]=box_p[2]; dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) stroke_q[q++]=box_q[4]; else { stroke_q[q++]=box_q[1]; stroke_q[q++]=box_q[2]; } break; } case MiterJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) { stroke_q[q++]=box_q[4]; stroke_p[p++]=box_p[4]; } else { stroke_q[q++]=box_q[1]; stroke_q[q++]=box_q[2]; stroke_p[p++]=box_p[1]; stroke_p[p++]=box_p[2]; } break; } case RoundJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) stroke_q[q++]=box_q[4]; else { stroke_q[q++]=box_q[1]; stroke_q[q++]=box_q[2]; } center=polygon_primitive[n].point; theta.p=atan2(box_p[1].y-center.y,box_p[1].x-center.x); theta.q=atan2(box_p[2].y-center.y,box_p[2].x-center.x); if (theta.p < theta.q) theta.p+=2.0*MagickPI; arc_segments=(size_t) CastDoubleToLong(ceil((double) ((theta.p- theta.q)/(2.0*sqrt((double) (PerceptibleReciprocal(mid))))))); CheckPathExtent(arc_segments+MaxStrokePad,MaxStrokePad); stroke_p[p++]=box_p[1]; for (j=1; j < (ssize_t) arc_segments; j++) { delta_theta=(double) (j*(theta.q-theta.p)/arc_segments); stroke_p[p].x=(double) (center.x+mid*cos(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); stroke_p[p].y=(double) (center.y+mid*sin(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); p++; } stroke_p[p++]=box_p[2]; break; } default: break; } slope.p=slope.q; inverse_slope.p=inverse_slope.q; box_p[0]=box_p[2]; box_p[1]=box_p[3]; box_q[0]=box_q[2]; box_q[1]=box_q[3]; dx.p=dx.q; dy.p=dy.q; n=i; } stroke_p[p++]=box_p[1]; stroke_q[q++]=box_q[1]; /* Trace stroked polygon. */ stroke_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t) (p+q+2UL*closed_path+2UL),sizeof(*stroke_polygon)); if (stroke_polygon == (PrimitiveInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory( polygon_primitive); return(stroke_polygon); } for (i=0; i < (ssize_t) p; i++) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_p[i]; } if (closed_path != MagickFalse) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[0].point; i++; } for ( ; i < (ssize_t) (p+q+closed_path); i++) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_q[p+q+closed_path-(i+1)]; } if (closed_path != MagickFalse) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[p+closed_path].point; i++; } stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[0].point; i++; stroke_polygon[i].primitive=UndefinedPrimitive; stroke_polygon[0].coordinates=(size_t) (p+q+2*closed_path+1); stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive); return(stroke_polygon); }
kmp_csupport.c
/* * kmp_csupport.c -- kfront linkage support for OpenMP. */ //===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.txt for details. // //===----------------------------------------------------------------------===// #include "omp.h" /* extern "C" declarations of user-visible routines */ #include "kmp.h" #include "kmp_i18n.h" #include "kmp_itt.h" #include "kmp_error.h" #include "kmp_stats.h" #if OMPT_SUPPORT #include "ompt-internal.h" #include "ompt-specific.h" #endif #define MAX_MESSAGE 512 /* ------------------------------------------------------------------------ */ /* ------------------------------------------------------------------------ */ /* flags will be used in future, e.g., to implement */ /* openmp_strict library restrictions */ /*! * @ingroup STARTUP_SHUTDOWN * @param loc in source location information * @param flags in for future use (currently ignored) * * Initialize the runtime library. This call is optional; if it is not made then * it will be implicitly called by attempts to use other library functions. * */ void __kmpc_begin(ident_t *loc, kmp_int32 flags) { // By default __kmp_ignore_mppbeg() returns TRUE. if (__kmp_ignore_mppbeg() == FALSE) { __kmp_internal_begin(); KC_TRACE( 10, ("__kmpc_begin: called\n" ) ); } } /*! * @ingroup STARTUP_SHUTDOWN * @param loc source location information * * Shutdown the runtime library. This is also optional, and even if called will not * do anything unless the `KMP_IGNORE_MPPEND` environment variable is set to zero. */ void __kmpc_end(ident_t *loc) { // By default, __kmp_ignore_mppend() returns TRUE which makes __kmpc_end() call no-op. // However, this can be overridden with KMP_IGNORE_MPPEND environment variable. // If KMP_IGNORE_MPPEND is 0, __kmp_ignore_mppend() returns FALSE and __kmpc_end() // will unregister this root (it can cause library shut down). if (__kmp_ignore_mppend() == FALSE) { KC_TRACE( 10, ("__kmpc_end: called\n" ) ); KA_TRACE( 30, ("__kmpc_end\n" )); __kmp_internal_end_thread( -1 ); } } /*! @ingroup THREAD_STATES @param loc Source location information. @return The global thread index of the active thread. This function can be called in any context. If the runtime has ony been entered at the outermost level from a single (necessarily non-OpenMP<sup>*</sup>) thread, then the thread number is that which would be returned by omp_get_thread_num() in the outermost active parallel construct. (Or zero if there is no active parallel construct, since the master thread is necessarily thread zero). If multiple non-OpenMP threads all enter an OpenMP construct then this will be a unique thread identifier among all the threads created by the OpenMP runtime (but the value cannote be defined in terms of OpenMP thread ids returned by omp_get_thread_num()). */ kmp_int32 __kmpc_global_thread_num(ident_t *loc) { kmp_int32 gtid = __kmp_entry_gtid(); KC_TRACE( 10, ("__kmpc_global_thread_num: T#%d\n", gtid ) ); return gtid; } /*! @ingroup THREAD_STATES @param loc Source location information. @return The number of threads under control of the OpenMP<sup>*</sup> runtime This function can be called in any context. It returns the total number of threads under the control of the OpenMP runtime. That is not a number that can be determined by any OpenMP standard calls, since the library may be called from more than one non-OpenMP thread, and this reflects the total over all such calls. Similarly the runtime maintains underlying threads even when they are not active (since the cost of creating and destroying OS threads is high), this call counts all such threads even if they are not waiting for work. */ kmp_int32 __kmpc_global_num_threads(ident_t *loc) { KC_TRACE( 10, ("__kmpc_global_num_threads: num_threads = %d\n", __kmp_nth ) ); return TCR_4(__kmp_nth); } /*! @ingroup THREAD_STATES @param loc Source location information. @return The thread number of the calling thread in the innermost active parallel construct. */ kmp_int32 __kmpc_bound_thread_num(ident_t *loc) { KC_TRACE( 10, ("__kmpc_bound_thread_num: called\n" ) ); return __kmp_tid_from_gtid( __kmp_entry_gtid() ); } /*! @ingroup THREAD_STATES @param loc Source location information. @return The number of threads in the innermost active parallel construct. */ kmp_int32 __kmpc_bound_num_threads(ident_t *loc) { KC_TRACE( 10, ("__kmpc_bound_num_threads: called\n" ) ); return __kmp_entry_thread() -> th.th_team -> t.t_nproc; } /*! * @ingroup DEPRECATED * @param loc location description * * This function need not be called. It always returns TRUE. */ kmp_int32 __kmpc_ok_to_fork(ident_t *loc) { #ifndef KMP_DEBUG return TRUE; #else const char *semi2; const char *semi3; int line_no; if (__kmp_par_range == 0) { return TRUE; } semi2 = loc->psource; if (semi2 == NULL) { return TRUE; } semi2 = strchr(semi2, ';'); if (semi2 == NULL) { return TRUE; } semi2 = strchr(semi2 + 1, ';'); if (semi2 == NULL) { return TRUE; } if (__kmp_par_range_filename[0]) { const char *name = semi2 - 1; while ((name > loc->psource) && (*name != '/') && (*name != ';')) { name--; } if ((*name == '/') || (*name == ';')) { name++; } if (strncmp(__kmp_par_range_filename, name, semi2 - name)) { return __kmp_par_range < 0; } } semi3 = strchr(semi2 + 1, ';'); if (__kmp_par_range_routine[0]) { if ((semi3 != NULL) && (semi3 > semi2) && (strncmp(__kmp_par_range_routine, semi2 + 1, semi3 - semi2 - 1))) { return __kmp_par_range < 0; } } if (KMP_SSCANF(semi3 + 1, "%d", &line_no) == 1) { if ((line_no >= __kmp_par_range_lb) && (line_no <= __kmp_par_range_ub)) { return __kmp_par_range > 0; } return __kmp_par_range < 0; } return TRUE; #endif /* KMP_DEBUG */ } /*! @ingroup THREAD_STATES @param loc Source location information. @return 1 if this thread is executing inside an active parallel region, zero if not. */ kmp_int32 __kmpc_in_parallel( ident_t *loc ) { return __kmp_entry_thread() -> th.th_root -> r.r_active; } /*! @ingroup PARALLEL @param loc source location information @param global_tid global thread number @param num_threads number of threads requested for this parallel construct Set the number of threads to be used by the next fork spawned by this thread. This call is only required if the parallel construct has a `num_threads` clause. */ void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid, kmp_int32 num_threads ) { KA_TRACE( 20, ("__kmpc_push_num_threads: enter T#%d num_threads=%d\n", global_tid, num_threads ) ); __kmp_push_num_threads( loc, global_tid, num_threads ); } void __kmpc_pop_num_threads(ident_t *loc, kmp_int32 global_tid ) { KA_TRACE( 20, ("__kmpc_pop_num_threads: enter\n" ) ); /* the num_threads are automatically popped */ } #if OMP_40_ENABLED void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid, kmp_int32 proc_bind ) { KA_TRACE( 20, ("__kmpc_push_proc_bind: enter T#%d proc_bind=%d\n", global_tid, proc_bind ) ); __kmp_push_proc_bind( loc, global_tid, (kmp_proc_bind_t)proc_bind ); } #endif /* OMP_40_ENABLED */ /*! @ingroup PARALLEL @param loc source location information @param argc total number of arguments in the ellipsis @param microtask pointer to callback routine consisting of outlined parallel construct @param ... pointers to shared variables that aren't global Do the actual fork and call the microtask in the relevant number of threads. */ void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro microtask, ...) { KMP_STOP_EXPLICIT_TIMER(OMP_serial); KMP_COUNT_BLOCK(OMP_PARALLEL); int gtid = __kmp_entry_gtid(); // maybe to save thr_state is enough here { va_list ap; va_start( ap, microtask ); #if OMPT_SUPPORT int tid = __kmp_tid_from_gtid( gtid ); kmp_info_t *master_th = __kmp_threads[ gtid ]; kmp_team_t *parent_team = master_th->th.th_team; if (ompt_status & ompt_status_track) { parent_team->t.t_implicit_task_taskdata[tid]. ompt_task_info.frame.reenter_runtime_frame = __builtin_frame_address(0); } #endif #if INCLUDE_SSC_MARKS SSC_MARK_FORKING(); #endif __kmp_fork_call( loc, gtid, fork_context_intel, argc, #if OMPT_SUPPORT VOLATILE_CAST(void *) microtask, // "unwrapped" task #endif VOLATILE_CAST(microtask_t) microtask, // "wrapped" task VOLATILE_CAST(launch_t) __kmp_invoke_task_func, /* TODO: revert workaround for Intel(R) 64 tracker #96 */ #if (KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) && KMP_OS_LINUX &ap #else ap #endif ); #if INCLUDE_SSC_MARKS SSC_MARK_JOINING(); #endif __kmp_join_call( loc, gtid, fork_context_intel ); va_end( ap ); #if OMPT_SUPPORT if (ompt_status & ompt_status_track) { parent_team->t.t_implicit_task_taskdata[tid]. ompt_task_info.frame.reenter_runtime_frame = 0; } #endif } KMP_START_EXPLICIT_TIMER(OMP_serial); } #if OMP_40_ENABLED /*! @ingroup PARALLEL @param loc source location information @param global_tid global thread number @param num_teams number of teams requested for the teams construct @param num_threads number of threads per team requested for the teams construct Set the number of teams to be used by the teams construct. This call is only required if the teams construct has a `num_teams` clause or a `thread_limit` clause (or both). */ void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid, kmp_int32 num_teams, kmp_int32 num_threads ) { KA_TRACE( 20, ("__kmpc_push_num_teams: enter T#%d num_teams=%d num_threads=%d\n", global_tid, num_teams, num_threads ) ); __kmp_push_num_teams( loc, global_tid, num_teams, num_threads ); } /*! @ingroup PARALLEL @param loc source location information @param argc total number of arguments in the ellipsis @param microtask pointer to callback routine consisting of outlined teams construct @param ... pointers to shared variables that aren't global Do the actual fork and call the microtask in the relevant number of threads. */ void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro microtask, ...) { int gtid = __kmp_entry_gtid(); kmp_info_t *this_thr = __kmp_threads[ gtid ]; va_list ap; va_start( ap, microtask ); // remember teams entry point and nesting level this_thr->th.th_teams_microtask = microtask; this_thr->th.th_teams_level = this_thr->th.th_team->t.t_level; // AC: can be >0 on host #if OMPT_SUPPORT kmp_team_t *parent_team = this_thr->th.th_team; int tid = __kmp_tid_from_gtid( gtid ); if (ompt_status & ompt_status_track) { parent_team->t.t_implicit_task_taskdata[tid]. ompt_task_info.frame.reenter_runtime_frame = __builtin_frame_address(0); } #endif // check if __kmpc_push_num_teams called, set default number of teams otherwise if ( this_thr->th.th_teams_size.nteams == 0 ) { __kmp_push_num_teams( loc, gtid, 0, 0 ); } KMP_DEBUG_ASSERT(this_thr->th.th_set_nproc >= 1); KMP_DEBUG_ASSERT(this_thr->th.th_teams_size.nteams >= 1); KMP_DEBUG_ASSERT(this_thr->th.th_teams_size.nth >= 1); __kmp_fork_call( loc, gtid, fork_context_intel, argc, #if OMPT_SUPPORT VOLATILE_CAST(void *) microtask, // "unwrapped" task #endif VOLATILE_CAST(microtask_t) __kmp_teams_master, // "wrapped" task VOLATILE_CAST(launch_t) __kmp_invoke_teams_master, #if (KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) && KMP_OS_LINUX &ap #else ap #endif ); __kmp_join_call( loc, gtid, fork_context_intel ); #if OMPT_SUPPORT if (ompt_status & ompt_status_track) { parent_team->t.t_implicit_task_taskdata[tid]. ompt_task_info.frame.reenter_runtime_frame = NULL; } #endif this_thr->th.th_teams_microtask = NULL; this_thr->th.th_teams_level = 0; *(kmp_int64*)(&this_thr->th.th_teams_size) = 0L; va_end( ap ); } #endif /* OMP_40_ENABLED */ // // I don't think this function should ever have been exported. // The __kmpc_ prefix was misapplied. I'm fairly certain that no generated // openmp code ever called it, but it's been exported from the RTL for so // long that I'm afraid to remove the definition. // int __kmpc_invoke_task_func( int gtid ) { return __kmp_invoke_task_func( gtid ); } /*! @ingroup PARALLEL @param loc source location information @param global_tid global thread number Enter a serialized parallel construct. This interface is used to handle a conditional parallel region, like this, @code #pragma omp parallel if (condition) @endcode when the condition is false. */ void __kmpc_serialized_parallel(ident_t *loc, kmp_int32 global_tid) { __kmp_serialized_parallel(loc, global_tid); /* The implementation is now in kmp_runtime.c so that it can share static functions with * kmp_fork_call since the tasks to be done are similar in each case. */ } /*! @ingroup PARALLEL @param loc source location information @param global_tid global thread number Leave a serialized parallel construct. */ void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32 global_tid) { kmp_internal_control_t *top; kmp_info_t *this_thr; kmp_team_t *serial_team; KC_TRACE( 10, ("__kmpc_end_serialized_parallel: called by T#%d\n", global_tid ) ); /* skip all this code for autopar serialized loops since it results in unacceptable overhead */ if( loc != NULL && (loc->flags & KMP_IDENT_AUTOPAR ) ) return; // Not autopar code if( ! TCR_4( __kmp_init_parallel ) ) __kmp_parallel_initialize(); this_thr = __kmp_threads[ global_tid ]; serial_team = this_thr->th.th_serial_team; #if OMP_41_ENABLED kmp_task_team_t * task_team = this_thr->th.th_task_team; // we need to wait for the proxy tasks before finishing the thread if ( task_team != NULL && task_team->tt.tt_found_proxy_tasks ) __kmp_task_team_wait(this_thr, serial_team, NULL ); // is an ITT object needed here? #endif KMP_MB(); KMP_DEBUG_ASSERT( serial_team ); KMP_ASSERT( serial_team -> t.t_serialized ); KMP_DEBUG_ASSERT( this_thr -> th.th_team == serial_team ); KMP_DEBUG_ASSERT( serial_team != this_thr->th.th_root->r.r_root_team ); KMP_DEBUG_ASSERT( serial_team -> t.t_threads ); KMP_DEBUG_ASSERT( serial_team -> t.t_threads[0] == this_thr ); /* If necessary, pop the internal control stack values and replace the team values */ top = serial_team -> t.t_control_stack_top; if ( top && top -> serial_nesting_level == serial_team -> t.t_serialized ) { copy_icvs( &serial_team -> t.t_threads[0] -> th.th_current_task -> td_icvs, top ); serial_team -> t.t_control_stack_top = top -> next; __kmp_free(top); } //if( serial_team -> t.t_serialized > 1 ) serial_team -> t.t_level--; /* pop dispatch buffers stack */ KMP_DEBUG_ASSERT(serial_team->t.t_dispatch->th_disp_buffer); { dispatch_private_info_t * disp_buffer = serial_team->t.t_dispatch->th_disp_buffer; serial_team->t.t_dispatch->th_disp_buffer = serial_team->t.t_dispatch->th_disp_buffer->next; __kmp_free( disp_buffer ); } -- serial_team -> t.t_serialized; if ( serial_team -> t.t_serialized == 0 ) { /* return to the parallel section */ #if KMP_ARCH_X86 || KMP_ARCH_X86_64 if ( __kmp_inherit_fp_control && serial_team->t.t_fp_control_saved ) { __kmp_clear_x87_fpu_status_word(); __kmp_load_x87_fpu_control_word( &serial_team->t.t_x87_fpu_control_word ); __kmp_load_mxcsr( &serial_team->t.t_mxcsr ); } #endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */ this_thr -> th.th_team = serial_team -> t.t_parent; this_thr -> th.th_info.ds.ds_tid = serial_team -> t.t_master_tid; /* restore values cached in the thread */ this_thr -> th.th_team_nproc = serial_team -> t.t_parent -> t.t_nproc; /* JPH */ this_thr -> th.th_team_master = serial_team -> t.t_parent -> t.t_threads[0]; /* JPH */ this_thr -> th.th_team_serialized = this_thr -> th.th_team -> t.t_serialized; /* TODO the below shouldn't need to be adjusted for serialized teams */ this_thr -> th.th_dispatch = & this_thr -> th.th_team -> t.t_dispatch[ serial_team -> t.t_master_tid ]; __kmp_pop_current_task_from_thread( this_thr ); KMP_ASSERT( this_thr -> th.th_current_task -> td_flags.executing == 0 ); this_thr -> th.th_current_task -> td_flags.executing = 1; if ( __kmp_tasking_mode != tskm_immediate_exec ) { // Copy the task team from the new child / old parent team to the thread. this_thr->th.th_task_team = this_thr->th.th_team->t.t_task_team[this_thr->th.th_task_state]; KA_TRACE( 20, ( "__kmpc_end_serialized_parallel: T#%d restoring task_team %p / team %p\n", global_tid, this_thr -> th.th_task_team, this_thr -> th.th_team ) ); } } else { if ( __kmp_tasking_mode != tskm_immediate_exec ) { KA_TRACE( 20, ( "__kmpc_end_serialized_parallel: T#%d decreasing nesting depth of serial team %p to %d\n", global_tid, serial_team, serial_team -> t.t_serialized ) ); } } #if USE_ITT_BUILD kmp_uint64 cur_time = 0; #if USE_ITT_NOTIFY if ( __itt_get_timestamp_ptr ) { cur_time = __itt_get_timestamp(); } #endif /* USE_ITT_NOTIFY */ if ( this_thr->th.th_team->t.t_level == 0 #if OMP_40_ENABLED && this_thr->th.th_teams_microtask == NULL #endif ) { // Report the barrier this_thr->th.th_ident = loc; if ( ( __itt_frame_submit_v3_ptr || KMP_ITT_DEBUG ) && ( __kmp_forkjoin_frames_mode == 3 || __kmp_forkjoin_frames_mode == 1 ) ) { __kmp_itt_frame_submit( global_tid, this_thr->th.th_frame_time_serialized, cur_time, 0, loc, this_thr->th.th_team_nproc, 0 ); if ( __kmp_forkjoin_frames_mode == 3 ) // Since barrier frame for serialized region is equal to the region we use the same begin timestamp as for the barrier. __kmp_itt_frame_submit( global_tid, serial_team->t.t_region_time, cur_time, 0, loc, this_thr->th.th_team_nproc, 2 ); } else if ( ( __itt_frame_end_v3_ptr || KMP_ITT_DEBUG ) && ! __kmp_forkjoin_frames_mode && __kmp_forkjoin_frames ) // Mark the end of the "parallel" region for VTune. Only use one of frame notification scheme at the moment. __kmp_itt_region_joined( global_tid, 1 ); } #endif /* USE_ITT_BUILD */ if ( __kmp_env_consistency_check ) __kmp_pop_parallel( global_tid, NULL ); } /*! @ingroup SYNCHRONIZATION @param loc source location information. Execute <tt>flush</tt>. This is implemented as a full memory fence. (Though depending on the memory ordering convention obeyed by the compiler even that may not be necessary). */ void __kmpc_flush(ident_t *loc) { KC_TRACE( 10, ("__kmpc_flush: called\n" ) ); /* need explicit __mf() here since use volatile instead in library */ KMP_MB(); /* Flush all pending memory write invalidates. */ #if ( KMP_ARCH_X86 || KMP_ARCH_X86_64 ) #if KMP_MIC // fence-style instructions do not exist, but lock; xaddl $0,(%rsp) can be used. // We shouldn't need it, though, since the ABI rules require that // * If the compiler generates NGO stores it also generates the fence // * If users hand-code NGO stores they should insert the fence // therefore no incomplete unordered stores should be visible. #else // C74404 // This is to address non-temporal store instructions (sfence needed). // The clflush instruction is addressed either (mfence needed). // Probably the non-temporal load monvtdqa instruction should also be addressed. // mfence is a SSE2 instruction. Do not execute it if CPU is not SSE2. if ( ! __kmp_cpuinfo.initialized ) { __kmp_query_cpuid( & __kmp_cpuinfo ); }; // if if ( ! __kmp_cpuinfo.sse2 ) { // CPU cannot execute SSE2 instructions. } else { #if KMP_COMPILER_ICC || KMP_COMPILER_MSVC _mm_mfence(); #else __sync_synchronize(); #endif // KMP_COMPILER_ICC }; // if #endif // KMP_MIC #elif (KMP_ARCH_ARM || KMP_ARCH_AARCH64) // Nothing to see here move along #elif KMP_ARCH_PPC64 // Nothing needed here (we have a real MB above). #if KMP_OS_CNK // The flushing thread needs to yield here; this prevents a // busy-waiting thread from saturating the pipeline. flush is // often used in loops like this: // while (!flag) { // #pragma omp flush(flag) // } // and adding the yield here is good for at least a 10x speedup // when running >2 threads per core (on the NAS LU benchmark). __kmp_yield(TRUE); #endif #else #error Unknown or unsupported architecture #endif } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid thread id. Execute a barrier. */ void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid) { KMP_COUNT_BLOCK(OMP_BARRIER); KMP_TIME_BLOCK(OMP_barrier); KC_TRACE( 10, ("__kmpc_barrier: called T#%d\n", global_tid ) ); if (! TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); if ( __kmp_env_consistency_check ) { if ( loc == 0 ) { KMP_WARNING( ConstructIdentInvalid ); // ??? What does it mean for the user? }; // if __kmp_check_barrier( global_tid, ct_barrier, loc ); } __kmp_threads[ global_tid ]->th.th_ident = loc; // TODO: explicit barrier_wait_id: // this function is called when 'barrier' directive is present or // implicit barrier at the end of a worksharing construct. // 1) better to add a per-thread barrier counter to a thread data structure // 2) set to 0 when a new team is created // 4) no sync is required __kmp_barrier( bs_plain_barrier, global_tid, FALSE, 0, NULL, NULL ); } /* The BARRIER for a MASTER section is always explicit */ /*! @ingroup WORK_SHARING @param loc source location information. @param global_tid global thread number . @return 1 if this thread should execute the <tt>master</tt> block, 0 otherwise. */ kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid) { KMP_COUNT_BLOCK(OMP_MASTER); int status = 0; KC_TRACE( 10, ("__kmpc_master: called T#%d\n", global_tid ) ); if( ! TCR_4( __kmp_init_parallel ) ) __kmp_parallel_initialize(); if( KMP_MASTER_GTID( global_tid )) status = 1; #if OMPT_SUPPORT && OMPT_TRACE if (status) { if ((ompt_status == ompt_status_track_callback) && ompt_callbacks.ompt_callback(ompt_event_master_begin)) { kmp_info_t *this_thr = __kmp_threads[ global_tid ]; kmp_team_t *team = this_thr -> th.th_team; int tid = __kmp_tid_from_gtid( global_tid ); ompt_callbacks.ompt_callback(ompt_event_master_begin)( team->t.ompt_team_info.parallel_id, team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_id); } } #endif if ( __kmp_env_consistency_check ) { #if KMP_USE_DYNAMIC_LOCK if (status) __kmp_push_sync( global_tid, ct_master, loc, NULL, 0 ); else __kmp_check_sync( global_tid, ct_master, loc, NULL, 0 ); #else if (status) __kmp_push_sync( global_tid, ct_master, loc, NULL ); else __kmp_check_sync( global_tid, ct_master, loc, NULL ); #endif } return status; } /*! @ingroup WORK_SHARING @param loc source location information. @param global_tid global thread number . Mark the end of a <tt>master</tt> region. This should only be called by the thread that executes the <tt>master</tt> region. */ void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid) { KC_TRACE( 10, ("__kmpc_end_master: called T#%d\n", global_tid ) ); KMP_DEBUG_ASSERT( KMP_MASTER_GTID( global_tid )); #if OMPT_SUPPORT && OMPT_TRACE kmp_info_t *this_thr = __kmp_threads[ global_tid ]; kmp_team_t *team = this_thr -> th.th_team; if ((ompt_status == ompt_status_track_callback) && ompt_callbacks.ompt_callback(ompt_event_master_end)) { int tid = __kmp_tid_from_gtid( global_tid ); ompt_callbacks.ompt_callback(ompt_event_master_end)( team->t.ompt_team_info.parallel_id, team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_id); } #endif if ( __kmp_env_consistency_check ) { if( global_tid < 0 ) KMP_WARNING( ThreadIdentInvalid ); if( KMP_MASTER_GTID( global_tid )) __kmp_pop_sync( global_tid, ct_master, loc ); } } /*! @ingroup WORK_SHARING @param loc source location information. @param gtid global thread number. Start execution of an <tt>ordered</tt> construct. */ void __kmpc_ordered( ident_t * loc, kmp_int32 gtid ) { int cid = 0; kmp_info_t *th; KMP_DEBUG_ASSERT( __kmp_init_serial ); KC_TRACE( 10, ("__kmpc_ordered: called T#%d\n", gtid )); if (! TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); #if USE_ITT_BUILD __kmp_itt_ordered_prep( gtid ); // TODO: ordered_wait_id #endif /* USE_ITT_BUILD */ th = __kmp_threads[ gtid ]; #if OMPT_SUPPORT && OMPT_TRACE if (ompt_status & ompt_status_track) { /* OMPT state update */ th->th.ompt_thread_info.wait_id = (uint64_t) loc; th->th.ompt_thread_info.state = ompt_state_wait_ordered; /* OMPT event callback */ if ((ompt_status == ompt_status_track_callback) && ompt_callbacks.ompt_callback(ompt_event_wait_ordered)) { ompt_callbacks.ompt_callback(ompt_event_wait_ordered)( th->th.ompt_thread_info.wait_id); } } #endif if ( th -> th.th_dispatch -> th_deo_fcn != 0 ) (*th->th.th_dispatch->th_deo_fcn)( & gtid, & cid, loc ); else __kmp_parallel_deo( & gtid, & cid, loc ); #if OMPT_SUPPORT && OMPT_TRACE if (ompt_status & ompt_status_track) { /* OMPT state update */ th->th.ompt_thread_info.state = ompt_state_work_parallel; th->th.ompt_thread_info.wait_id = 0; /* OMPT event callback */ if ((ompt_status == ompt_status_track_callback) && ompt_callbacks.ompt_callback(ompt_event_acquired_ordered)) { ompt_callbacks.ompt_callback(ompt_event_acquired_ordered)( th->th.ompt_thread_info.wait_id); } } #endif #if USE_ITT_BUILD __kmp_itt_ordered_start( gtid ); #endif /* USE_ITT_BUILD */ } /*! @ingroup WORK_SHARING @param loc source location information. @param gtid global thread number. End execution of an <tt>ordered</tt> construct. */ void __kmpc_end_ordered( ident_t * loc, kmp_int32 gtid ) { int cid = 0; kmp_info_t *th; KC_TRACE( 10, ("__kmpc_end_ordered: called T#%d\n", gtid ) ); #if USE_ITT_BUILD __kmp_itt_ordered_end( gtid ); // TODO: ordered_wait_id #endif /* USE_ITT_BUILD */ th = __kmp_threads[ gtid ]; if ( th -> th.th_dispatch -> th_dxo_fcn != 0 ) (*th->th.th_dispatch->th_dxo_fcn)( & gtid, & cid, loc ); else __kmp_parallel_dxo( & gtid, & cid, loc ); #if OMPT_SUPPORT && OMPT_BLAME if ((ompt_status == ompt_status_track_callback) && ompt_callbacks.ompt_callback(ompt_event_release_ordered)) { ompt_callbacks.ompt_callback(ompt_event_release_ordered)( th->th.ompt_thread_info.wait_id); } #endif } #if KMP_USE_DYNAMIC_LOCK static __forceinline kmp_indirect_lock_t * __kmp_get_indirect_csptr(kmp_critical_name * crit, ident_t const * loc, kmp_int32 gtid, kmp_dyna_lockseq_t seq) { // Code from __kmp_get_critical_section_ptr // This function returns an indirect lock object instead of a user lock. kmp_indirect_lock_t **lck, *ret; lck = (kmp_indirect_lock_t **)crit; ret = (kmp_indirect_lock_t *)TCR_PTR(*lck); if (ret == NULL) { void *idx; kmp_indirect_locktag_t tag = DYNA_GET_I_TAG(seq); kmp_indirect_lock_t *ilk = __kmp_allocate_indirect_lock(&idx, gtid, tag); ret = ilk; DYNA_I_LOCK_FUNC(ilk, init)(ilk->lock); DYNA_SET_I_LOCK_LOCATION(ilk, loc); DYNA_SET_I_LOCK_FLAGS(ilk, kmp_lf_critical_section); KA_TRACE(20, ("__kmp_get_indirect_csptr: initialized indirect lock #%d\n", tag)); #if USE_ITT_BUILD __kmp_itt_critical_creating(ilk->lock, loc); #endif int status = KMP_COMPARE_AND_STORE_PTR(lck, 0, ilk); if (status == 0) { #if USE_ITT_BUILD __kmp_itt_critical_destroyed(ilk->lock); #endif // Postponing destroy, to avoid costly dispatch here. //DYNA_D_LOCK_FUNC(&idx, destroy)((kmp_dyna_lock_t *)&idx); ret = (kmp_indirect_lock_t *)TCR_PTR(*lck); KMP_DEBUG_ASSERT(ret != NULL); } } return ret; } // Fast-path acquire tas lock #define DYNA_ACQUIRE_TAS_LOCK(lock, gtid) { \ kmp_tas_lock_t *l = (kmp_tas_lock_t *)lock; \ if (l->lk.poll != DYNA_LOCK_FREE(tas) || \ ! KMP_COMPARE_AND_STORE_ACQ32(&(l->lk.poll), DYNA_LOCK_FREE(tas), DYNA_LOCK_BUSY(gtid+1, tas))) { \ kmp_uint32 spins; \ KMP_FSYNC_PREPARE(l); \ KMP_INIT_YIELD(spins); \ if (TCR_4(__kmp_nth) > (__kmp_avail_proc ? __kmp_avail_proc : __kmp_xproc)) { \ KMP_YIELD(TRUE); \ } else { \ KMP_YIELD_SPIN(spins); \ } \ while (l->lk.poll != DYNA_LOCK_FREE(tas) || \ ! KMP_COMPARE_AND_STORE_ACQ32(&(l->lk.poll), DYNA_LOCK_FREE(tas), DYNA_LOCK_BUSY(gtid+1, tas))) { \ if (TCR_4(__kmp_nth) > (__kmp_avail_proc ? __kmp_avail_proc : __kmp_xproc)) { \ KMP_YIELD(TRUE); \ } else { \ KMP_YIELD_SPIN(spins); \ } \ } \ } \ KMP_FSYNC_ACQUIRED(l); \ } // Fast-path test tas lock #define DYNA_TEST_TAS_LOCK(lock, gtid, rc) { \ kmp_tas_lock_t *l = (kmp_tas_lock_t *)lock; \ rc = l->lk.poll == DYNA_LOCK_FREE(tas) && \ KMP_COMPARE_AND_STORE_ACQ32(&(l->lk.poll), DYNA_LOCK_FREE(tas), DYNA_LOCK_BUSY(gtid+1, tas)); \ } // Fast-path release tas lock #define DYNA_RELEASE_TAS_LOCK(lock, gtid) { \ TCW_4(((kmp_tas_lock_t *)lock)->lk.poll, DYNA_LOCK_FREE(tas)); \ KMP_MB(); \ } #if DYNA_HAS_FUTEX # include <unistd.h> # include <sys/syscall.h> # ifndef FUTEX_WAIT # define FUTEX_WAIT 0 # endif # ifndef FUTEX_WAKE # define FUTEX_WAKE 1 # endif // Fast-path acquire futex lock #define DYNA_ACQUIRE_FUTEX_LOCK(lock, gtid) { \ kmp_futex_lock_t *ftx = (kmp_futex_lock_t *)lock; \ kmp_int32 gtid_code = (gtid+1) << 1; \ KMP_MB(); \ KMP_FSYNC_PREPARE(ftx); \ kmp_int32 poll_val; \ while ((poll_val = KMP_COMPARE_AND_STORE_RET32(&(ftx->lk.poll), DYNA_LOCK_FREE(futex), \ DYNA_LOCK_BUSY(gtid_code, futex))) != DYNA_LOCK_FREE(futex)) { \ kmp_int32 cond = DYNA_LOCK_STRIP(poll_val) & 1; \ if (!cond) { \ if (!KMP_COMPARE_AND_STORE_RET32(&(ftx->lk.poll), poll_val, poll_val | DYNA_LOCK_BUSY(1, futex))) { \ continue; \ } \ poll_val |= DYNA_LOCK_BUSY(1, futex); \ } \ kmp_int32 rc; \ if ((rc = syscall(__NR_futex, &(ftx->lk.poll), FUTEX_WAIT, poll_val, NULL, NULL, 0)) != 0) { \ continue; \ } \ gtid_code |= 1; \ } \ KMP_FSYNC_ACQUIRED(ftx); \ } // Fast-path test futex lock #define DYNA_TEST_FUTEX_LOCK(lock, gtid, rc) { \ kmp_futex_lock_t *ftx = (kmp_futex_lock_t *)lock; \ if (KMP_COMPARE_AND_STORE_ACQ32(&(ftx->lk.poll), DYNA_LOCK_FREE(futex), DYNA_LOCK_BUSY(gtid+1, futex) << 1)) { \ KMP_FSYNC_ACQUIRED(ftx); \ rc = TRUE; \ } else { \ rc = FALSE; \ } \ } // Fast-path release futex lock #define DYNA_RELEASE_FUTEX_LOCK(lock, gtid) { \ kmp_futex_lock_t *ftx = (kmp_futex_lock_t *)lock; \ KMP_MB(); \ KMP_FSYNC_RELEASING(ftx); \ kmp_int32 poll_val = KMP_XCHG_FIXED32(&(ftx->lk.poll), DYNA_LOCK_FREE(futex)); \ if (DYNA_LOCK_STRIP(poll_val) & 1) { \ syscall(__NR_futex, &(ftx->lk.poll), FUTEX_WAKE, DYNA_LOCK_BUSY(1, futex), NULL, NULL, 0); \ } \ KMP_MB(); \ KMP_YIELD(TCR_4(__kmp_nth) > (__kmp_avail_proc ? __kmp_avail_proc : __kmp_xproc)); \ } #endif // DYNA_HAS_FUTEX #else // KMP_USE_DYNAMIC_LOCK static kmp_user_lock_p __kmp_get_critical_section_ptr( kmp_critical_name * crit, ident_t const * loc, kmp_int32 gtid ) { kmp_user_lock_p *lck_pp = (kmp_user_lock_p *)crit; // // Because of the double-check, the following load // doesn't need to be volatile. // kmp_user_lock_p lck = (kmp_user_lock_p)TCR_PTR( *lck_pp ); if ( lck == NULL ) { void * idx; // Allocate & initialize the lock. // Remember allocated locks in table in order to free them in __kmp_cleanup() lck = __kmp_user_lock_allocate( &idx, gtid, kmp_lf_critical_section ); __kmp_init_user_lock_with_checks( lck ); __kmp_set_user_lock_location( lck, loc ); #if USE_ITT_BUILD __kmp_itt_critical_creating( lck ); // __kmp_itt_critical_creating() should be called *before* the first usage of underlying // lock. It is the only place where we can guarantee it. There are chances the lock will // destroyed with no usage, but it is not a problem, because this is not real event seen // by user but rather setting name for object (lock). See more details in kmp_itt.h. #endif /* USE_ITT_BUILD */ // // Use a cmpxchg instruction to slam the start of the critical // section with the lock pointer. If another thread beat us // to it, deallocate the lock, and use the lock that the other // thread allocated. // int status = KMP_COMPARE_AND_STORE_PTR( lck_pp, 0, lck ); if ( status == 0 ) { // Deallocate the lock and reload the value. #if USE_ITT_BUILD __kmp_itt_critical_destroyed( lck ); // Let ITT know the lock is destroyed and the same memory location may be reused for // another purpose. #endif /* USE_ITT_BUILD */ __kmp_destroy_user_lock_with_checks( lck ); __kmp_user_lock_free( &idx, gtid, lck ); lck = (kmp_user_lock_p)TCR_PTR( *lck_pp ); KMP_DEBUG_ASSERT( lck != NULL ); } } return lck; } #endif // KMP_USE_DYNAMIC_LOCK /*! @ingroup WORK_SHARING @param loc source location information. @param global_tid global thread number . @param crit identity of the critical section. This could be a pointer to a lock associated with the critical section, or some other suitably unique value. Enter code protected by a `critical` construct. This function blocks until the executing thread can enter the critical section. */ void __kmpc_critical( ident_t * loc, kmp_int32 global_tid, kmp_critical_name * crit ) { KMP_COUNT_BLOCK(OMP_CRITICAL); kmp_user_lock_p lck; KC_TRACE( 10, ("__kmpc_critical: called T#%d\n", global_tid ) ); #if KMP_USE_DYNAMIC_LOCK // Assumption: all direct locks fit in OMP_CRITICAL_SIZE. // The global sequence __kmp_user_lock_seq is used unless compiler pushes a value. if (DYNA_IS_D_LOCK(__kmp_user_lock_seq)) { lck = (kmp_user_lock_p)crit; // The thread that reaches here first needs to tag the lock word. if (*((kmp_dyna_lock_t *)lck) == 0) { KMP_COMPARE_AND_STORE_ACQ32((volatile kmp_int32 *)lck, 0, DYNA_GET_D_TAG(__kmp_user_lock_seq)); } if (__kmp_env_consistency_check) { __kmp_push_sync(global_tid, ct_critical, loc, lck, __kmp_user_lock_seq); } # if USE_ITT_BUILD __kmp_itt_critical_acquiring(lck); # endif # if DYNA_USE_FAST_TAS if (__kmp_user_lock_seq == lockseq_tas && !__kmp_env_consistency_check) { DYNA_ACQUIRE_TAS_LOCK(lck, global_tid); } else # elif DYNA_USE_FAST_FUTEX if (__kmp_user_lock_seq == lockseq_futex && !__kmp_env_consistency_check) { DYNA_ACQUIRE_FUTEX_LOCK(lck, global_tid); } else # endif { DYNA_D_LOCK_FUNC(lck, set)((kmp_dyna_lock_t *)lck, global_tid); } } else { kmp_indirect_lock_t *ilk = __kmp_get_indirect_csptr(crit, loc, global_tid, __kmp_user_lock_seq); lck = ilk->lock; if (__kmp_env_consistency_check) { __kmp_push_sync(global_tid, ct_critical, loc, lck, __kmp_user_lock_seq); } # if USE_ITT_BUILD __kmp_itt_critical_acquiring(lck); # endif DYNA_I_LOCK_FUNC(ilk, set)(lck, global_tid); } #else // KMP_USE_DYNAMIC_LOCK //TODO: add THR_OVHD_STATE KMP_CHECK_USER_LOCK_INIT(); if ( ( __kmp_user_lock_kind == lk_tas ) && ( sizeof( lck->tas.lk.poll ) <= OMP_CRITICAL_SIZE ) ) { lck = (kmp_user_lock_p)crit; } #if KMP_OS_LINUX && (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) else if ( ( __kmp_user_lock_kind == lk_futex ) && ( sizeof( lck->futex.lk.poll ) <= OMP_CRITICAL_SIZE ) ) { lck = (kmp_user_lock_p)crit; } #endif else { // ticket, queuing or drdpa lck = __kmp_get_critical_section_ptr( crit, loc, global_tid ); } if ( __kmp_env_consistency_check ) __kmp_push_sync( global_tid, ct_critical, loc, lck ); /* since the critical directive binds to all threads, not just * the current team we have to check this even if we are in a * serialized team */ /* also, even if we are the uber thread, we still have to conduct the lock, * as we have to contend with sibling threads */ #if USE_ITT_BUILD __kmp_itt_critical_acquiring( lck ); #endif /* USE_ITT_BUILD */ // Value of 'crit' should be good for using as a critical_id of the critical section directive. __kmp_acquire_user_lock_with_checks( lck, global_tid ); #endif // KMP_USE_DYNAMIC_LOCK #if USE_ITT_BUILD __kmp_itt_critical_acquired( lck ); #endif /* USE_ITT_BUILD */ KA_TRACE( 15, ("__kmpc_critical: done T#%d\n", global_tid )); } // __kmpc_critical /*! @ingroup WORK_SHARING @param loc source location information. @param global_tid global thread number . @param crit identity of the critical section. This could be a pointer to a lock associated with the critical section, or some other suitably unique value. Leave a critical section, releasing any lock that was held during its execution. */ void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid, kmp_critical_name *crit) { kmp_user_lock_p lck; KC_TRACE( 10, ("__kmpc_end_critical: called T#%d\n", global_tid )); #if KMP_USE_DYNAMIC_LOCK if (DYNA_IS_D_LOCK(__kmp_user_lock_seq)) { lck = (kmp_user_lock_p)crit; KMP_ASSERT(lck != NULL); if (__kmp_env_consistency_check) { __kmp_pop_sync(global_tid, ct_critical, loc); } # if USE_ITT_BUILD __kmp_itt_critical_releasing( lck ); # endif # if DYNA_USE_FAST_TAS if (__kmp_user_lock_seq == lockseq_tas && !__kmp_env_consistency_check) { DYNA_RELEASE_TAS_LOCK(lck, global_tid); } else # elif DYNA_USE_FAST_FUTEX if (__kmp_user_lock_seq == lockseq_futex && !__kmp_env_consistency_check) { DYNA_RELEASE_FUTEX_LOCK(lck, global_tid); } else # endif { DYNA_D_LOCK_FUNC(lck, unset)((kmp_dyna_lock_t *)lck, global_tid); } } else { kmp_indirect_lock_t *ilk = (kmp_indirect_lock_t *)TCR_PTR(*((kmp_indirect_lock_t **)crit)); KMP_ASSERT(ilk != NULL); lck = ilk->lock; if (__kmp_env_consistency_check) { __kmp_pop_sync(global_tid, ct_critical, loc); } # if USE_ITT_BUILD __kmp_itt_critical_releasing( lck ); # endif DYNA_I_LOCK_FUNC(ilk, unset)(lck, global_tid); } #else // KMP_USE_DYNAMIC_LOCK if ( ( __kmp_user_lock_kind == lk_tas ) && ( sizeof( lck->tas.lk.poll ) <= OMP_CRITICAL_SIZE ) ) { lck = (kmp_user_lock_p)crit; } #if KMP_OS_LINUX && (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) else if ( ( __kmp_user_lock_kind == lk_futex ) && ( sizeof( lck->futex.lk.poll ) <= OMP_CRITICAL_SIZE ) ) { lck = (kmp_user_lock_p)crit; } #endif else { // ticket, queuing or drdpa lck = (kmp_user_lock_p) TCR_PTR(*((kmp_user_lock_p *)crit)); } KMP_ASSERT(lck != NULL); if ( __kmp_env_consistency_check ) __kmp_pop_sync( global_tid, ct_critical, loc ); #if USE_ITT_BUILD __kmp_itt_critical_releasing( lck ); #endif /* USE_ITT_BUILD */ // Value of 'crit' should be good for using as a critical_id of the critical section directive. __kmp_release_user_lock_with_checks( lck, global_tid ); #if OMPT_SUPPORT && OMPT_BLAME if ((ompt_status == ompt_status_track_callback) && ompt_callbacks.ompt_callback(ompt_event_release_critical)) { ompt_callbacks.ompt_callback(ompt_event_release_critical)( (uint64_t) lck); } #endif #endif // KMP_USE_DYNAMIC_LOCK KA_TRACE( 15, ("__kmpc_end_critical: done T#%d\n", global_tid )); } /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid thread id. @return one if the thread should execute the master block, zero otherwise Start execution of a combined barrier and master. The barrier is executed inside this function. */ kmp_int32 __kmpc_barrier_master(ident_t *loc, kmp_int32 global_tid) { int status; KC_TRACE( 10, ("__kmpc_barrier_master: called T#%d\n", global_tid ) ); if (! TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); if ( __kmp_env_consistency_check ) __kmp_check_barrier( global_tid, ct_barrier, loc ); #if USE_ITT_NOTIFY __kmp_threads[global_tid]->th.th_ident = loc; #endif status = __kmp_barrier( bs_plain_barrier, global_tid, TRUE, 0, NULL, NULL ); return (status != 0) ? 0 : 1; } /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid thread id. Complete the execution of a combined barrier and master. This function should only be called at the completion of the <tt>master</tt> code. Other threads will still be waiting at the barrier and this call releases them. */ void __kmpc_end_barrier_master(ident_t *loc, kmp_int32 global_tid) { KC_TRACE( 10, ("__kmpc_end_barrier_master: called T#%d\n", global_tid )); __kmp_end_split_barrier ( bs_plain_barrier, global_tid ); } /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid thread id. @return one if the thread should execute the master block, zero otherwise Start execution of a combined barrier and master(nowait) construct. The barrier is executed inside this function. There is no equivalent "end" function, since the */ kmp_int32 __kmpc_barrier_master_nowait( ident_t * loc, kmp_int32 global_tid ) { kmp_int32 ret; KC_TRACE( 10, ("__kmpc_barrier_master_nowait: called T#%d\n", global_tid )); if (! TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); if ( __kmp_env_consistency_check ) { if ( loc == 0 ) { KMP_WARNING( ConstructIdentInvalid ); // ??? What does it mean for the user? } __kmp_check_barrier( global_tid, ct_barrier, loc ); } #if USE_ITT_NOTIFY __kmp_threads[global_tid]->th.th_ident = loc; #endif __kmp_barrier( bs_plain_barrier, global_tid, FALSE, 0, NULL, NULL ); ret = __kmpc_master (loc, global_tid); if ( __kmp_env_consistency_check ) { /* there's no __kmpc_end_master called; so the (stats) */ /* actions of __kmpc_end_master are done here */ if ( global_tid < 0 ) { KMP_WARNING( ThreadIdentInvalid ); } if (ret) { /* only one thread should do the pop since only */ /* one did the push (see __kmpc_master()) */ __kmp_pop_sync( global_tid, ct_master, loc ); } } return (ret); } /* The BARRIER for a SINGLE process section is always explicit */ /*! @ingroup WORK_SHARING @param loc source location information @param global_tid global thread number @return One if this thread should execute the single construct, zero otherwise. Test whether to execute a <tt>single</tt> construct. There are no implicit barriers in the two "single" calls, rather the compiler should introduce an explicit barrier if it is required. */ kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid) { KMP_COUNT_BLOCK(OMP_SINGLE); kmp_int32 rc = __kmp_enter_single( global_tid, loc, TRUE ); #if OMPT_SUPPORT && OMPT_TRACE kmp_info_t *this_thr = __kmp_threads[ global_tid ]; kmp_team_t *team = this_thr -> th.th_team; int tid = __kmp_tid_from_gtid( global_tid ); if ((ompt_status == ompt_status_track_callback)) { if (rc) { if (ompt_callbacks.ompt_callback(ompt_event_single_in_block_begin)) { ompt_callbacks.ompt_callback(ompt_event_single_in_block_begin)( team->t.ompt_team_info.parallel_id, team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_id, team->t.ompt_team_info.microtask); } } else { if (ompt_callbacks.ompt_callback(ompt_event_single_others_begin)) { ompt_callbacks.ompt_callback(ompt_event_single_others_begin)( team->t.ompt_team_info.parallel_id, team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_id); } this_thr->th.ompt_thread_info.state = ompt_state_wait_single; } } #endif return rc; } /*! @ingroup WORK_SHARING @param loc source location information @param global_tid global thread number Mark the end of a <tt>single</tt> construct. This function should only be called by the thread that executed the block of code protected by the `single` construct. */ void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid) { __kmp_exit_single( global_tid ); #if OMPT_SUPPORT && OMPT_TRACE kmp_info_t *this_thr = __kmp_threads[ global_tid ]; kmp_team_t *team = this_thr -> th.th_team; int tid = __kmp_tid_from_gtid( global_tid ); if ((ompt_status == ompt_status_track_callback) && ompt_callbacks.ompt_callback(ompt_event_single_in_block_end)) { ompt_callbacks.ompt_callback(ompt_event_single_in_block_end)( team->t.ompt_team_info.parallel_id, team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_id); } #endif } /*! @ingroup WORK_SHARING @param loc Source location @param global_tid Global thread id Mark the end of a statically scheduled loop. */ void __kmpc_for_static_fini( ident_t *loc, kmp_int32 global_tid ) { KE_TRACE( 10, ("__kmpc_for_static_fini called T#%d\n", global_tid)); #if OMPT_SUPPORT && OMPT_TRACE kmp_info_t *this_thr = __kmp_threads[ global_tid ]; kmp_team_t *team = this_thr -> th.th_team; int tid = __kmp_tid_from_gtid( global_tid ); if ((ompt_status == ompt_status_track_callback) && ompt_callbacks.ompt_callback(ompt_event_loop_end)) { ompt_callbacks.ompt_callback(ompt_event_loop_end)( team->t.ompt_team_info.parallel_id, team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_id); } #endif if ( __kmp_env_consistency_check ) __kmp_pop_workshare( global_tid, ct_pdo, loc ); } /* * User routines which take C-style arguments (call by value) * different from the Fortran equivalent routines */ void ompc_set_num_threads( int arg ) { // !!!!! TODO: check the per-task binding __kmp_set_num_threads( arg, __kmp_entry_gtid() ); } void ompc_set_dynamic( int flag ) { kmp_info_t *thread; /* For the thread-private implementation of the internal controls */ thread = __kmp_entry_thread(); __kmp_save_internal_controls( thread ); set__dynamic( thread, flag ? TRUE : FALSE ); } void ompc_set_nested( int flag ) { kmp_info_t *thread; /* For the thread-private internal controls implementation */ thread = __kmp_entry_thread(); __kmp_save_internal_controls( thread ); set__nested( thread, flag ? TRUE : FALSE ); } void ompc_set_max_active_levels( int max_active_levels ) { /* TO DO */ /* we want per-task implementation of this internal control */ /* For the per-thread internal controls implementation */ __kmp_set_max_active_levels( __kmp_entry_gtid(), max_active_levels ); } void ompc_set_schedule( omp_sched_t kind, int modifier ) { // !!!!! TODO: check the per-task binding __kmp_set_schedule( __kmp_entry_gtid(), ( kmp_sched_t ) kind, modifier ); } int ompc_get_ancestor_thread_num( int level ) { return __kmp_get_ancestor_thread_num( __kmp_entry_gtid(), level ); } int ompc_get_team_size( int level ) { return __kmp_get_team_size( __kmp_entry_gtid(), level ); } void kmpc_set_stacksize( int arg ) { // __kmp_aux_set_stacksize initializes the library if needed __kmp_aux_set_stacksize( arg ); } void kmpc_set_stacksize_s( size_t arg ) { // __kmp_aux_set_stacksize initializes the library if needed __kmp_aux_set_stacksize( arg ); } void kmpc_set_blocktime( int arg ) { int gtid, tid; kmp_info_t *thread; gtid = __kmp_entry_gtid(); tid = __kmp_tid_from_gtid(gtid); thread = __kmp_thread_from_gtid(gtid); __kmp_aux_set_blocktime( arg, thread, tid ); } void kmpc_set_library( int arg ) { // __kmp_user_set_library initializes the library if needed __kmp_user_set_library( (enum library_type)arg ); } void kmpc_set_defaults( char const * str ) { // __kmp_aux_set_defaults initializes the library if needed __kmp_aux_set_defaults( str, KMP_STRLEN( str ) ); } int kmpc_set_affinity_mask_proc( int proc, void **mask ) { #if defined(KMP_STUB) || !KMP_AFFINITY_SUPPORTED return -1; #else if ( ! TCR_4(__kmp_init_middle) ) { __kmp_middle_initialize(); } return __kmp_aux_set_affinity_mask_proc( proc, mask ); #endif } int kmpc_unset_affinity_mask_proc( int proc, void **mask ) { #if defined(KMP_STUB) || !KMP_AFFINITY_SUPPORTED return -1; #else if ( ! TCR_4(__kmp_init_middle) ) { __kmp_middle_initialize(); } return __kmp_aux_unset_affinity_mask_proc( proc, mask ); #endif } int kmpc_get_affinity_mask_proc( int proc, void **mask ) { #if defined(KMP_STUB) || !KMP_AFFINITY_SUPPORTED return -1; #else if ( ! TCR_4(__kmp_init_middle) ) { __kmp_middle_initialize(); } return __kmp_aux_get_affinity_mask_proc( proc, mask ); #endif } /* -------------------------------------------------------------------------- */ /*! @ingroup THREADPRIVATE @param loc source location information @param gtid global thread number @param cpy_size size of the cpy_data buffer @param cpy_data pointer to data to be copied @param cpy_func helper function to call for copying data @param didit flag variable: 1=single thread; 0=not single thread __kmpc_copyprivate implements the interface for the private data broadcast needed for the copyprivate clause associated with a single region in an OpenMP<sup>*</sup> program (both C and Fortran). All threads participating in the parallel region call this routine. One of the threads (called the single thread) should have the <tt>didit</tt> variable set to 1 and all other threads should have that variable set to 0. All threads pass a pointer to a data buffer (cpy_data) that they have built. The OpenMP specification forbids the use of nowait on the single region when a copyprivate clause is present. However, @ref __kmpc_copyprivate implements a barrier internally to avoid race conditions, so the code generation for the single region should avoid generating a barrier after the call to @ref __kmpc_copyprivate. The <tt>gtid</tt> parameter is the global thread id for the current thread. The <tt>loc</tt> parameter is a pointer to source location information. Internal implementation: The single thread will first copy its descriptor address (cpy_data) to a team-private location, then the other threads will each call the function pointed to by the parameter cpy_func, which carries out the copy by copying the data using the cpy_data buffer. The cpy_func routine used for the copy and the contents of the data area defined by cpy_data and cpy_size may be built in any fashion that will allow the copy to be done. For instance, the cpy_data buffer can hold the actual data to be copied or it may hold a list of pointers to the data. The cpy_func routine must interpret the cpy_data buffer appropriately. The interface to cpy_func is as follows: @code void cpy_func( void *destination, void *source ) @endcode where void *destination is the cpy_data pointer for the thread being copied to and void *source is the cpy_data pointer for the thread being copied from. */ void __kmpc_copyprivate( ident_t *loc, kmp_int32 gtid, size_t cpy_size, void *cpy_data, void(*cpy_func)(void*,void*), kmp_int32 didit ) { void **data_ptr; KC_TRACE( 10, ("__kmpc_copyprivate: called T#%d\n", gtid )); KMP_MB(); data_ptr = & __kmp_team_from_gtid( gtid )->t.t_copypriv_data; if ( __kmp_env_consistency_check ) { if ( loc == 0 ) { KMP_WARNING( ConstructIdentInvalid ); } } /* ToDo: Optimize the following two barriers into some kind of split barrier */ if (didit) *data_ptr = cpy_data; /* This barrier is not a barrier region boundary */ #if USE_ITT_NOTIFY __kmp_threads[gtid]->th.th_ident = loc; #endif __kmp_barrier( bs_plain_barrier, gtid, FALSE , 0, NULL, NULL ); if (! didit) (*cpy_func)( cpy_data, *data_ptr ); /* Consider next barrier the user-visible barrier for barrier region boundaries */ /* Nesting checks are already handled by the single construct checks */ #if USE_ITT_NOTIFY __kmp_threads[gtid]->th.th_ident = loc; // TODO: check if it is needed (e.g. tasks can overwrite the location) #endif __kmp_barrier( bs_plain_barrier, gtid, FALSE , 0, NULL, NULL ); } /* -------------------------------------------------------------------------- */ #define INIT_LOCK __kmp_init_user_lock_with_checks #define INIT_NESTED_LOCK __kmp_init_nested_user_lock_with_checks #define ACQUIRE_LOCK __kmp_acquire_user_lock_with_checks #define ACQUIRE_LOCK_TIMED __kmp_acquire_user_lock_with_checks_timed #define ACQUIRE_NESTED_LOCK __kmp_acquire_nested_user_lock_with_checks #define ACQUIRE_NESTED_LOCK_TIMED __kmp_acquire_nested_user_lock_with_checks_timed #define RELEASE_LOCK __kmp_release_user_lock_with_checks #define RELEASE_NESTED_LOCK __kmp_release_nested_user_lock_with_checks #define TEST_LOCK __kmp_test_user_lock_with_checks #define TEST_NESTED_LOCK __kmp_test_nested_user_lock_with_checks #define DESTROY_LOCK __kmp_destroy_user_lock_with_checks #define DESTROY_NESTED_LOCK __kmp_destroy_nested_user_lock_with_checks /* * TODO: Make check abort messages use location info & pass it * into with_checks routines */ /* initialize the lock */ void __kmpc_init_lock( ident_t * loc, kmp_int32 gtid, void ** user_lock ) { #if KMP_USE_DYNAMIC_LOCK KMP_DEBUG_ASSERT(__kmp_init_serial); if (__kmp_env_consistency_check && user_lock == NULL) { KMP_FATAL(LockIsUninitialized, "omp_init_lock"); } if (DYNA_IS_D_LOCK(__kmp_user_lock_seq)) { DYNA_INIT_D_LOCK(user_lock, __kmp_user_lock_seq); # if USE_ITT_BUILD __kmp_itt_lock_creating((kmp_user_lock_p)user_lock, NULL); # endif } else { DYNA_INIT_I_LOCK(user_lock, __kmp_user_lock_seq); kmp_indirect_lock_t *ilk = DYNA_LOOKUP_I_LOCK(user_lock); DYNA_SET_I_LOCK_LOCATION(ilk, loc); # if USE_ITT_BUILD __kmp_itt_lock_creating(ilk->lock, loc); # endif } #else // KMP_USE_DYNAMIC_LOCK static char const * const func = "omp_init_lock"; kmp_user_lock_p lck; KMP_DEBUG_ASSERT( __kmp_init_serial ); if ( __kmp_env_consistency_check ) { if ( user_lock == NULL ) { KMP_FATAL( LockIsUninitialized, func ); } } KMP_CHECK_USER_LOCK_INIT(); if ( ( __kmp_user_lock_kind == lk_tas ) && ( sizeof( lck->tas.lk.poll ) <= OMP_LOCK_T_SIZE ) ) { lck = (kmp_user_lock_p)user_lock; } #if KMP_OS_LINUX && (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) else if ( ( __kmp_user_lock_kind == lk_futex ) && ( sizeof( lck->futex.lk.poll ) <= OMP_LOCK_T_SIZE ) ) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_user_lock_allocate( user_lock, gtid, 0 ); } INIT_LOCK( lck ); __kmp_set_user_lock_location( lck, loc ); #if USE_ITT_BUILD __kmp_itt_lock_creating( lck ); #endif /* USE_ITT_BUILD */ #endif // KMP_USE_DYNAMIC_LOCK } // __kmpc_init_lock /* initialize the lock */ void __kmpc_init_nest_lock( ident_t * loc, kmp_int32 gtid, void ** user_lock ) { #if KMP_USE_DYNAMIC_LOCK KMP_DEBUG_ASSERT(__kmp_init_serial); if (__kmp_env_consistency_check && user_lock == NULL) { KMP_FATAL(LockIsUninitialized, "omp_init_nest_lock"); } // Invoke init function after converting to nested version. kmp_dyna_lockseq_t nested_seq; switch (__kmp_user_lock_seq) { case lockseq_tas: nested_seq = lockseq_nested_tas; break; #if DYNA_HAS_FUTEX case lockseq_futex: nested_seq = lockseq_nested_futex; break; #endif case lockseq_ticket: nested_seq = lockseq_nested_ticket; break; case lockseq_queuing: nested_seq = lockseq_nested_queuing; break; case lockseq_drdpa: nested_seq = lockseq_nested_drdpa; break; default: nested_seq = lockseq_nested_queuing; break; // Use nested queuing lock for lock kinds without "nested" implementation. } DYNA_INIT_I_LOCK(user_lock, nested_seq); // All nested locks are indirect locks. kmp_indirect_lock_t *ilk = DYNA_LOOKUP_I_LOCK(user_lock); DYNA_SET_I_LOCK_LOCATION(ilk, loc); # if USE_ITT_BUILD __kmp_itt_lock_creating(ilk->lock, loc); # endif #else // KMP_USE_DYNAMIC_LOCK static char const * const func = "omp_init_nest_lock"; kmp_user_lock_p lck; KMP_DEBUG_ASSERT( __kmp_init_serial ); if ( __kmp_env_consistency_check ) { if ( user_lock == NULL ) { KMP_FATAL( LockIsUninitialized, func ); } } KMP_CHECK_USER_LOCK_INIT(); if ( ( __kmp_user_lock_kind == lk_tas ) && ( sizeof( lck->tas.lk.poll ) + sizeof( lck->tas.lk.depth_locked ) <= OMP_NEST_LOCK_T_SIZE ) ) { lck = (kmp_user_lock_p)user_lock; } #if KMP_OS_LINUX && (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) else if ( ( __kmp_user_lock_kind == lk_futex ) && ( sizeof( lck->futex.lk.poll ) + sizeof( lck->futex.lk.depth_locked ) <= OMP_NEST_LOCK_T_SIZE ) ) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_user_lock_allocate( user_lock, gtid, 0 ); } INIT_NESTED_LOCK( lck ); __kmp_set_user_lock_location( lck, loc ); #if USE_ITT_BUILD __kmp_itt_lock_creating( lck ); #endif /* USE_ITT_BUILD */ #endif // KMP_USE_DYNAMIC_LOCK } // __kmpc_init_nest_lock void __kmpc_destroy_lock( ident_t * loc, kmp_int32 gtid, void ** user_lock ) { #if KMP_USE_DYNAMIC_LOCK # if USE_ITT_BUILD kmp_user_lock_p lck; if (DYNA_EXTRACT_D_TAG(user_lock) == 0) { lck = ((kmp_indirect_lock_t *)DYNA_LOOKUP_I_LOCK(user_lock))->lock; } else { lck = (kmp_user_lock_p)user_lock; } __kmp_itt_lock_destroyed(lck); # endif DYNA_D_LOCK_FUNC(user_lock, destroy)((kmp_dyna_lock_t *)user_lock); #else kmp_user_lock_p lck; if ( ( __kmp_user_lock_kind == lk_tas ) && ( sizeof( lck->tas.lk.poll ) <= OMP_LOCK_T_SIZE ) ) { lck = (kmp_user_lock_p)user_lock; } #if KMP_OS_LINUX && (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) else if ( ( __kmp_user_lock_kind == lk_futex ) && ( sizeof( lck->futex.lk.poll ) <= OMP_LOCK_T_SIZE ) ) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock( user_lock, "omp_destroy_lock" ); } #if USE_ITT_BUILD __kmp_itt_lock_destroyed( lck ); #endif /* USE_ITT_BUILD */ DESTROY_LOCK( lck ); if ( ( __kmp_user_lock_kind == lk_tas ) && ( sizeof( lck->tas.lk.poll ) <= OMP_LOCK_T_SIZE ) ) { ; } #if KMP_OS_LINUX && (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) else if ( ( __kmp_user_lock_kind == lk_futex ) && ( sizeof( lck->futex.lk.poll ) <= OMP_LOCK_T_SIZE ) ) { ; } #endif else { __kmp_user_lock_free( user_lock, gtid, lck ); } #endif // KMP_USE_DYNAMIC_LOCK } // __kmpc_destroy_lock /* destroy the lock */ void __kmpc_destroy_nest_lock( ident_t * loc, kmp_int32 gtid, void ** user_lock ) { #if KMP_USE_DYNAMIC_LOCK # if USE_ITT_BUILD kmp_indirect_lock_t *ilk = DYNA_LOOKUP_I_LOCK(user_lock); __kmp_itt_lock_destroyed(ilk->lock); # endif DYNA_D_LOCK_FUNC(user_lock, destroy)((kmp_dyna_lock_t *)user_lock); #else // KMP_USE_DYNAMIC_LOCK kmp_user_lock_p lck; if ( ( __kmp_user_lock_kind == lk_tas ) && ( sizeof( lck->tas.lk.poll ) + sizeof( lck->tas.lk.depth_locked ) <= OMP_NEST_LOCK_T_SIZE ) ) { lck = (kmp_user_lock_p)user_lock; } #if KMP_OS_LINUX && (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) else if ( ( __kmp_user_lock_kind == lk_futex ) && ( sizeof( lck->futex.lk.poll ) + sizeof( lck->futex.lk.depth_locked ) <= OMP_NEST_LOCK_T_SIZE ) ) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock( user_lock, "omp_destroy_nest_lock" ); } #if USE_ITT_BUILD __kmp_itt_lock_destroyed( lck ); #endif /* USE_ITT_BUILD */ DESTROY_NESTED_LOCK( lck ); if ( ( __kmp_user_lock_kind == lk_tas ) && ( sizeof( lck->tas.lk.poll ) + sizeof( lck->tas.lk.depth_locked ) <= OMP_NEST_LOCK_T_SIZE ) ) { ; } #if KMP_OS_LINUX && (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) else if ( ( __kmp_user_lock_kind == lk_futex ) && ( sizeof( lck->futex.lk.poll ) + sizeof( lck->futex.lk.depth_locked ) <= OMP_NEST_LOCK_T_SIZE ) ) { ; } #endif else { __kmp_user_lock_free( user_lock, gtid, lck ); } #endif // KMP_USE_DYNAMIC_LOCK } // __kmpc_destroy_nest_lock void __kmpc_set_lock( ident_t * loc, kmp_int32 gtid, void ** user_lock ) { KMP_COUNT_BLOCK(OMP_set_lock); #if KMP_USE_DYNAMIC_LOCK int tag = DYNA_EXTRACT_D_TAG(user_lock); # if USE_ITT_BUILD __kmp_itt_lock_acquiring((kmp_user_lock_p)user_lock); // itt function will get to the right lock object. # endif # if DYNA_USE_FAST_TAS if (tag == locktag_tas && !__kmp_env_consistency_check) { DYNA_ACQUIRE_TAS_LOCK(user_lock, gtid); } else # elif DYNA_USE_FAST_FUTEX if (tag == locktag_futex && !__kmp_env_consistency_check) { DYNA_ACQUIRE_FUTEX_LOCK(user_lock, gtid); } else # endif { __kmp_direct_set_ops[tag]((kmp_dyna_lock_t *)user_lock, gtid); } # if USE_ITT_BUILD __kmp_itt_lock_acquired((kmp_user_lock_p)user_lock); # endif #else // KMP_USE_DYNAMIC_LOCK kmp_user_lock_p lck; if ( ( __kmp_user_lock_kind == lk_tas ) && ( sizeof( lck->tas.lk.poll ) <= OMP_LOCK_T_SIZE ) ) { lck = (kmp_user_lock_p)user_lock; } #if KMP_OS_LINUX && (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) else if ( ( __kmp_user_lock_kind == lk_futex ) && ( sizeof( lck->futex.lk.poll ) <= OMP_LOCK_T_SIZE ) ) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock( user_lock, "omp_set_lock" ); } #if USE_ITT_BUILD __kmp_itt_lock_acquiring( lck ); #endif /* USE_ITT_BUILD */ ACQUIRE_LOCK( lck, gtid ); #if USE_ITT_BUILD __kmp_itt_lock_acquired( lck ); #endif /* USE_ITT_BUILD */ #endif // KMP_USE_DYNAMIC_LOCK } void __kmpc_set_nest_lock( ident_t * loc, kmp_int32 gtid, void ** user_lock ) { #if KMP_USE_DYNAMIC_LOCK # if USE_ITT_BUILD __kmp_itt_lock_acquiring((kmp_user_lock_p)user_lock); # endif DYNA_D_LOCK_FUNC(user_lock, set)((kmp_dyna_lock_t *)user_lock, gtid); # if USE_ITT_BUILD __kmp_itt_lock_acquired((kmp_user_lock_p)user_lock); #endif #else // KMP_USE_DYNAMIC_LOCK kmp_user_lock_p lck; if ( ( __kmp_user_lock_kind == lk_tas ) && ( sizeof( lck->tas.lk.poll ) + sizeof( lck->tas.lk.depth_locked ) <= OMP_NEST_LOCK_T_SIZE ) ) { lck = (kmp_user_lock_p)user_lock; } #if KMP_OS_LINUX && (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) else if ( ( __kmp_user_lock_kind == lk_futex ) && ( sizeof( lck->futex.lk.poll ) + sizeof( lck->futex.lk.depth_locked ) <= OMP_NEST_LOCK_T_SIZE ) ) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock( user_lock, "omp_set_nest_lock" ); } #if USE_ITT_BUILD __kmp_itt_lock_acquiring( lck ); #endif /* USE_ITT_BUILD */ ACQUIRE_NESTED_LOCK( lck, gtid ); #if USE_ITT_BUILD __kmp_itt_lock_acquired( lck ); #endif /* USE_ITT_BUILD */ #endif // KMP_USE_DYNAMIC_LOCK } void __kmpc_unset_lock( ident_t *loc, kmp_int32 gtid, void **user_lock ) { #if KMP_USE_DYNAMIC_LOCK int tag = DYNA_EXTRACT_D_TAG(user_lock); # if USE_ITT_BUILD __kmp_itt_lock_releasing((kmp_user_lock_p)user_lock); # endif # if DYNA_USE_FAST_TAS if (tag == locktag_tas && !__kmp_env_consistency_check) { DYNA_RELEASE_TAS_LOCK(user_lock, gtid); } else # elif DYNA_USE_FAST_FUTEX if (tag == locktag_futex && !__kmp_env_consistency_check) { DYNA_RELEASE_FUTEX_LOCK(user_lock, gtid); } else # endif { __kmp_direct_unset_ops[tag]((kmp_dyna_lock_t *)user_lock, gtid); } #else // KMP_USE_DYNAMIC_LOCK kmp_user_lock_p lck; /* Can't use serial interval since not block structured */ /* release the lock */ if ( ( __kmp_user_lock_kind == lk_tas ) && ( sizeof( lck->tas.lk.poll ) <= OMP_LOCK_T_SIZE ) ) { #if KMP_OS_LINUX && (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) // "fast" path implemented to fix customer performance issue #if USE_ITT_BUILD __kmp_itt_lock_releasing( (kmp_user_lock_p)user_lock ); #endif /* USE_ITT_BUILD */ TCW_4(((kmp_user_lock_p)user_lock)->tas.lk.poll, 0); KMP_MB(); return; #else lck = (kmp_user_lock_p)user_lock; #endif } #if KMP_OS_LINUX && (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) else if ( ( __kmp_user_lock_kind == lk_futex ) && ( sizeof( lck->futex.lk.poll ) <= OMP_LOCK_T_SIZE ) ) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock( user_lock, "omp_unset_lock" ); } #if USE_ITT_BUILD __kmp_itt_lock_releasing( lck ); #endif /* USE_ITT_BUILD */ RELEASE_LOCK( lck, gtid ); #if OMPT_SUPPORT && OMPT_BLAME if ((ompt_status == ompt_status_track_callback) && ompt_callbacks.ompt_callback(ompt_event_release_lock)) { ompt_callbacks.ompt_callback(ompt_event_release_lock)((uint64_t) lck); } #endif #endif // KMP_USE_DYNAMIC_LOCK } /* release the lock */ void __kmpc_unset_nest_lock( ident_t *loc, kmp_int32 gtid, void **user_lock ) { #if KMP_USE_DYNAMIC_LOCK # if USE_ITT_BUILD __kmp_itt_lock_releasing((kmp_user_lock_p)user_lock); # endif DYNA_D_LOCK_FUNC(user_lock, unset)((kmp_dyna_lock_t *)user_lock, gtid); #else // KMP_USE_DYNAMIC_LOCK kmp_user_lock_p lck; /* Can't use serial interval since not block structured */ if ( ( __kmp_user_lock_kind == lk_tas ) && ( sizeof( lck->tas.lk.poll ) + sizeof( lck->tas.lk.depth_locked ) <= OMP_NEST_LOCK_T_SIZE ) ) { #if KMP_OS_LINUX && (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) // "fast" path implemented to fix customer performance issue kmp_tas_lock_t *tl = (kmp_tas_lock_t*)user_lock; #if USE_ITT_BUILD __kmp_itt_lock_releasing( (kmp_user_lock_p)user_lock ); #endif /* USE_ITT_BUILD */ if ( --(tl->lk.depth_locked) == 0 ) { TCW_4(tl->lk.poll, 0); } KMP_MB(); return; #else lck = (kmp_user_lock_p)user_lock; #endif } #if KMP_OS_LINUX && (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) else if ( ( __kmp_user_lock_kind == lk_futex ) && ( sizeof( lck->futex.lk.poll ) + sizeof( lck->futex.lk.depth_locked ) <= OMP_NEST_LOCK_T_SIZE ) ) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock( user_lock, "omp_unset_nest_lock" ); } #if USE_ITT_BUILD __kmp_itt_lock_releasing( lck ); #endif /* USE_ITT_BUILD */ int release_status; release_status = RELEASE_NESTED_LOCK( lck, gtid ); #if OMPT_SUPPORT && OMPT_BLAME if (ompt_status == ompt_status_track_callback) { if (release_status == KMP_LOCK_RELEASED) { if (ompt_callbacks.ompt_callback(ompt_event_release_nest_lock_last)) { ompt_callbacks.ompt_callback(ompt_event_release_nest_lock_last)( (uint64_t) lck); } } else if (ompt_callbacks.ompt_callback(ompt_event_release_nest_lock_prev)) { ompt_callbacks.ompt_callback(ompt_event_release_nest_lock_prev)( (uint64_t) lck); } } #endif #endif // KMP_USE_DYNAMIC_LOCK } /* try to acquire the lock */ int __kmpc_test_lock( ident_t *loc, kmp_int32 gtid, void **user_lock ) { KMP_COUNT_BLOCK(OMP_test_lock); KMP_TIME_BLOCK(OMP_test_lock); #if KMP_USE_DYNAMIC_LOCK int rc; int tag = DYNA_EXTRACT_D_TAG(user_lock); # if USE_ITT_BUILD __kmp_itt_lock_acquiring((kmp_user_lock_p)user_lock); # endif # if DYNA_USE_FAST_TAS if (tag == locktag_tas && !__kmp_env_consistency_check) { DYNA_TEST_TAS_LOCK(user_lock, gtid, rc); } else # elif DYNA_USE_FAST_FUTEX if (tag == locktag_futex && !__kmp_env_consistency_check) { DYNA_TEST_FUTEX_LOCK(user_lock, gtid, rc); } else # endif { rc = __kmp_direct_test_ops[tag]((kmp_dyna_lock_t *)user_lock, gtid); } if (rc) { # if USE_ITT_BUILD __kmp_itt_lock_acquired((kmp_user_lock_p)user_lock); # endif return FTN_TRUE; } else { # if USE_ITT_BUILD __kmp_itt_lock_cancelled((kmp_user_lock_p)user_lock); # endif return FTN_FALSE; } #else // KMP_USE_DYNAMIC_LOCK kmp_user_lock_p lck; int rc; if ( ( __kmp_user_lock_kind == lk_tas ) && ( sizeof( lck->tas.lk.poll ) <= OMP_LOCK_T_SIZE ) ) { lck = (kmp_user_lock_p)user_lock; } #if KMP_OS_LINUX && (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) else if ( ( __kmp_user_lock_kind == lk_futex ) && ( sizeof( lck->futex.lk.poll ) <= OMP_LOCK_T_SIZE ) ) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock( user_lock, "omp_test_lock" ); } #if USE_ITT_BUILD __kmp_itt_lock_acquiring( lck ); #endif /* USE_ITT_BUILD */ rc = TEST_LOCK( lck, gtid ); #if USE_ITT_BUILD if ( rc ) { __kmp_itt_lock_acquired( lck ); } else { __kmp_itt_lock_cancelled( lck ); } #endif /* USE_ITT_BUILD */ return ( rc ? FTN_TRUE : FTN_FALSE ); /* Can't use serial interval since not block structured */ #endif // KMP_USE_DYNAMIC_LOCK } /* try to acquire the lock */ int __kmpc_test_nest_lock( ident_t *loc, kmp_int32 gtid, void **user_lock ) { #if KMP_USE_DYNAMIC_LOCK int rc; # if USE_ITT_BUILD __kmp_itt_lock_acquiring((kmp_user_lock_p)user_lock); # endif rc = DYNA_D_LOCK_FUNC(user_lock, test)((kmp_dyna_lock_t *)user_lock, gtid); # if USE_ITT_BUILD if (rc) { __kmp_itt_lock_acquired((kmp_user_lock_p)user_lock); } else { __kmp_itt_lock_cancelled((kmp_user_lock_p)user_lock); } # endif return rc; #else // KMP_USE_DYNAMIC_LOCK kmp_user_lock_p lck; int rc; if ( ( __kmp_user_lock_kind == lk_tas ) && ( sizeof( lck->tas.lk.poll ) + sizeof( lck->tas.lk.depth_locked ) <= OMP_NEST_LOCK_T_SIZE ) ) { lck = (kmp_user_lock_p)user_lock; } #if KMP_OS_LINUX && (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) else if ( ( __kmp_user_lock_kind == lk_futex ) && ( sizeof( lck->futex.lk.poll ) + sizeof( lck->futex.lk.depth_locked ) <= OMP_NEST_LOCK_T_SIZE ) ) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock( user_lock, "omp_test_nest_lock" ); } #if USE_ITT_BUILD __kmp_itt_lock_acquiring( lck ); #endif /* USE_ITT_BUILD */ rc = TEST_NESTED_LOCK( lck, gtid ); #if USE_ITT_BUILD if ( rc ) { __kmp_itt_lock_acquired( lck ); } else { __kmp_itt_lock_cancelled( lck ); } #endif /* USE_ITT_BUILD */ return rc; /* Can't use serial interval since not block structured */ #endif // KMP_USE_DYNAMIC_LOCK } /*--------------------------------------------------------------------------------------------------------------------*/ /* * Interface to fast scalable reduce methods routines */ // keep the selected method in a thread local structure for cross-function usage: will be used in __kmpc_end_reduce* functions; // another solution: to re-determine the method one more time in __kmpc_end_reduce* functions (new prototype required then) // AT: which solution is better? #define __KMP_SET_REDUCTION_METHOD(gtid,rmethod) \ ( ( __kmp_threads[ ( gtid ) ] -> th.th_local.packed_reduction_method ) = ( rmethod ) ) #define __KMP_GET_REDUCTION_METHOD(gtid) \ ( __kmp_threads[ ( gtid ) ] -> th.th_local.packed_reduction_method ) // description of the packed_reduction_method variable: look at the macros in kmp.h // used in a critical section reduce block static __forceinline void __kmp_enter_critical_section_reduce_block( ident_t * loc, kmp_int32 global_tid, kmp_critical_name * crit ) { // this lock was visible to a customer and to the thread profiler as a serial overhead span // (although it's used for an internal purpose only) // why was it visible in previous implementation? // should we keep it visible in new reduce block? kmp_user_lock_p lck; #if KMP_USE_DYNAMIC_LOCK if (DYNA_IS_D_LOCK(__kmp_user_lock_seq)) { lck = (kmp_user_lock_p)crit; if (*((kmp_dyna_lock_t *)lck) == 0) { KMP_COMPARE_AND_STORE_ACQ32((volatile kmp_int32 *)lck, 0, DYNA_GET_D_TAG(__kmp_user_lock_seq)); } KMP_DEBUG_ASSERT(lck != NULL); if (__kmp_env_consistency_check) { __kmp_push_sync(global_tid, ct_critical, loc, lck, __kmp_user_lock_seq); } DYNA_D_LOCK_FUNC(lck, set)((kmp_dyna_lock_t *)lck, global_tid); } else { kmp_indirect_lock_t *ilk = __kmp_get_indirect_csptr(crit, loc, global_tid, __kmp_user_lock_seq); KMP_DEBUG_ASSERT(ilk != NULL); if (__kmp_env_consistency_check) { __kmp_push_sync(global_tid, ct_critical, loc, ilk->lock, __kmp_user_lock_seq); } DYNA_I_LOCK_FUNC(ilk, set)(ilk->lock, global_tid); } #else // KMP_USE_DYNAMIC_LOCK // We know that the fast reduction code is only emitted by Intel compilers // with 32 byte critical sections. If there isn't enough space, then we // have to use a pointer. if ( __kmp_base_user_lock_size <= INTEL_CRITICAL_SIZE ) { lck = (kmp_user_lock_p)crit; } else { lck = __kmp_get_critical_section_ptr( crit, loc, global_tid ); } KMP_DEBUG_ASSERT( lck != NULL ); if ( __kmp_env_consistency_check ) __kmp_push_sync( global_tid, ct_critical, loc, lck ); __kmp_acquire_user_lock_with_checks( lck, global_tid ); #endif // KMP_USE_DYNAMIC_LOCK } // used in a critical section reduce block static __forceinline void __kmp_end_critical_section_reduce_block( ident_t * loc, kmp_int32 global_tid, kmp_critical_name * crit ) { kmp_user_lock_p lck; #if KMP_USE_DYNAMIC_LOCK if (DYNA_IS_D_LOCK(__kmp_user_lock_seq)) { lck = (kmp_user_lock_p)crit; if (__kmp_env_consistency_check) __kmp_pop_sync(global_tid, ct_critical, loc); DYNA_D_LOCK_FUNC(lck, unset)((kmp_dyna_lock_t *)lck, global_tid); } else { kmp_indirect_lock_t *ilk = (kmp_indirect_lock_t *)TCR_PTR(*((kmp_indirect_lock_t **)crit)); if (__kmp_env_consistency_check) __kmp_pop_sync(global_tid, ct_critical, loc); DYNA_I_LOCK_FUNC(ilk, unset)(ilk->lock, global_tid); } #else // KMP_USE_DYNAMIC_LOCK // We know that the fast reduction code is only emitted by Intel compilers with 32 byte critical // sections. If there isn't enough space, then we have to use a pointer. if ( __kmp_base_user_lock_size > 32 ) { lck = *( (kmp_user_lock_p *) crit ); KMP_ASSERT( lck != NULL ); } else { lck = (kmp_user_lock_p) crit; } if ( __kmp_env_consistency_check ) __kmp_pop_sync( global_tid, ct_critical, loc ); __kmp_release_user_lock_with_checks( lck, global_tid ); #endif // KMP_USE_DYNAMIC_LOCK } // __kmp_end_critical_section_reduce_block /* 2.a.i. Reduce Block without a terminating barrier */ /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid global thread number @param num_vars number of items (variables) to be reduced @param reduce_size size of data in bytes to be reduced @param reduce_data pointer to data to be reduced @param reduce_func callback function providing reduction operation on two operands and returning result of reduction in lhs_data @param lck pointer to the unique lock data structure @result 1 for the master thread, 0 for all other team threads, 2 for all team threads if atomic reduction needed The nowait version is used for a reduce clause with the nowait argument. */ kmp_int32 __kmpc_reduce_nowait( ident_t *loc, kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck ) { KMP_COUNT_BLOCK(REDUCE_nowait); int retval = 0; PACKED_REDUCTION_METHOD_T packed_reduction_method; #if OMP_40_ENABLED kmp_team_t *team; kmp_info_t *th; int teams_swapped = 0, task_state; #endif KA_TRACE( 10, ( "__kmpc_reduce_nowait() enter: called T#%d\n", global_tid ) ); // why do we need this initialization here at all? // Reduction clause can not be used as a stand-alone directive. // do not call __kmp_serial_initialize(), it will be called by __kmp_parallel_initialize() if needed // possible detection of false-positive race by the threadchecker ??? if( ! TCR_4( __kmp_init_parallel ) ) __kmp_parallel_initialize(); // check correctness of reduce block nesting #if KMP_USE_DYNAMIC_LOCK if ( __kmp_env_consistency_check ) __kmp_push_sync( global_tid, ct_reduce, loc, NULL, 0 ); #else if ( __kmp_env_consistency_check ) __kmp_push_sync( global_tid, ct_reduce, loc, NULL ); #endif #if OMP_40_ENABLED th = __kmp_thread_from_gtid(global_tid); if( th->th.th_teams_microtask ) { // AC: check if we are inside the teams construct? team = th->th.th_team; if( team->t.t_level == th->th.th_teams_level ) { // this is reduction at teams construct KMP_DEBUG_ASSERT(!th->th.th_info.ds.ds_tid); // AC: check that tid == 0 // Let's swap teams temporarily for the reduction barrier teams_swapped = 1; th->th.th_info.ds.ds_tid = team->t.t_master_tid; th->th.th_team = team->t.t_parent; th->th.th_team_nproc = th->th.th_team->t.t_nproc; th->th.th_task_team = th->th.th_team->t.t_task_team[0]; task_state = th->th.th_task_state; th->th.th_task_state = 0; } } #endif // OMP_40_ENABLED // packed_reduction_method value will be reused by __kmp_end_reduce* function, the value should be kept in a variable // the variable should be either a construct-specific or thread-specific property, not a team specific property // (a thread can reach the next reduce block on the next construct, reduce method may differ on the next construct) // an ident_t "loc" parameter could be used as a construct-specific property (what if loc == 0?) // (if both construct-specific and team-specific variables were shared, then unness extra syncs should be needed) // a thread-specific variable is better regarding two issues above (next construct and extra syncs) // a thread-specific "th_local.reduction_method" variable is used currently // each thread executes 'determine' and 'set' lines (no need to execute by one thread, to avoid unness extra syncs) packed_reduction_method = __kmp_determine_reduction_method( loc, global_tid, num_vars, reduce_size, reduce_data, reduce_func, lck ); __KMP_SET_REDUCTION_METHOD( global_tid, packed_reduction_method ); if( packed_reduction_method == critical_reduce_block ) { __kmp_enter_critical_section_reduce_block( loc, global_tid, lck ); retval = 1; } else if( packed_reduction_method == empty_reduce_block ) { // usage: if team size == 1, no synchronization is required ( Intel platforms only ) retval = 1; } else if( packed_reduction_method == atomic_reduce_block ) { retval = 2; // all threads should do this pop here (because __kmpc_end_reduce_nowait() won't be called by the code gen) // (it's not quite good, because the checking block has been closed by this 'pop', // but atomic operation has not been executed yet, will be executed slightly later, literally on next instruction) if ( __kmp_env_consistency_check ) __kmp_pop_sync( global_tid, ct_reduce, loc ); } else if( TEST_REDUCTION_METHOD( packed_reduction_method, tree_reduce_block ) ) { //AT: performance issue: a real barrier here //AT: (if master goes slow, other threads are blocked here waiting for the master to come and release them) //AT: (it's not what a customer might expect specifying NOWAIT clause) //AT: (specifying NOWAIT won't result in improvement of performance, it'll be confusing to a customer) //AT: another implementation of *barrier_gather*nowait() (or some other design) might go faster // and be more in line with sense of NOWAIT //AT: TO DO: do epcc test and compare times // this barrier should be invisible to a customer and to the thread profiler // (it's neither a terminating barrier nor customer's code, it's used for an internal purpose) #if USE_ITT_NOTIFY __kmp_threads[global_tid]->th.th_ident = loc; #endif retval = __kmp_barrier( UNPACK_REDUCTION_BARRIER( packed_reduction_method ), global_tid, FALSE, reduce_size, reduce_data, reduce_func ); retval = ( retval != 0 ) ? ( 0 ) : ( 1 ); // all other workers except master should do this pop here // ( none of other workers will get to __kmpc_end_reduce_nowait() ) if ( __kmp_env_consistency_check ) { if( retval == 0 ) { __kmp_pop_sync( global_tid, ct_reduce, loc ); } } } else { // should never reach this block KMP_ASSERT( 0 ); // "unexpected method" } #if OMP_40_ENABLED if( teams_swapped ) { // Restore thread structure th->th.th_info.ds.ds_tid = 0; th->th.th_team = team; th->th.th_team_nproc = team->t.t_nproc; th->th.th_task_team = team->t.t_task_team[task_state]; th->th.th_task_state = task_state; } #endif KA_TRACE( 10, ( "__kmpc_reduce_nowait() exit: called T#%d: method %08x, returns %08x\n", global_tid, packed_reduction_method, retval ) ); return retval; } /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid global thread id. @param lck pointer to the unique lock data structure Finish the execution of a reduce nowait. */ void __kmpc_end_reduce_nowait( ident_t *loc, kmp_int32 global_tid, kmp_critical_name *lck ) { PACKED_REDUCTION_METHOD_T packed_reduction_method; KA_TRACE( 10, ( "__kmpc_end_reduce_nowait() enter: called T#%d\n", global_tid ) ); packed_reduction_method = __KMP_GET_REDUCTION_METHOD( global_tid ); if( packed_reduction_method == critical_reduce_block ) { __kmp_end_critical_section_reduce_block( loc, global_tid, lck ); } else if( packed_reduction_method == empty_reduce_block ) { // usage: if team size == 1, no synchronization is required ( on Intel platforms only ) } else if( packed_reduction_method == atomic_reduce_block ) { // neither master nor other workers should get here // (code gen does not generate this call in case 2: atomic reduce block) // actually it's better to remove this elseif at all; // after removal this value will checked by the 'else' and will assert } else if( TEST_REDUCTION_METHOD( packed_reduction_method, tree_reduce_block ) ) { // only master gets here } else { // should never reach this block KMP_ASSERT( 0 ); // "unexpected method" } if ( __kmp_env_consistency_check ) __kmp_pop_sync( global_tid, ct_reduce, loc ); KA_TRACE( 10, ( "__kmpc_end_reduce_nowait() exit: called T#%d: method %08x\n", global_tid, packed_reduction_method ) ); return; } /* 2.a.ii. Reduce Block with a terminating barrier */ /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid global thread number @param num_vars number of items (variables) to be reduced @param reduce_size size of data in bytes to be reduced @param reduce_data pointer to data to be reduced @param reduce_func callback function providing reduction operation on two operands and returning result of reduction in lhs_data @param lck pointer to the unique lock data structure @result 1 for the master thread, 0 for all other team threads, 2 for all team threads if atomic reduction needed A blocking reduce that includes an implicit barrier. */ kmp_int32 __kmpc_reduce( ident_t *loc, kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck ) { KMP_COUNT_BLOCK(REDUCE_wait); int retval = 0; PACKED_REDUCTION_METHOD_T packed_reduction_method; KA_TRACE( 10, ( "__kmpc_reduce() enter: called T#%d\n", global_tid ) ); // why do we need this initialization here at all? // Reduction clause can not be a stand-alone directive. // do not call __kmp_serial_initialize(), it will be called by __kmp_parallel_initialize() if needed // possible detection of false-positive race by the threadchecker ??? if( ! TCR_4( __kmp_init_parallel ) ) __kmp_parallel_initialize(); // check correctness of reduce block nesting #if KMP_USE_DYNAMIC_LOCK if ( __kmp_env_consistency_check ) __kmp_push_sync( global_tid, ct_reduce, loc, NULL, 0 ); #else if ( __kmp_env_consistency_check ) __kmp_push_sync( global_tid, ct_reduce, loc, NULL ); #endif packed_reduction_method = __kmp_determine_reduction_method( loc, global_tid, num_vars, reduce_size, reduce_data, reduce_func, lck ); __KMP_SET_REDUCTION_METHOD( global_tid, packed_reduction_method ); if( packed_reduction_method == critical_reduce_block ) { __kmp_enter_critical_section_reduce_block( loc, global_tid, lck ); retval = 1; } else if( packed_reduction_method == empty_reduce_block ) { // usage: if team size == 1, no synchronization is required ( Intel platforms only ) retval = 1; } else if( packed_reduction_method == atomic_reduce_block ) { retval = 2; } else if( TEST_REDUCTION_METHOD( packed_reduction_method, tree_reduce_block ) ) { //case tree_reduce_block: // this barrier should be visible to a customer and to the thread profiler // (it's a terminating barrier on constructs if NOWAIT not specified) #if USE_ITT_NOTIFY __kmp_threads[global_tid]->th.th_ident = loc; // needed for correct notification of frames #endif retval = __kmp_barrier( UNPACK_REDUCTION_BARRIER( packed_reduction_method ), global_tid, TRUE, reduce_size, reduce_data, reduce_func ); retval = ( retval != 0 ) ? ( 0 ) : ( 1 ); // all other workers except master should do this pop here // ( none of other workers except master will enter __kmpc_end_reduce() ) if ( __kmp_env_consistency_check ) { if( retval == 0 ) { // 0: all other workers; 1: master __kmp_pop_sync( global_tid, ct_reduce, loc ); } } } else { // should never reach this block KMP_ASSERT( 0 ); // "unexpected method" } KA_TRACE( 10, ( "__kmpc_reduce() exit: called T#%d: method %08x, returns %08x\n", global_tid, packed_reduction_method, retval ) ); return retval; } /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid global thread id. @param lck pointer to the unique lock data structure Finish the execution of a blocking reduce. The <tt>lck</tt> pointer must be the same as that used in the corresponding start function. */ void __kmpc_end_reduce( ident_t *loc, kmp_int32 global_tid, kmp_critical_name *lck ) { PACKED_REDUCTION_METHOD_T packed_reduction_method; KA_TRACE( 10, ( "__kmpc_end_reduce() enter: called T#%d\n", global_tid ) ); packed_reduction_method = __KMP_GET_REDUCTION_METHOD( global_tid ); // this barrier should be visible to a customer and to the thread profiler // (it's a terminating barrier on constructs if NOWAIT not specified) if( packed_reduction_method == critical_reduce_block ) { __kmp_end_critical_section_reduce_block( loc, global_tid, lck ); // TODO: implicit barrier: should be exposed #if USE_ITT_NOTIFY __kmp_threads[global_tid]->th.th_ident = loc; #endif __kmp_barrier( bs_plain_barrier, global_tid, FALSE, 0, NULL, NULL ); } else if( packed_reduction_method == empty_reduce_block ) { // usage: if team size == 1, no synchronization is required ( Intel platforms only ) // TODO: implicit barrier: should be exposed #if USE_ITT_NOTIFY __kmp_threads[global_tid]->th.th_ident = loc; #endif __kmp_barrier( bs_plain_barrier, global_tid, FALSE, 0, NULL, NULL ); } else if( packed_reduction_method == atomic_reduce_block ) { // TODO: implicit barrier: should be exposed #if USE_ITT_NOTIFY __kmp_threads[global_tid]->th.th_ident = loc; #endif __kmp_barrier( bs_plain_barrier, global_tid, FALSE, 0, NULL, NULL ); } else if( TEST_REDUCTION_METHOD( packed_reduction_method, tree_reduce_block ) ) { // only master executes here (master releases all other workers) __kmp_end_split_barrier( UNPACK_REDUCTION_BARRIER( packed_reduction_method ), global_tid ); } else { // should never reach this block KMP_ASSERT( 0 ); // "unexpected method" } if ( __kmp_env_consistency_check ) __kmp_pop_sync( global_tid, ct_reduce, loc ); KA_TRACE( 10, ( "__kmpc_end_reduce() exit: called T#%d: method %08x\n", global_tid, packed_reduction_method ) ); return; } #undef __KMP_GET_REDUCTION_METHOD #undef __KMP_SET_REDUCTION_METHOD /*-- end of interface to fast scalable reduce routines ---------------------------------------------------------------*/ kmp_uint64 __kmpc_get_taskid() { kmp_int32 gtid; kmp_info_t * thread; gtid = __kmp_get_gtid(); if ( gtid < 0 ) { return 0; }; // if thread = __kmp_thread_from_gtid( gtid ); return thread->th.th_current_task->td_task_id; } // __kmpc_get_taskid kmp_uint64 __kmpc_get_parent_taskid() { kmp_int32 gtid; kmp_info_t * thread; kmp_taskdata_t * parent_task; gtid = __kmp_get_gtid(); if ( gtid < 0 ) { return 0; }; // if thread = __kmp_thread_from_gtid( gtid ); parent_task = thread->th.th_current_task->td_parent; return ( parent_task == NULL ? 0 : parent_task->td_task_id ); } // __kmpc_get_parent_taskid void __kmpc_place_threads(int nC, int nT, int nO) { if ( ! __kmp_init_serial ) { __kmp_serial_initialize(); } __kmp_place_num_cores = nC; __kmp_place_num_threads_per_core = nT; __kmp_place_core_offset = nO; } // end of file //
GB_msort_1.c
//------------------------------------------------------------------------------ // GB_msort_1: sort a 1-by-n list of integers //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // A parallel mergesort of an array of 1-by-n integers. #include "GB_msort_1.h" //------------------------------------------------------------------------------ // GB_msort_1_binary_search: binary search for the pivot //------------------------------------------------------------------------------ // The Pivot value is Y [pivot], and a binary search for the Pivot is made in // the array X [p_pstart...p_end-1], which is sorted in non-decreasing order on // input. The return value is pleft, where // // X [p_start ... pleft-1] <= Pivot and // X [pleft ... p_end-1] >= Pivot holds. // // pleft is returned in the range p_start to p_end. If pleft is p_start, then // the Pivot is smaller than all entries in X [p_start...p_end-1], and the left // list X [p_start...pleft-1] is empty. If pleft is p_end, then the Pivot is // larger than all entries in X [p_start...p_end-1], and the right list X // [pleft...p_end-1] is empty. static int64_t GB_msort_1_binary_search // return pleft ( const int64_t *restrict Y_0, // Pivot is Y [pivot] const int64_t pivot, const int64_t *restrict X_0, // search in X [p_start..p_end_-1] const int64_t p_start, const int64_t p_end ) { //-------------------------------------------------------------------------- // find where the Pivot appears in X //-------------------------------------------------------------------------- // binary search of X [p_start...p_end-1] for the Pivot int64_t pleft = p_start ; int64_t pright = p_end - 1 ; while (pleft < pright) { int64_t pmiddle = (pleft + pright) >> 1 ; // less = (X [pmiddle] < Pivot) bool less = GB_lt_1 (X_0, pmiddle, Y_0, pivot) ; pleft = less ? (pmiddle+1) : pleft ; pright = less ? pright : pmiddle ; } // binary search is narrowed down to a single item // or it has found the list is empty: ASSERT (pleft == pright || pleft == pright + 1) ; // If found is true then X [pleft == pright] == Pivot. If duplicates // appear then X [pleft] is any one of the entries equal to the Pivot // in the list. If found is false then // X [p_start ... pleft-1] < Pivot and // X [pleft+1 ... p_end-1] > Pivot holds. // The value X [pleft] may be either < or > Pivot. bool found = (pleft == pright) && GB_eq_1 (X_0, pleft, Y_0, pivot) ; // Modify pleft and pright: if (!found && (pleft == pright)) { if (GB_lt_1 (X_0, pleft, Y_0, pivot)) { pleft++ ; } else { // pright++ ; // (not needed) } } //-------------------------------------------------------------------------- // return result //-------------------------------------------------------------------------- // If found is false then // X [p_start ... pleft-1] < Pivot and // X [pleft ... p_end-1] > Pivot holds, // and pleft-1 == pright // If X has no duplicates, then whether or not Pivot is found, // X [p_start ... pleft-1] < Pivot and // X [pleft ... p_end-1] >= Pivot holds. // If X has duplicates, then whether or not Pivot is found, // X [p_start ... pleft-1] <= Pivot and // X [pleft ... p_end-1] >= Pivot holds. return (pleft) ; } //------------------------------------------------------------------------------ // GB_msort_1_create_merge_tasks //------------------------------------------------------------------------------ // Recursively constructs ntasks tasks to merge two arrays, Left and Right, // into Sresult, where Left is L [pL_start...pL_end-1], Right is R // [pR_start...pR_end-1], and Sresult is S [pS_start...pS_start+total_work-1], // and where total_work is the total size of Left and Right. // // Task tid will merge L [L_task [tid] ... L_task [tid] + L_len [tid] - 1] and // R [R_task [tid] ... R_task [tid] + R_len [tid] -1] into the merged output // array S [S_task [tid] ... ]. The task tids created are t0 to // t0+ntasks-1. void GB_msort_1_create_merge_tasks ( // output: int64_t *restrict L_task, // L_task [t0...t0+ntasks-1] computed int64_t *restrict L_len, // L_len [t0...t0+ntasks-1] computed int64_t *restrict R_task, // R_task [t0...t0+ntasks-1] computed int64_t *restrict R_len, // R_len [t0...t0+ntasks-1] computed int64_t *restrict S_task, // S_task [t0...t0+ntasks-1] computed // input: const int t0, // first task tid to create const int ntasks, // # of tasks to create const int64_t pS_start, // merge into S [pS_start...] const int64_t *restrict L_0, // Left = L [pL_start...pL_end-1] const int64_t pL_start, const int64_t pL_end, const int64_t *restrict R_0, // Right = R [pR_start...pR_end-1] const int64_t pR_start, const int64_t pR_end ) { //-------------------------------------------------------------------------- // get problem size //-------------------------------------------------------------------------- int64_t nleft = pL_end - pL_start ; // size of Left array int64_t nright = pR_end - pR_start ; // size of Right array int64_t total_work = nleft + nright ; // total work to do ASSERT (ntasks >= 1) ; ASSERT (total_work > 0) ; //-------------------------------------------------------------------------- // create the tasks //-------------------------------------------------------------------------- if (ntasks == 1) { //---------------------------------------------------------------------- // a single task will merge all of Left and Right into Sresult //---------------------------------------------------------------------- L_task [t0] = pL_start ; L_len [t0] = nleft ; R_task [t0] = pR_start ; R_len [t0] = nright ; S_task [t0] = pS_start ; } else { //---------------------------------------------------------------------- // partition the Left and Right arrays for multiple merge tasks //---------------------------------------------------------------------- int64_t pleft, pright ; if (nleft >= nright) { // split Left in half, and search for its pivot in Right pleft = (pL_end + pL_start) >> 1 ; pright = GB_msort_1_binary_search ( L_0, pleft, R_0, pR_start, pR_end) ; } else { // split Right in half, and search for its pivot in Left pright = (pR_end + pR_start) >> 1 ; pleft = GB_msort_1_binary_search ( R_0, pright, L_0, pL_start, pL_end) ; } //---------------------------------------------------------------------- // partition the tasks according to the work of each partition //---------------------------------------------------------------------- // work0 is the total work in the first partition int64_t work0 = (pleft - pL_start) + (pright - pR_start) ; int ntasks0 = (int) round ((double) ntasks * (((double) work0) / ((double) total_work))) ; // ensure at least one task is assigned to each partition ntasks0 = GB_IMAX (ntasks0, 1) ; ntasks0 = GB_IMIN (ntasks0, ntasks-1) ; int ntasks1 = ntasks - ntasks0 ; //---------------------------------------------------------------------- // assign ntasks0 to the first half //---------------------------------------------------------------------- // ntasks0 tasks merge L [pL_start...pleft-1] and R [pR_start..pright-1] // into the result S [pS_start...work0-1]. GB_msort_1_create_merge_tasks ( L_task, L_len, R_task, R_len, S_task, t0, ntasks0, pS_start, L_0, pL_start, pleft, R_0, pR_start, pright) ; //---------------------------------------------------------------------- // assign ntasks1 to the second half //---------------------------------------------------------------------- // ntasks1 tasks merge L [pleft...pL_end-1] and R [pright...pR_end-1] // into the result S [pS_start+work0...pS_start+total_work]. int t1 = t0 + ntasks0 ; // first task id of the second set of tasks int64_t pS_start1 = pS_start + work0 ; // 2nd set starts here in S GB_msort_1_create_merge_tasks ( L_task, L_len, R_task, R_len, S_task, t1, ntasks1, pS_start1, L_0, pleft, pL_end, R_0, pright, pR_end) ; } } //------------------------------------------------------------------------------ // GB_msort_1_merge: merge two sorted lists via a single thread //------------------------------------------------------------------------------ // merge Left [0..nleft-1] and Right [0..nright-1] into S [0..nleft+nright-1] */ static void GB_msort_1_merge ( int64_t *restrict S_0, // output of length nleft + nright const int64_t *restrict Left_0, // left input of length nleft const int64_t nleft, const int64_t *restrict Right_0, // right input of length nright const int64_t nright ) { int64_t p, pleft, pright ; // merge the two inputs, Left and Right, while both inputs exist for (p = 0, pleft = 0, pright = 0 ; pleft < nleft && pright < nright ; p++) { if (GB_lt_1 (Left_0, pleft, Right_0, pright)) { // S [p] = Left [pleft++] S_0 [p] = Left_0 [pleft] ; pleft++ ; } else { // S [p] = Right [pright++] S_0 [p] = Right_0 [pright] ; pright++ ; } } // either input is exhausted; copy the remaining list into S if (pleft < nleft) { int64_t nremaining = (nleft - pleft) ; memcpy (S_0 + p, Left_0 + pleft, nremaining * sizeof (int64_t)) ; } else if (pright < nright) { int64_t nremaining = (nright - pright) ; memcpy (S_0 + p, Right_0 + pright, nremaining * sizeof (int64_t)) ; } } //------------------------------------------------------------------------------ // GB_msort_1: parallel mergesort //------------------------------------------------------------------------------ GB_PUBLIC GrB_Info GB_msort_1 // sort array A of size 1-by-n ( int64_t *restrict A_0, // size n array const int64_t n, int nthreads // # of threads to use ) { //-------------------------------------------------------------------------- // handle small problems with a single thread //-------------------------------------------------------------------------- if (nthreads <= 1 || n <= GB_BASECASE) { // sequential quicksort GB_qsort_1 (A_0, n) ; return (GrB_SUCCESS) ; } //-------------------------------------------------------------------------- // determine # of tasks //-------------------------------------------------------------------------- // determine the number of levels to create, which must always be an // even number. The # of levels is chosen to ensure that the # of leaves // of the task tree is between 4*nthreads and 16*nthreads. // 2 to 4 threads: 4 levels, 16 qsort leaves // 5 to 16 threads: 6 levels, 64 qsort leaves // 17 to 64 threads: 8 levels, 256 qsort leaves // 65 to 256 threads: 10 levels, 1024 qsort leaves // 256 to 1024 threads: 12 levels, 4096 qsort leaves // ... int k = (int) (2 + 2 * ceil (log2 ((double) nthreads) / 2)) ; int ntasks = 1 << k ; //-------------------------------------------------------------------------- // allocate workspace //-------------------------------------------------------------------------- int64_t *restrict W = NULL ; size_t W_size = 0 ; W = GB_MALLOC_WORK (n + 6*ntasks + 1, int64_t, &W_size) ; if (W == NULL) { // out of memory return (GrB_OUT_OF_MEMORY) ; } int64_t *T = W ; int64_t *restrict W_0 = T ; T += n ; int64_t *restrict L_task = T ; T += ntasks ; int64_t *restrict L_len = T ; T += ntasks ; int64_t *restrict R_task = T ; T += ntasks ; int64_t *restrict R_len = T ; T += ntasks ; int64_t *restrict S_task = T ; T += ntasks ; int64_t *restrict Slice = T ; T += (ntasks+1) ; //-------------------------------------------------------------------------- // partition and sort the leaves //-------------------------------------------------------------------------- GB_eslice (Slice, n, ntasks) ; int tid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { int64_t leaf = Slice [tid] ; int64_t leafsize = Slice [tid+1] - leaf ; GB_qsort_1 (A_0 + leaf, leafsize) ; } //-------------------------------------------------------------------------- // merge each level //-------------------------------------------------------------------------- int nt = 1 ; for ( ; k >= 2 ; k -= 2) { //---------------------------------------------------------------------- // merge level k into level k-1, from A into W //---------------------------------------------------------------------- // TODO: skip k and k-1 for each group of 4 sublists of A if they are // already sorted with respect to each other. // this could be done in parallel if ntasks was large for (int tid = 0 ; tid < ntasks ; tid += 2*nt) { // create 2*nt tasks to merge two A sublists into one W sublist GB_msort_1_create_merge_tasks ( L_task, L_len, R_task, R_len, S_task, tid, 2*nt, Slice [tid], A_0, Slice [tid], Slice [tid+nt], A_0, Slice [tid+nt], Slice [tid+2*nt]) ; } #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { // merge A [pL...pL+nL-1] and A [pR...pR+nR-1] into W [pS..] int64_t pL = L_task [tid], nL = L_len [tid] ; int64_t pR = R_task [tid], nR = R_len [tid] ; int64_t pS = S_task [tid] ; GB_msort_1_merge ( W_0 + pS, A_0 + pL, nL, A_0 + pR, nR) ; } nt = 2*nt ; //---------------------------------------------------------------------- // merge level k-1 into level k-2, from W into A //---------------------------------------------------------------------- // this could be done in parallel if ntasks was large for (int tid = 0 ; tid < ntasks ; tid += 2*nt) { // create 2*nt tasks to merge two W sublists into one A sublist GB_msort_1_create_merge_tasks ( L_task, L_len, R_task, R_len, S_task, tid, 2*nt, Slice [tid], W_0, Slice [tid], Slice [tid+nt], W_0, Slice [tid+nt], Slice [tid+2*nt]) ; } #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { // merge A [pL...pL+nL-1] and A [pR...pR+nR-1] into W [pS..] int64_t pL = L_task [tid], nL = L_len [tid] ; int64_t pR = R_task [tid], nR = R_len [tid] ; int64_t pS = S_task [tid] ; GB_msort_1_merge ( A_0 + pS, W_0 + pL, nL, W_0 + pR, nR) ; } nt = 2*nt ; } //-------------------------------------------------------------------------- // free workspace and return result //-------------------------------------------------------------------------- GB_FREE_WORK (&W, W_size) ; return (GrB_SUCCESS) ; }
singleModificado.c
#include <stdio.h> #include <omp.h> void main() { int n = 9, i, a, b[n]; for (i=0; i<n; i++) b[i] = -1; #pragma omp parallel { #pragma omp single { printf("Introduce valor de inicialización a: "); scanf("%d", &a ); printf("Single Inicial ejecutada por el thread %d\n", omp_get_thread_num()); } #pragma omp for for (i=0; i<n; i++) b[i] = a; //printf("Iteración Inicial ejecutada por el thread %d\n", omp_get_thread_num()); //#pragma omp barrier //hay barrera implícita después del for #pragma omp single { printf("Imprimo dentro de la región parallel con la directiva single:\n"); printf("Single Final ejecutada por el thread %d\n", omp_get_thread_num()); for (i=0; i<n; i++){ //printf("Iteración Final ejecutada por el thread %d\n", omp_get_thread_num()); printf("b[%d] = %d\n",i,b[i]); } } } }
compute_ktopipi_type2.h
#ifndef _COMPUTE_KTOPIPI_TYPE2_H #define _COMPUTE_KTOPIPI_TYPE2_H #include<alg/a2a/mf_productstore.h> CPS_START_NAMESPACE //TYPE 2 //Each contraction of this type is made up of different trace combinations of two objects (below [but not in the code!] for simplicity we ignore the fact that the two vectors in //the meson fields are allowed to vary in position relative to each other): //1) \sum_{ \vec x_K } \Gamma_1 \prop^L(x_op,x_K) \gamma^5 \prop^H(x_K,x_op) //2) \sum_{ \vec y, \vec z } \Gamma_2 \prop^L(x_op,y) S_2 \prop^L(y,z) S_2 \prop^L(z,x_op) //We use g5-hermiticity on the strange propagator //1) -> \sum_{ \vec x_K } \Gamma_1 \prop^L(x_op,x_K) [\prop^H(x_op,x_K)]^\dagger \gamma^5 // = \sum_{ \vec x_K } \Gamma_1 vL(x_op) wL^dag(x_K) [ vH(x_op) wH^dag(x_K) ]^dag \gamma^5 // = \sum_{ \vec x_K } \Gamma_1 vL(x_op) [[ wL^dag(x_K) wH(x_K) ]] [vH(x_op)]^dag \gamma^5 // where [[ ]] indicate meson fields //2) In terms of v and w // \sum_{ \vec y, \vec z } \Gamma_2 vL(x_op) [[ wL^dag(y) S_2 vL(y) ]] [[ wL^dag(z) S_2 vL(z) ]] wL^dag(x_op) //Run inside threaded environment template<typename mf_Policies> void ComputeKtoPiPiGparity<mf_Policies>::type2_contract(ResultsContainerType &result, const int t_K, const int t_dis, const int thread_id, const SCFmat &part1, const SCFmatVector &part2){ #ifndef MEMTEST_MODE static const int n_contract = 6; //six type2 diagrams static const int con_off = 7; //index of first contraction in set for(int mu=0;mu<4;mu++){ //sum over mu here for(int gcombidx=0;gcombidx<8;gcombidx++){ const SCFmat &G1 = Gamma1<ComplexType>(gcombidx,mu); const SCFmat &G2 = Gamma2<ComplexType>(gcombidx,mu); SCFmat G1_pt1 = part1; //= G1*part1; multGammaLeft(G1_pt1,1,gcombidx,mu); CPScolorMatrix<ComplexType> tr_sf_G1_pt1 = G1_pt1.SpinFlavorTrace(); for(int pt2_pion=0; pt2_pion<2; pt2_pion++){ //which pion comes first in part 2? SCFmat G2_pt2 = part2[pt2_pion]; //= G2*part2[pt2_pion]; multGammaLeft(G2_pt2,2,gcombidx,mu); CPScolorMatrix<ComplexType> tr_sf_G2_pt2 = G2_pt2.SpinFlavorTrace(); SCFmat ctrans_G2_pt2(G2_pt2); //speedup by transposing part 1 ctrans_G2_pt2.TransposeColor(); #define C(IDX) result(t_K,t_dis,IDX-con_off,gcombidx,thread_id) C(7) += G1_pt1.Trace() * G2_pt2.Trace(); C(8) += Trace( tr_sf_G1_pt1 , Transpose(tr_sf_G2_pt2) ); C(9) += Trace( tr_sf_G1_pt1 , tr_sf_G2_pt2 ); C(10) += Trace( G1_pt1 , G2_pt2 ); C(11) += Trace( G1_pt1, ctrans_G2_pt2 ); C(12) += Trace( G1_pt1.ColorTrace() , G2_pt2.ColorTrace() ); #undef C } } } #endif } template<typename mf_Policies> void ComputeKtoPiPiGparity<mf_Policies>::type2_compute_mfproducts(std::vector<A2AmesonField<mf_Policies,A2AvectorWfftw,A2AvectorVfftw> > &con_pi1_pi2, std::vector<A2AmesonField<mf_Policies,A2AvectorWfftw,A2AvectorVfftw> > &con_pi2_pi1, const int tsep_pion, const int tstep, const std::vector<ThreeMomentum> &p_pi_1_all, MesonFieldMomentumContainer<mf_Policies> &mf_pions, const int Lt, const int tpi_sampled){ con_pi1_pi2.resize(tpi_sampled); //y is associated with pi1, z with pi2 con_pi2_pi1.resize(tpi_sampled); //y is associated with pi2, z with pi1 A2AmesonField<mf_Policies,A2AvectorWfftw,A2AvectorVfftw> tmp; if(!UniqueID()){ printf("Computing con_*_*\n"); fflush(stdout); } //Some of these mults are quite likely duplicates, so use the product store to maximize reuse MesonFieldProductStore<mf_Policies> products; int nmom = p_pi_1_all.size(); for(int pidx=0;pidx<nmom;pidx++){ const ThreeMomentum &p_pi_1 = p_pi_1_all[pidx]; ThreeMomentum p_pi_2 = -p_pi_1; std::vector<A2AmesonField<mf_Policies,A2AvectorWfftw,A2AvectorVfftw> > &mf_pi1 = mf_pions.get(p_pi_1); std::vector<A2AmesonField<mf_Policies,A2AvectorWfftw,A2AvectorVfftw> > &mf_pi2 = mf_pions.get(p_pi_2); #ifdef NODE_DISTRIBUTE_MESONFIELDS nodeGetMany(2,&mf_pi1,&mf_pi2); #endif //nodeGetPionMf(mf_pi1,mf_pi2); //for(int tpi1=0;tpi1<Lt;tpi1 += tstep){ //my sensible ordering for(int t_pi1_lin = 1; t_pi1_lin <= Lt; t_pi1_lin += tstep){ //Daiqian's weird ordering int tpi1 = modLt(t_pi1_lin,Lt); int tpi1_idx = tpi1 / tstep; int tpi2 = modLt(tpi1 + tsep_pion, Lt); if(pidx==0){ con_pi1_pi2[tpi1_idx] = products.getProduct(mf_pi1[tpi1], mf_pi2[tpi2]); //node distributed con_pi2_pi1[tpi1_idx] = products.getProduct(mf_pi2[tpi2], mf_pi1[tpi1]); //mult(con_pi1_pi2[tpi1_idx], mf_pi1[tpi1], mf_pi2[tpi2]); //mult(con_pi2_pi1[tpi1_idx], mf_pi2[tpi2], mf_pi1[tpi1]); }else{ //mult(tmp, mf_pi1[tpi1], mf_pi2[tpi2]); tmp = products.getProduct(mf_pi1[tpi1], mf_pi2[tpi2]); con_pi1_pi2[tpi1_idx].plus_equals(tmp, true); //mult(tmp, mf_pi2[tpi2], mf_pi1[tpi1]); tmp = products.getProduct(mf_pi2[tpi2], mf_pi1[tpi1]); con_pi2_pi1[tpi1_idx].plus_equals(tmp, true); } //NB time coordinate of con_*_* is the time coordinate of pi1 (that closest to the kaon) } #ifdef NODE_DISTRIBUTE_MESONFIELDS nodeDistributeMany(2,&mf_pi1,&mf_pi2); #endif //nodeDistributePionMf(mf_pi1,mf_pi2); } if(nmom > 1) for(int t=0;t<tpi_sampled;t++){ con_pi1_pi2[t].times_equals(1./nmom); con_pi2_pi1[t].times_equals(1./nmom); } if(!UniqueID()){ printf("Finished computing con_pi_pi\n"); fflush(stdout); } } template<typename mf_Policies> void ComputeKtoPiPiGparity<mf_Policies>::type2_mult_vMv_setup(std::vector<mult_vMv_split<mf_Policies,A2AvectorV,A2AvectorWfftw,A2AvectorWfftw,A2AvectorV> > &mult_vMv_split_part1, std::vector<mult_vMv_split<mf_Policies,A2AvectorV,A2AvectorWfftw,A2AvectorVfftw,A2AvectorW> > &mult_vMv_split_part2_pi1_pi2, std::vector<mult_vMv_split<mf_Policies,A2AvectorV,A2AvectorWfftw,A2AvectorVfftw,A2AvectorW> > &mult_vMv_split_part2_pi2_pi1, const std::vector< A2AmesonField<mf_Policies,A2AvectorWfftw,A2AvectorVfftw> > &con_pi1_pi2, const std::vector< A2AmesonField<mf_Policies,A2AvectorWfftw,A2AvectorVfftw> > &con_pi2_pi1, const A2AvectorV<mf_Policies> & vL, const A2AvectorV<mf_Policies> & vH, const A2AvectorW<mf_Policies> & wL, const std::vector<A2AmesonField<mf_Policies,A2AvectorWfftw,A2AvectorWfftw> > &mf_kaon, const std::vector<int> &t_K_all, const int top_loc, const int tstep, const int Lt,const int tpi_sampled, const std::vector< std::vector<bool> > &node_top_used, const std::vector< std::vector<bool> > &node_top_used_kaon){ //Split the vector-mesonfield outer product into two stages where in the first we reorder the mesonfield to optimize cache hits mult_vMv_split_part1.resize(t_K_all.size()); mult_vMv_split_part2_pi1_pi2.resize(tpi_sampled); mult_vMv_split_part2_pi2_pi1.resize(tpi_sampled); int top_glb = top_loc + GJP.TnodeCoor()*GJP.TnodeSites(); //Part 1 #pragma omp parallel for for(int tkidx=0; tkidx < t_K_all.size(); tkidx++){ if(!node_top_used_kaon[tkidx][top_loc]) continue; int t_K = t_K_all[tkidx]; mult_vMv_split_part1[tkidx].setup(vL,mf_kaon[t_K],vH,top_glb); } //Part 2 #pragma omp parallel for for(int t_pi1_lin = 1; t_pi1_lin <= Lt; t_pi1_lin += tstep){ //Daiqian's weird ordering int t_pi1 = modLt(t_pi1_lin,Lt); int t_pi1_idx = t_pi1 / tstep; if(!node_top_used[t_pi1_idx][top_loc]) continue; //can be better parallelized! mult_vMv_split_part2_pi1_pi2[t_pi1_idx].setup(vL,con_pi1_pi2[t_pi1_idx],wL, top_glb); mult_vMv_split_part2_pi2_pi1[t_pi1_idx].setup(vL,con_pi2_pi1[t_pi1_idx],wL, top_glb); } } template<typename mf_Policies> void ComputeKtoPiPiGparity<mf_Policies>::type2_precompute_part1_part2(std::vector<SCFmatVector > &mult_vMv_contracted_part1, std::vector<SCFmatVector > &mult_vMv_contracted_part2_pi1_pi2, std::vector<SCFmatVector > &mult_vMv_contracted_part2_pi2_pi1, std::vector<mult_vMv_split<mf_Policies,A2AvectorV,A2AvectorWfftw,A2AvectorWfftw,A2AvectorV> > &mult_vMv_split_part1, std::vector<mult_vMv_split<mf_Policies,A2AvectorV,A2AvectorWfftw,A2AvectorVfftw,A2AvectorW> > &mult_vMv_split_part2_pi1_pi2, std::vector<mult_vMv_split<mf_Policies,A2AvectorV,A2AvectorWfftw,A2AvectorVfftw,A2AvectorW> > &mult_vMv_split_part2_pi2_pi1, const std::vector<int> &t_K_all, const int top_loc, const int tstep, const int Lt,const int tpi_sampled, const std::vector< std::vector<bool> > &node_top_used, const std::vector< std::vector<bool> > &node_top_used_kaon){ mult_vMv_contracted_part1.resize(t_K_all.size()); mult_vMv_contracted_part2_pi1_pi2.resize(tpi_sampled); mult_vMv_contracted_part2_pi2_pi1.resize(tpi_sampled); for(int tkidx=0; tkidx < t_K_all.size(); tkidx++){ if(!node_top_used_kaon[tkidx][top_loc]) continue; int t_K = t_K_all[tkidx]; mult_vMv_split_part1[tkidx].contract(mult_vMv_contracted_part1[tkidx], false, true); mult_vMv_split_part1[tkidx].free_mem(); } for(int t_pi1_lin = 1; t_pi1_lin <= Lt; t_pi1_lin += tstep){ //Daiqian's weird ordering int t_pi1 = modLt(t_pi1_lin,Lt); int t_pi1_idx = t_pi1 / tstep; if(!node_top_used[t_pi1_idx][top_loc]) continue; mult_vMv_split_part2_pi1_pi2[t_pi1_idx].contract(mult_vMv_contracted_part2_pi1_pi2[t_pi1_idx], false,true); mult_vMv_split_part2_pi1_pi2[t_pi1_idx].free_mem(); mult_vMv_split_part2_pi2_pi1[t_pi1_idx].contract(mult_vMv_contracted_part2_pi2_pi1[t_pi1_idx], false,true); mult_vMv_split_part2_pi2_pi1[t_pi1_idx].free_mem(); } } //This version averages over multiple pion momentum configurations. Use to project onto A1 representation at run-time. Saves a lot of time! //This version also overlaps computation for multiple K->pi separations. Result should be an array of ResultsContainerType the same size as the vector 'tsep_k_pi' template<typename mf_Policies> void ComputeKtoPiPiGparity<mf_Policies>::type2(ResultsContainerType result[], const std::vector<int> &tsep_k_pi, const int &tsep_pion, const int &tstep, const std::vector<ThreeMomentum> &p_pi_1_all, const std::vector<A2AmesonField<mf_Policies,A2AvectorWfftw,A2AvectorWfftw> > &mf_kaon, MesonFieldMomentumContainer<mf_Policies> &mf_pions, const A2AvectorV<mf_Policies> & vL, const A2AvectorV<mf_Policies> & vH, const A2AvectorW<mf_Policies> & wL, const A2AvectorW<mf_Policies> & wH){ const int Lt = GJP.Tnodes()*GJP.TnodeSites(); assert(Lt % tstep == 0); const int tpi_sampled = Lt/tstep; static const int n_contract = 6; //six type2 diagrams static const int con_off = 7; //index of first contraction in set const int nthread = omp_get_max_threads(); for(int tkp=0;tkp<tsep_k_pi.size();tkp++) result[tkp].resize(n_contract,nthread); //Resize zeroes output. Result will be thread-reduced before this method ends const int size_3d = vL.getMode(0).nodeSites(0)*vL.getMode(0).nodeSites(1)*vL.getMode(0).nodeSites(2); //Compile some information about which timeslices are involved in the calculation such that we can minimize work by skipping unused timeslices std::vector< std::vector<bool> > node_top_used(tpi_sampled); //Which local operator timeslices are used for a given pi1 index std::vector<int> t_K_all; //Which kaon timeslices we need overall for(int t_pi1_lin = 1; t_pi1_lin <= Lt; t_pi1_lin += tstep){ //Daiqian's weird ordering int t_pi1 = modLt(t_pi1_lin,Lt); int t_pi1_idx = t_pi1 / tstep; getUsedTimeslices(node_top_used[t_pi1_idx],t_K_all,tsep_k_pi,t_pi1); } std::vector< std::vector<bool> > node_top_used_kaon(t_K_all.size()); //Which local operator timeslices are used for a given kaon index std::vector<int> tkidx_map(Lt,-1); for(int tkidx=0;tkidx<t_K_all.size();tkidx++){ getUsedTimeslicesForKaon(node_top_used_kaon[tkidx],tsep_k_pi,t_K_all[tkidx]); tkidx_map[t_K_all[tkidx]] = tkidx; //allow us to map into the storage given a value of t_K } //Form the product of the two meson fields //con_*_* = \sum_{\vec y,\vec z} [[ wL^dag(y) S_2 vL(y) ]] [[ wL^dag(z) S_2 vL(z) ]] std::vector< A2AmesonField<mf_Policies,A2AvectorWfftw,A2AvectorVfftw> > con_pi1_pi2;//(tpi_sampled); //y is associated with pi1, z with pi2 std::vector< A2AmesonField<mf_Policies,A2AvectorWfftw,A2AvectorVfftw> > con_pi2_pi1; //(tpi_sampled); //y is associated with pi2, z with pi1 type2_compute_mfproducts(con_pi1_pi2,con_pi2_pi1,tsep_pion,tstep,p_pi_1_all,mf_pions, Lt, tpi_sampled); for(int top_loc = 0; top_loc < GJP.TnodeSites(); top_loc++){ const int top_glb = top_loc + GJP.TnodeCoor()*GJP.TnodeSites(); #ifndef DISABLE_TYPE2_SPLIT_VMV //Split the vector-mesonfield outer product into two stages where in the first we reorder the mesonfield to optimize cache hits std::vector<mult_vMv_split<mf_Policies,A2AvectorV,A2AvectorWfftw,A2AvectorWfftw,A2AvectorV> > mult_vMv_split_part1; //[t_K_all.size()]; std::vector<mult_vMv_split<mf_Policies,A2AvectorV,A2AvectorWfftw,A2AvectorVfftw,A2AvectorW> > mult_vMv_split_part2_pi1_pi2; //[tpi_sampled]; std::vector<mult_vMv_split<mf_Policies,A2AvectorV,A2AvectorWfftw,A2AvectorVfftw,A2AvectorW> > mult_vMv_split_part2_pi2_pi1; //[tpi_sampled]; type2_mult_vMv_setup(mult_vMv_split_part1,mult_vMv_split_part2_pi1_pi2,mult_vMv_split_part2_pi2_pi1,con_pi1_pi2,con_pi2_pi1,vL,vH,wL,mf_kaon,t_K_all,top_loc,tstep, Lt,tpi_sampled,node_top_used,node_top_used_kaon); # ifndef DISABLE_TYPE2_PRECOMPUTE //Contract on all 3d sites on this node with fixed operator time coord top_glb into a canonically ordered output vector std::vector<SCFmatVector > mult_vMv_contracted_part1; //[t_K_all.size()][x3d]; std::vector<SCFmatVector > mult_vMv_contracted_part2_pi1_pi2; //[tpi_sampled][x3d]; std::vector<SCFmatVector > mult_vMv_contracted_part2_pi2_pi1; //[tpi_sampled][x3d]; type2_precompute_part1_part2(mult_vMv_contracted_part1,mult_vMv_contracted_part2_pi1_pi2,mult_vMv_contracted_part2_pi2_pi1, mult_vMv_split_part1,mult_vMv_split_part2_pi1_pi2,mult_vMv_split_part2_pi2_pi1, t_K_all,top_loc,tstep,Lt,tpi_sampled,node_top_used,node_top_used_kaon); # endif #endif //Now loop over Q_i insertion location. Each node naturally has its own sublattice to work on. Thread over sites in usual way #pragma omp parallel for for(int xop3d_loc = 0; xop3d_loc < size_3d; xop3d_loc++){ int thread_id = omp_get_thread_num(); //Part 1 does not care about the location of the pion, only that of the kaon. It may be used multiple times if we have multiple K->pi seps, so compute it separately. SCFmatVector part1_storage(t_K_all.size()); for(int tkidx=0; tkidx < t_K_all.size(); tkidx++){ if(!node_top_used_kaon[tkidx][top_loc]) continue; int t_K = t_K_all[tkidx]; //Compute part 1 // = \sum_{ \vec x_K } \Gamma_1 vL(x_op) [[ wL^dag(x_K) wH(x_K) ]] [vH(x_op)]^dag \gamma^5 SCFmat &part1 = part1_storage[tkidx]; #if defined(DISABLE_TYPE2_SPLIT_VMV) mult(part1, vL, mf_kaon[t_K], vH, xop3d_loc, top_loc, false, true); #elif defined(DISABLE_TYPE2_PRECOMPUTE) mult_vMv_split_part1[tkidx].contract(part1,xop3d_loc,false,true); #else part1 = mult_vMv_contracted_part1[tkidx][xop3d_loc]; #endif part1.gr(-5); //right multiply by g5 } //for(int t_pi1 = 0; t_pi1 < Lt; t_pi1 += tstep){ //my sensible ordering for(int t_pi1_lin = 1; t_pi1_lin <= Lt; t_pi1_lin += tstep){ //Daiqian's weird ordering int t_pi1 = modLt(t_pi1_lin,Lt); int t_pi1_idx = t_pi1 / tstep; int t_pi2 = modLt(t_pi1 + tsep_pion, Lt); if(!node_top_used[t_pi1_idx][top_loc]) continue; //skip unused timeslices //Construct part 2 (this doesn't involve the kaon): // \sum_{ \vec y, \vec z } \Gamma_2 vL(x_op) [[ wL^dag(y) S_2 vL(y) ]] [[ wL^dag(z) S_2 vL(z) ]] wL^dag(x_op) //SCFmat part2[2]; SCFmatVector part2(2); #if defined(DISABLE_TYPE2_SPLIT_VMV) mult(part2[0], vL, con_pi1_pi2[t_pi1_idx], wL, xop3d_loc, top_loc, false, true); //part2 goes from insertion to pi1 to pi2 and back to insertion mult(part2[1], vL, con_pi2_pi1[t_pi1_idx], wL, xop3d_loc, top_loc, false, true); //part2 goes from insertion to pi2 to pi1 and back to insertion #elif defined(DISABLE_TYPE2_PRECOMPUTE) mult_vMv_split_part2_pi1_pi2[t_pi1_idx].contract(part2[0],xop3d_loc,false,true); mult_vMv_split_part2_pi2_pi1[t_pi1_idx].contract(part2[1],xop3d_loc,false,true); #else part2[0] = mult_vMv_contracted_part2_pi1_pi2[t_pi1_idx][xop3d_loc]; part2[1] = mult_vMv_contracted_part2_pi2_pi1[t_pi1_idx][xop3d_loc]; #endif for(int tkpi_idx = 0; tkpi_idx < tsep_k_pi.size(); tkpi_idx++){ int t_K = modLt(t_pi1 - tsep_k_pi[tkpi_idx], Lt); int t_dis = modLt(top_glb - t_K, Lt); //distance between kaon and operator is the output time coordinate if(t_dis >= tsep_k_pi[tkpi_idx] || t_dis == 0) continue; //don't bother computing operator insertion locations outside of the region between the kaon and first pion or on top of either operator const SCFmat &part1 = part1_storage[tkidx_map[t_K]]; type2_contract(result[tkpi_idx],t_K,t_dis,thread_id,part1,part2); } }//tpi1 loop }//xop3d_loc loop }//top_loc loop for(int tkp=0;tkp<tsep_k_pi.size();tkp++){ result[tkp].threadSum(); result[tkp].nodeSum(); #ifndef DAIQIAN_COMPATIBILITY_MODE result[tkp] *= Float(0.5); //coefficient of 0.5 associated with average over pt2 pion ordering #endif } } CPS_END_NAMESPACE #endif
core_slantr.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/core_blas/core_zlantr.c, normal z -> s, Fri Sep 28 17:38:21 2018 * **/ #include <plasma_core_blas.h> #include "plasma_types.h" #include "plasma_internal.h" #include "core_lapack.h" #include <math.h> /******************************************************************************/ __attribute__((weak)) void plasma_core_slantr(plasma_enum_t norm, plasma_enum_t uplo, plasma_enum_t diag, int m, int n, const float *A, int lda, float *work, float *value) { // Due to a bug in LAPACKE < 3.6.1, this function always returns zero. // *value = LAPACKE_slantr_work(LAPACK_COL_MAJOR, // lapack_const(norm), lapack_const(uplo), // lapack_const(diag), // m, n, A, lda, work); // Calling LAPACK directly instead. char nrm = lapack_const(norm); char upl = lapack_const(uplo); char dia = lapack_const(diag); *value = LAPACK_slantr(&nrm, &upl, &dia, &m, &n, A, &lda, work); } /******************************************************************************/ void plasma_core_omp_slantr(plasma_enum_t norm, plasma_enum_t uplo, plasma_enum_t diag, int m, int n, const float *A, int lda, float *work, float *value, plasma_sequence_t *sequence, plasma_request_t *request) { #pragma omp task depend(in:A[0:lda*n]) \ depend(out:value[0:1]) { if (sequence->status == PlasmaSuccess) plasma_core_slantr(norm, uplo, diag, m, n, A, lda, work, value); } } /******************************************************************************/ void plasma_core_omp_slantr_aux(plasma_enum_t norm, plasma_enum_t uplo, plasma_enum_t diag, int m, int n, const float *A, int lda, float *value, plasma_sequence_t *sequence, plasma_request_t *request) { switch (norm) { case PlasmaOneNorm: #pragma omp task depend(in:A[0:lda*n]) \ depend(out:value[0:n]) { if (sequence->status == PlasmaSuccess) { if (uplo == PlasmaUpper) { if (diag == PlasmaNonUnit) { for (int j = 0; j < n; j++) { value[j] = fabsf(A[lda*j]); for (int i = 1; i < imin(j+1, m); i++) { value[j] += fabsf(A[lda*j+i]); } } } else { // PlasmaUnit int j; for (j = 0; j < imin(n, m); j++) { value[j] = 1.0; for (int i = 0; i < j; i++) { value[j] += fabsf(A[lda*j+i]); } } for (; j < n; j++) { value[j] = fabsf(A[lda*j]); for (int i = 1; i < m; i++) { value[j] += fabsf(A[lda*j+i]); } } } } else { // PlasmaLower if (diag == PlasmaNonUnit) { int j; for (j = 0; j < imin(n, m); j++) { value[j] = fabsf(A[lda*j+j]); for (int i = j+1; i < m; i++) { value[j] += fabsf(A[lda*j+i]); } } for (; j < n; j++) value[j] = 0.0; } else { // PlasmaUnit int j; for (j = 0; j < imin(n, m); j++) { value[j] = 1.0; for (int i = j+1; i < m; i++) { value[j] += fabsf(A[lda*j+i]); } } for (; j < n; j++) value[j] = 0.0; } } } } break; case PlasmaInfNorm: #pragma omp task depend(in:A[0:lda*n]) \ depend(out:value[0:m]) { if (sequence->status == PlasmaSuccess) { if (uplo == PlasmaUpper) { if (diag == PlasmaNonUnit) { for (int i = 0; i < m; i++) value[i] = 0.0; for (int j = 0; j < n; j++) { for (int i = 0; i < imin(j+1, m); i++) { value[i] += fabsf(A[lda*j+i]); } } } else { // PlasmaUnit int i; for (i = 0; i < imin(m, n); i++) value[i] = 1.0; for (; i < m; i++) value[i] = 0.0; int j; for (j = 0; j < imin(n, m); j++) { for (i = 0; i < j; i++) { value[i] += fabsf(A[lda*j+i]); } } for (; j < n; j++) { for (i = 0; i < m; i++) { value[i] += fabsf(A[lda*j+i]); } } } } else { // PlasmaLower if (diag == PlasmaNonUnit) { for (int i = 0; i < m; i++) value[i] = 0.0; for (int j = 0; j < imin(n, m); j++) { for (int i = j; i < m; i++) { value[i] += fabsf(A[lda*j+i]); } } } else { // PlasmaUnit int i; for (i = 0; i < imin(m, n); i++) value[i] = 1.0; for (; i < m; i++) value[i] = 0.0; for (int j = 0; j < imin(n, m); j++) { for (i = j+1; i < m; i++) { value[i] += fabsf(A[lda*j+i]); } } } } } } break; } }
resource_manager.h
// ----------------------------------------------------------------------------- // // Copyright (C) The BioDynaMo Project. // All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // // See the LICENSE file distributed with this work for details. // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. // // ----------------------------------------------------------------------------- #ifndef RESOURCE_MANAGER_H_ #define RESOURCE_MANAGER_H_ #include <Rtypes.h> #include <limits> #include <memory> #include <ostream> #include <string> #include <tuple> #include <utility> #include <vector> #ifdef USE_OPENCL #define __CL_ENABLE_EXCEPTIONS #ifdef __APPLE__ #include <OpenCL/cl.hpp> #else #include <CL/cl.hpp> #endif #endif #include "backend.h" #include "diffusion_grid.h" #include "tuple_util.h" #include "variadic_template_parameter_util.h" namespace bdm { /// Unique identifier of a simulation object. Acts as a type erased pointer. /// Has the same type for every simulation object. /// The id is split into two parts: Type index and element index. /// The first one is used to obtain the container in the ResourceManager, the /// second specifies the element within this vector. class SoHandle { public: constexpr SoHandle() noexcept : type_idx_(std::numeric_limits<decltype(type_idx_)>::max()), element_idx_(std::numeric_limits<decltype(element_idx_)>::max()) {} SoHandle(uint16_t type_idx, uint32_t element_idx) : type_idx_(type_idx), element_idx_(element_idx) {} uint16_t GetTypeIdx() const { return type_idx_; } uint32_t GetElementIdx() const { return element_idx_; } void SetElementIdx(uint32_t element_idx) { element_idx_ = element_idx; } bool operator==(const SoHandle& other) const { return type_idx_ == other.type_idx_ && element_idx_ == other.element_idx_; } bool operator!=(const SoHandle& other) const { return !(*this == other); } bool operator<(const SoHandle& other) const { if (type_idx_ == other.type_idx_) { return element_idx_ < other.element_idx_; } else { return type_idx_ < other.type_idx_; } } friend std::ostream& operator<<(std::ostream& stream, const SoHandle& handle) { stream << "Type idx: " << handle.type_idx_ << " element idx: " << handle.element_idx_; return stream; } private: // TODO(lukas) add using TypeIdx_t = uint16_t and // using ElementIdx_t = uint32_t uint16_t type_idx_; /// changed element index to uint32_t after issues with std::atomic with /// size 16 -> max element_idx: 4.294.967.296 uint32_t element_idx_; ClassDefNV(SoHandle, 1); }; constexpr SoHandle kNullSoHandle; namespace detail { /// \see bdm::ConvertToContainerTuple, VariadicTypedef template <typename Backend, typename... Types> struct ConvertToContainerTuple {}; /// \see bdm::ConvertToContainerTuple, VariadicTypedef template <typename Backend, typename... Types> struct ConvertToContainerTuple<Backend, VariadicTypedef<Types...>> { // Helper alias to get the container type associated with Backend template <typename T> using Container = typename Backend::template Container<T>; // Helper type alias to get a type with certain Backend template <typename T> using ToBackend = typename T::template Self<Backend>; using type = std::tuple<Container<ToBackend<Types>>...>; // NOLINT }; /// Type trait to obtain the index of a type within a tuple. /// Required to extract variadic types from withi a `VariadicTypedef` template <typename TSo, typename... Types> struct ToIndex; template <typename TSo, typename... Types> struct ToIndex<TSo, VariadicTypedef<Types...>> { static constexpr uint16_t value = GetIndex<TSo, Types...>(); // NOLINT }; } // namespace detail /// Create a tuple of types in the parameter pack and wrap each type with /// container. /// @tparam Backend in which the variadic types should be stored in /// @tparam TVariadicTypedefWrapper type that wraps a VariadicTypedef /// which in turn contains the variadic template parameters /// \see VariadicTypedefWrapper template <typename Backend, typename TVariadicTypedef> struct ConvertToContainerTuple { typedef typename detail::ConvertToContainerTuple<Backend, TVariadicTypedef>::type type; // NOLINT }; /// Forward declaration for concrete compile time parameter. /// Will be used as default template parameter. template <typename TBackend = Soa> struct CompileTimeParam; /// ResourceManager holds a container for each atomic type in the simulation. /// It provides methods to get a certain container, execute a function on a /// a certain element, all elements of a certain type or all elements inside /// the ResourceManager. Elements are uniquely identified with its SoHandle. /// Furthermore, the types specified in AtomicTypes are backend invariant /// Hence it doesn't matter which version of the Backend is specified. /// ResourceManager internally uses the TBackendWrapper parameter to convert /// all atomic types to the desired backend. /// This makes user code easier since atomic types can be specified as scalars. /// @tparam TCompileTimeParam type that containes the compile time parameter for /// a specific simulation. ResourceManager extracts Backend and AtomicTypes. template <typename TCompileTimeParam = CompileTimeParam<>> class ResourceManager { public: using Backend = typename TCompileTimeParam::SimulationBackend; using Types = typename TCompileTimeParam::AtomicTypes; /// Determine Container based on the Backend template <typename T> using TypeContainer = typename Backend::template Container<T>; /// Helper type alias to get a type with certain Backend template <typename T> using ToBackend = typename T::template Self<Backend>; /// Singleton pattern - return the only instance with this template parameters static ResourceManager<TCompileTimeParam>* Get() { return instance_.get(); } /// Return the container of this Type /// @tparam Type atomic type whose container should be returned /// invariant to the Backend. This means that even if ResourceManager /// stores e.g. `SoaCell`, Type can be `Cell` and still returns the /// correct container. template <typename Type> TypeContainer<ToBackend<Type>>* Get() { return &std::get<TypeContainer<ToBackend<Type>>>(data_); } /// Return the container of diffusion grids std::vector<DiffusionGrid*>& GetDiffusionGrids() { return diffusion_grids_; } /// Return the diffusion grid which holds the substance of specified id DiffusionGrid* GetDiffusionGrid(size_t substance_id) { assert(substance_id < diffusion_grids_.size() && "You tried to access a diffusion grid that does not exist!"); return diffusion_grids_[substance_id]; } /// Return the diffusion grid which holds the substance of specified name DiffusionGrid* GetDiffusionGrid(std::string substance_name) { for (auto dg : diffusion_grids_) { if (dg->GetSubstanceName() == substance_name) { return dg; } } return nullptr; } /// Returns the total number of simulation objects size_t GetNumSimObjects() { size_t num_so = 0; for (uint16_t i = 0; i < std::tuple_size<decltype(data_)>::value; i++) { ::bdm::Apply(&data_, i, [&](auto* container) { num_so += container->size(); }); } return num_so; } /// Default constructor. Unfortunately needs to be public although it is /// a singleton to be able to use ROOT I/O ResourceManager() { // Soa container contain one element upon construction Clear(); } /// Free the memory that was reserved for the diffusion grids virtual ~ResourceManager() { for (auto grid : diffusion_grids_) { delete grid; } } /// Apply a function on a certain element /// @param handle - simulation object id; specifies the tuple index and /// element index \see SoHandle /// @param function that will be called with the element as a parameter /// /// rm->ApplyOnElement(handle, [](auto& element) { /// std::cout << element << std::endl; /// }); template <typename TFunction> auto ApplyOnElement(SoHandle handle, TFunction&& function) { auto type_idx = handle.GetTypeIdx(); auto element_idx = handle.GetElementIdx(); return ::bdm::Apply(&data_, type_idx, [&](auto* container) -> decltype( function((*container)[0])) { return function((*container)[element_idx]); }); } /// Apply a function on all container types /// @param function that will be called with each container as a parameter /// /// rm->ApplyOnAllTypes([](auto* container, uint16_t type_idx) { /// std::cout << container->size() << std::endl; /// }); template <typename TFunction> void ApplyOnAllTypes(TFunction&& function) { // runtime dispatch - TODO(lukas) replace with c++17 std::apply for (uint16_t i = 0; i < std::tuple_size<decltype(data_)>::value; i++) { ::bdm::Apply(&data_, i, [&](auto* container) { function(container, i); }); } } /// Apply a function on all container types. Function invocations are /// parallelized /// @param function that will be called with each container as a parameter /// /// rm->ApplyOnAllTypes([](auto* container, uint16_t type_idx) { /// std::cout << container->size() << std::endl; /// }); template <typename TFunction> void ApplyOnAllTypesParallel(TFunction&& function) { // runtime dispatch - TODO(lukas) replace with c++17 std::apply for (uint16_t i = 0; i < std::tuple_size<decltype(data_)>::value; i++) { ::bdm::Apply(&data_, i, [&](auto* container) { function(container, i); }); } } /// Apply a function on all elements in every container /// @param function that will be called with each container as a parameter /// /// rm->ApplyOnAllElements([](auto& element, SoHandle handle) { /// std::cout << element << std::endl; /// }); template <typename TFunction> void ApplyOnAllElements(TFunction&& function) { // runtime dispatch - TODO(lukas) replace with c++17 std::apply for (uint16_t i = 0; i < std::tuple_size<decltype(data_)>::value; i++) { ::bdm::Apply(&data_, i, [&](auto* container) { for (size_t e = 0; e < container->size(); e++) { function((*container)[e], SoHandle(i, e)); } }); } } /// Apply a function on all elements in every container /// Function invocations are parallelized /// \see ApplyOnAllElements template <typename TFunction> void ApplyOnAllElementsParallel(TFunction&& function) { // runtime dispatch - TODO(lukas) replace with c++17 std::apply for (uint16_t i = 0; i < std::tuple_size<decltype(data_)>::value; i++) { ::bdm::Apply(&data_, i, [&](auto* container) { #pragma omp parallel for for (size_t e = 0; e < container->size(); e++) { function((*container)[e], SoHandle(i, e)); } }); } } /// Remove elements from each type void Clear() { ApplyOnAllTypes( [](auto* container, uint16_t type_idx) { container->clear(); }); } template <typename TSo> void push_back(const TSo& so) { // NOLINT Get<TSo>()->push_back(so); } #ifdef USE_OPENCL cl::Context* GetOpenCLContext() { return &opencl_context_; } cl::CommandQueue* GetOpenCLCommandQueue() { return &opencl_command_queue_; } std::vector<cl::Device>* GetOpenCLDeviceList() { return &opencl_devices_; } std::vector<cl::Program>* GetOpenCLProgramList() { return &opencl_programs_; } #endif /// Create a new simulation object and return a reference to it. /// @tparam TScalarSo simulation object type with scalar backend /// @param args arguments which will be forwarded to the TScalarSo constructor /// @remarks Note that this function is not thread safe. template <typename TScalarSo, typename... Args, typename TBackend = Backend> typename std::enable_if<std::is_same<TBackend, Soa>::value, typename TScalarSo::template Self<SoaRef>>::type New(Args... args) { auto container = Get<TScalarSo>(); auto idx = container->DelayedPushBack(TScalarSo(std::forward<Args>(args)...)); return (*container)[idx]; } template <typename TScalarSo, typename... Args, typename TBackend = Backend> typename std::enable_if<std::is_same<TBackend, Scalar>::value, TScalarSo&>::type New(Args... args) { auto container = Get<TScalarSo>(); auto idx = container->DelayedPushBack(TScalarSo(std::forward<Args>(args)...)); return (*container)[idx]; } /// Returns the number of simulation object types static constexpr size_t NumberOfTypes() { return std::tuple_size<decltype(data_)>::value; } template <typename TSo> static constexpr uint16_t GetTypeIndex() { return detail::ToIndex<TSo, Types>::value; } private: static std::unique_ptr<ResourceManager<TCompileTimeParam>> instance_; /// creates one container for each type in Types. /// Container type is determined based on the specified Backend typename ConvertToContainerTuple<Backend, Types>::type data_; std::vector<DiffusionGrid*> diffusion_grids_; #ifdef USE_OPENCL cl::Context opencl_context_; //! cl::CommandQueue opencl_command_queue_; //! // Currently only support for one GPU device std::vector<cl::Device> opencl_devices_; //! std::vector<cl::Program> opencl_programs_; //! #endif friend class SimulationBackup; ClassDefNV(ResourceManager, 1); }; template <typename T> std::unique_ptr<ResourceManager<T>> ResourceManager<T>::instance_ = std::unique_ptr<ResourceManager<T>>(new ResourceManager<T>()); /// Returns the ResourceManager template <typename TResourceManager = ResourceManager<>> TResourceManager* Rm() { return TResourceManager::Get(); } } // namespace bdm #endif // RESOURCE_MANAGER_H_
dynmat.c
/* Copyright (C) 2015 Atsushi Togo */ /* All rights reserved. */ /* This file is part of phonopy. */ /* 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 the name of the phonopy project 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 <math.h> #include <stdlib.h> #include <dynmat.h> #define PI 3.14159265358979323846 static void get_dynmat_ij(double *dynamical_matrix, const int num_patom, const int num_satom, const double *fc, const double q[3], PHPYCONST double (*svecs)[27][3], const int *multi, const double *mass, const int *s2p_map, const int *p2s_map, PHPYCONST double (*charge_sum)[3][3], const int i, const int j); static void get_dm(double dm_real[3][3], double dm_imag[3][3], const int num_patom, const int num_satom, const double *fc, const double q[3], PHPYCONST double (*svecs)[27][3], const int *multi, const int *p2s_map, PHPYCONST double (*charge_sum)[3][3], const int i, const int j, const int k); static double get_dielectric_part(const double q_cart[3], PHPYCONST double dielectric[3][3]); static void get_KK(double *dd_part, /* [natom, 3, natom, 3, (real,imag)] */ PHPYCONST double (*G_list)[3], /* [num_G, 3] */ const int num_G, const int num_patom, const double q_cart[3], const double *q_direction_cart, PHPYCONST double dielectric[3][3], PHPYCONST double (*pos)[3], /* [num_patom, 3] */ const double lambda, const double tolerance); static void make_Hermitian(double *mat, const int num_band); static void multiply_borns(double *dd, const double *dd_in, const int num_patom, PHPYCONST double (*born)[3][3]); int dym_get_dynamical_matrix_at_q(double *dynamical_matrix, const int num_patom, const int num_satom, const double *fc, const double q[3], PHPYCONST double (*svecs)[27][3], const int *multi, const double *mass, const int *s2p_map, const int *p2s_map, PHPYCONST double (*charge_sum)[3][3], const int with_openmp) { int i, j, ij; if (with_openmp) { #pragma omp parallel for for (ij = 0; ij < num_patom * num_patom ; ij++) { get_dynmat_ij(dynamical_matrix, num_patom, num_satom, fc, q, svecs, multi, mass, s2p_map, p2s_map, charge_sum, ij / num_patom, /* i */ ij % num_patom); /* j */ } } else { for (i = 0; i < num_patom; i++) { for (j = 0; j < num_patom; j++) { get_dynmat_ij(dynamical_matrix, num_patom, num_satom, fc, q, svecs, multi, mass, s2p_map, p2s_map, charge_sum, i, j); } } } make_Hermitian(dynamical_matrix, num_patom * 3); return 0; } void dym_get_dipole_dipole(double *dd, /* [natom, 3, natom, 3, (real,imag)] */ const double *dd_q0, /* [natom, 3, 3, (real,imag)] */ PHPYCONST double (*G_list)[3], /* [num_G, 3] */ const int num_G, const int num_patom, const double q_cart[3], const double *q_direction_cart, /* must be pointer */ PHPYCONST double (*born)[3][3], PHPYCONST double dielectric[3][3], PHPYCONST double (*pos)[3], /* [num_patom, 3] */ const double factor, /* 4pi/V*unit-conv */ const double lambda, const double tolerance) { int i, k, l, adrs, adrs_sum; double *dd_tmp; dd_tmp = NULL; dd_tmp = (double*) malloc(sizeof(double) * num_patom * num_patom * 18); for (i = 0; i < num_patom * num_patom * 18; i++) { dd[i] = 0; dd_tmp[i] = 0; } get_KK(dd_tmp, G_list, num_G, num_patom, q_cart, q_direction_cart, dielectric, pos, lambda, tolerance); multiply_borns(dd, dd_tmp, num_patom, born); for (i = 0; i < num_patom; i++) { for (k = 0; k < 3; k++) { /* alpha */ for (l = 0; l < 3; l++) { /* beta */ adrs = i * num_patom * 9 + k * num_patom * 3 + i * 3 + l; adrs_sum = i * 9 + k * 3 + l; dd[adrs * 2] -= dd_q0[adrs_sum * 2]; dd[adrs * 2 + 1] -= dd_q0[adrs_sum * 2 + 1]; } } } for (i = 0; i < num_patom * num_patom * 18; i++) { dd[i] *= factor; } /* This may not be necessary. */ make_Hermitian(dd, num_patom * 3); free(dd_tmp); dd_tmp = NULL; } void dym_get_dipole_dipole_q0(double *dd_q0, /* [natom, 3, 3, (real,imag)] */ PHPYCONST double (*G_list)[3], /* [num_G, 3] */ const int num_G, const int num_patom, PHPYCONST double (*born)[3][3], PHPYCONST double dielectric[3][3], PHPYCONST double (*pos)[3], /* [num_patom, 3] */ const double lambda, const double tolerance) { int i, j, k, l, adrs_tmp, adrs, adrsT; double zero_vec[3]; double *dd_tmp1, *dd_tmp2; dd_tmp1 = NULL; dd_tmp1 = (double*) malloc(sizeof(double) * num_patom * num_patom * 18); dd_tmp2 = NULL; dd_tmp2 = (double*) malloc(sizeof(double) * num_patom * num_patom * 18); for (i = 0; i < num_patom * num_patom * 18; i++) { dd_tmp1[i] = 0; dd_tmp2[i] = 0; } zero_vec[0] = 0; zero_vec[1] = 0; zero_vec[2] = 0; get_KK(dd_tmp1, G_list, num_G, num_patom, zero_vec, NULL, dielectric, pos, lambda, tolerance); multiply_borns(dd_tmp2, dd_tmp1, num_patom, born); for (i = 0; i < num_patom * 18; i++) { dd_q0[i] = 0; } for (i = 0; i < num_patom; i++) { for (k = 0; k < 3; k++) { /* alpha */ for (l = 0; l < 3; l++) { /* beta */ adrs = i * 9 + k * 3 + l; for (j = 0; j < num_patom; j++) { adrs_tmp = i * num_patom * 9 + k * num_patom * 3 + j * 3 + l ; dd_q0[adrs * 2] += dd_tmp2[adrs_tmp * 2]; dd_q0[adrs * 2 + 1] += dd_tmp2[adrs_tmp * 2 + 1]; } } } } for (i = 0; i < num_patom; i++) { for (k = 0; k < 3; k++) { /* alpha */ for (l = 0; l < 3; l++) { /* beta */ adrs = i * 9 + k * 3 + l; adrsT = i * 9 + l * 3 + k; dd_q0[adrs * 2] += dd_q0[adrsT * 2]; dd_q0[adrs * 2] /= 2; dd_q0[adrsT * 2] = dd_q0[adrs * 2]; dd_q0[adrs * 2 + 1] -= dd_q0[adrsT * 2 + 1]; dd_q0[adrs * 2 + 1] /= 2; dd_q0[adrsT * 2 + 1] = -dd_q0[adrs * 2 + 1]; } } } free(dd_tmp1); dd_tmp1 = NULL; free(dd_tmp2); dd_tmp2 = NULL; } void dym_get_charge_sum(double (*charge_sum)[3][3], const int num_patom, const double factor, /* 4pi/V*unit-conv and denominator */ const double q_cart[3], PHPYCONST double (*born)[3][3]) { int i, j, k, a, b; double (*q_born)[3]; q_born = (double (*)[3]) malloc(sizeof(double[3]) * num_patom); for (i = 0; i < num_patom; i++) { for (j = 0; j < 3; j++) { q_born[i][j] = 0; } } for (i = 0; i < num_patom; i++) { for (j = 0; j < 3; j++) { for (k = 0; k < 3; k++) { q_born[i][j] += q_cart[k] * born[i][k][j]; } } } for (i = 0; i < num_patom; i++) { for (j = 0; j < num_patom; j++) { for (a = 0; a < 3; a++) { for (b = 0; b < 3; b++) { charge_sum[i * num_patom + j][a][b] = q_born[i][a] * q_born[j][b] * factor; } } } } free(q_born); q_born = NULL; } /* fc[num_patom, num_satom, 3, 3] */ /* dm[num_comm_points, num_patom * 3, num_patom *3] */ /* comm_points[num_satom, num_patom, 27, 3] */ /* shortest_vectors[num_satom, num_patom, 27, 3] */ /* multiplicities[num_satom, num_patom] */ void dym_transform_dynmat_to_fc(double *fc, const double *dm, PHPYCONST double (*comm_points)[3], PHPYCONST double (*shortest_vectors)[27][3], const int *multiplicities, const double *masses, const int *s2pp_map, const int num_patom, const int num_satom) { int i, j, k, l, m, N, adrs, multi; double coef, phase, cos_phase, sin_phase; N = num_satom / num_patom; for (i = 0; i < num_patom * num_satom * 9; i++) { fc[i] = 0; } for (i = 0; i < num_patom; i++) { for (j = 0; j < num_satom; j++) { coef = sqrt(masses[i] * masses[s2pp_map[j]]) / N; for (k = 0; k < N; k++) { cos_phase = 0; sin_phase = 0; multi = multiplicities[j * num_patom + i]; for (l = 0; l < multi; l++) { phase = 0; for (m = 0; m < 3; m++) { phase -= comm_points[k][m] * shortest_vectors[j * num_patom + i][l][m]; } cos_phase += cos(phase * 2 * PI); sin_phase += sin(phase * 2 * PI); } cos_phase /= multi; sin_phase /= multi; for (l = 0; l < 3; l++) { for (m = 0; m < 3; m++) { adrs = k * num_patom * num_patom * 18 + i * num_patom * 18 + l * num_patom * 6 + s2pp_map[j] * 6 + m * 2; fc[i * num_satom * 9 + j * 9 + l * 3 + m] += (dm[adrs] * cos_phase - dm[adrs + 1] * sin_phase) * coef; } } } } } } static void get_dynmat_ij(double *dynamical_matrix, const int num_patom, const int num_satom, const double *fc, const double q[3], PHPYCONST double (*svecs)[27][3], const int *multi, const double *mass, const int *s2p_map, const int *p2s_map, PHPYCONST double (*charge_sum)[3][3], const int i, const int j) { int k, l, adrs; double mass_sqrt; double dm_real[3][3], dm_imag[3][3]; mass_sqrt = sqrt(mass[i] * mass[j]); for (k = 0; k < 3; k++) { for (l = 0; l < 3; l++) { dm_real[k][l] = 0; dm_imag[k][l] = 0; } } for (k = 0; k < num_satom; k++) { /* Lattice points of right index of fc */ if (s2p_map[k] != p2s_map[j]) { continue; } get_dm(dm_real, dm_imag, num_patom, num_satom, fc, q, svecs, multi, p2s_map, charge_sum, i, j, k); } for (k = 0; k < 3; k++) { for (l = 0; l < 3; l++) { adrs = (i * 3 + k) * num_patom * 3 + j * 3 + l; dynamical_matrix[adrs * 2] = dm_real[k][l] / mass_sqrt; dynamical_matrix[adrs * 2 + 1] = dm_imag[k][l] / mass_sqrt; } } } static void get_dm(double dm_real[3][3], double dm_imag[3][3], const int num_patom, const int num_satom, const double *fc, const double q[3], PHPYCONST double (*svecs)[27][3], const int *multi, const int *p2s_map, PHPYCONST double (*charge_sum)[3][3], const int i, const int j, const int k) { int l, m; double phase, cos_phase, sin_phase, fc_elem; cos_phase = 0; sin_phase = 0; for (l = 0; l < multi[k * num_patom + i]; l++) { phase = 0; for (m = 0; m < 3; m++) { phase += q[m] * svecs[k * num_patom + i][l][m]; } cos_phase += cos(phase * 2 * PI) / multi[k * num_patom + i]; sin_phase += sin(phase * 2 * PI) / multi[k * num_patom + i]; } for (l = 0; l < 3; l++) { for (m = 0; m < 3; m++) { if (charge_sum) { fc_elem = (fc[p2s_map[i] * num_satom * 9 + k * 9 + l * 3 + m] + charge_sum[i * num_patom + j][l][m]); } else { fc_elem = fc[p2s_map[i] * num_satom * 9 + k * 9 + l * 3 + m]; } dm_real[l][m] += fc_elem * cos_phase; dm_imag[l][m] += fc_elem * sin_phase; } } } static double get_dielectric_part(const double q_cart[3], PHPYCONST double dielectric[3][3]) { int i, j; double x[3]; double sum; for (i = 0; i < 3; i++) { x[i] = 0; for (j = 0; j < 3; j++) { x[i] += dielectric[i][j] * q_cart[j]; } } sum = 0; for (i = 0; i < 3; i++) { sum += q_cart[i] * x[i]; } return sum; } static void get_KK(double *dd_part, /* [natom, 3, natom, 3, (real,imag)] */ PHPYCONST double (*G_list)[3], /* [num_G, 3] */ const int num_G, const int num_patom, const double q_cart[3], const double *q_direction_cart, PHPYCONST double dielectric[3][3], PHPYCONST double (*pos)[3], /* [num_patom, 3] */ const double lambda, const double tolerance) { int i, j, k, l, g, adrs; double q_K[3]; double norm, cos_phase, sin_phase, phase, dielectric_part, exp_damp, L2; double KK[3][3]; L2 = 4 * lambda * lambda; /* sum over K = G + q and over G (i.e. q=0) */ /* q_direction has values for summation over K at Gamma point. */ /* q_direction is NULL for summation over G */ for (g = 0; g < num_G; g++) { norm = 0; for (i = 0; i < 3; i++) { q_K[i] = G_list[g][i] + q_cart[i]; norm += q_K[i] * q_K[i]; } if (sqrt(norm) < tolerance) { if (!q_direction_cart) { continue; } else { dielectric_part = get_dielectric_part(q_direction_cart, dielectric); for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { KK[i][j] = q_direction_cart[i] * q_direction_cart[j] / dielectric_part; } } } } else { dielectric_part = get_dielectric_part(q_K, dielectric); exp_damp = exp(-dielectric_part / L2); for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { KK[i][j] = q_K[i] * q_K[j] / dielectric_part * exp_damp; } } } for (i = 0; i < num_patom; i++) { for (j = 0; j < num_patom; j++) { phase = 0; for (k = 0; k < 3; k++) { /* For D-type dynamical matrix */ /* phase += (pos[i][k] - pos[j][k]) * q_K[k]; */ /* For C-type dynamical matrix */ phase += (pos[i][k] - pos[j][k]) * G_list[g][k]; } phase *= 2 * PI; cos_phase = cos(phase); sin_phase = sin(phase); for (k = 0; k < 3; k++) { for (l = 0; l < 3; l++) { adrs = i * num_patom * 9 + k * num_patom * 3 + j * 3 + l; dd_part[adrs * 2] += KK[k][l] * cos_phase; dd_part[adrs * 2 + 1] += KK[k][l] * sin_phase; } } } } } } static void make_Hermitian(double *mat, const int num_band) { int i, j, adrs, adrsT; for (i = 0; i < num_band; i++) { for (j = i; j < num_band; j++) { adrs = i * num_band + j * 1; adrs *= 2; adrsT = j * num_band + i * 1; adrsT *= 2; /* real part */ mat[adrs] += mat[adrsT]; mat[adrs] /= 2; /* imaginary part */ mat[adrs + 1] -= mat[adrsT+ 1]; mat[adrs + 1] /= 2; /* store */ mat[adrsT] = mat[adrs]; mat[adrsT + 1] = -mat[adrs + 1]; } } } static void multiply_borns(double *dd, const double *dd_in, const int num_patom, PHPYCONST double (*born)[3][3]) { int i, j, k, l, m, n, adrs, adrs_in; double zz; for (i = 0; i < num_patom; i++) { for (j = 0; j < num_patom; j++) { for (k = 0; k < 3; k++) { /* alpha */ for (l = 0; l < 3; l++) { /* beta */ adrs = i * num_patom * 9 + k * num_patom * 3 + j * 3 + l; for (m = 0; m < 3; m++) { /* alpha' */ for (n = 0; n < 3; n++) { /* beta' */ adrs_in = i * num_patom * 9 + m * num_patom * 3 + j * 3 + n ; zz = born[i][m][k] * born[j][n][l]; dd[adrs * 2] += dd_in[adrs_in * 2] * zz; dd[adrs * 2 + 1] += dd_in[adrs_in * 2 + 1] * zz; } } } } } } }
layer.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % L AAA Y Y EEEEE RRRR % % L A A Y Y E R R % % L AAAAA Y EEE RRRR % % L A A Y E R R % % LLLLL A A Y EEEEE R R % % % % MagickCore Image Layering Methods % % % % Software Design % % Cristy % % Anthony Thyssen % % January 2006 % % % % % % Copyright @ 2006 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % 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 declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/composite.h" #include "MagickCore/effect.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/layer.h" #include "MagickCore/list.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/profile.h" #include "MagickCore/resource_.h" #include "MagickCore/resize.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #include "MagickCore/transform.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l e a r B o u n d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClearBounds() Clear the area specified by the bounds in an image to % transparency. This typically used to handle Background Disposal for the % previous frame in an animation sequence. % % Warning: no bounds checks are performed, except for the null or missed % image, for images that don't change. in all other cases bound must fall % within the image. % % The format is: % % void ClearBounds(Image *image,RectangleInfo *bounds, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image to had the area cleared in % % o bounds: the area to be clear within the imag image % % o exception: return any errors or warnings in this structure. % */ static void ClearBounds(Image *image,RectangleInfo *bounds, ExceptionInfo *exception) { ssize_t y; if (bounds->x < 0) return; if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); for (y=0; y < (ssize_t) bounds->height; y++) { ssize_t x; Quantum *magick_restrict q; q=GetAuthenticPixels(image,bounds->x,bounds->y+y,bounds->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) bounds->width; x++) { SetPixelAlpha(image,TransparentAlpha,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I s B o u n d s C l e a r e d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsBoundsCleared() tests whether any pixel in the bounds given, gets cleared % when going from the first image to the second image. This typically used % to check if a proposed disposal method will work successfully to generate % the second frame image from the first disposed form of the previous frame. % % Warning: no bounds checks are performed, except for the null or missed % image, for images that don't change. in all other cases bound must fall % within the image. % % The format is: % % MagickBooleanType IsBoundsCleared(const Image *image1, % const Image *image2,RectangleInfo bounds,ExceptionInfo *exception) % % A description of each parameter follows: % % o image1, image 2: the images to check for cleared pixels % % o bounds: the area to be clear within the imag image % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType IsBoundsCleared(const Image *image1, const Image *image2,RectangleInfo *bounds,ExceptionInfo *exception) { const Quantum *p, *q; ssize_t x; ssize_t y; if (bounds->x < 0) return(MagickFalse); for (y=0; y < (ssize_t) bounds->height; y++) { p=GetVirtualPixels(image1,bounds->x,bounds->y+y,bounds->width,1,exception); q=GetVirtualPixels(image2,bounds->x,bounds->y+y,bounds->width,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) bounds->width; x++) { if ((GetPixelAlpha(image1,p) >= (Quantum) (QuantumRange/2)) && (GetPixelAlpha(image2,q) < (Quantum) (QuantumRange/2))) break; p+=GetPixelChannels(image1); q+=GetPixelChannels(image2); } if (x < (ssize_t) bounds->width) break; } return(y < (ssize_t) bounds->height ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o a l e s c e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CoalesceImages() composites a set of images while respecting any page % offsets and disposal methods. GIF, MIFF, and MNG animation sequences % typically start with an image background and each subsequent image % varies in size and offset. A new image sequence is returned with all % images the same size as the first images virtual canvas and composited % with the next image in the sequence. % % The format of the CoalesceImages method is: % % Image *CoalesceImages(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image sequence. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CoalesceImages(const Image *image,ExceptionInfo *exception) { Image *coalesce_image, *dispose_image, *previous; Image *next; RectangleInfo bounds; /* Coalesce the image sequence. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); next=GetFirstImageInList(image); bounds=next->page; if (bounds.width == 0) { bounds.width=next->columns; if (bounds.x > 0) bounds.width+=bounds.x; } if (bounds.height == 0) { bounds.height=next->rows; if (bounds.y > 0) bounds.height+=bounds.y; } bounds.x=0; bounds.y=0; coalesce_image=CloneImage(next,bounds.width,bounds.height,MagickTrue, exception); if (coalesce_image == (Image *) NULL) return((Image *) NULL); coalesce_image->background_color.alpha_trait=BlendPixelTrait; coalesce_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(coalesce_image,exception); coalesce_image->alpha_trait=next->alpha_trait; coalesce_image->page=bounds; coalesce_image->dispose=NoneDispose; /* Coalesce rest of the images. */ dispose_image=CloneImage(coalesce_image,0,0,MagickTrue,exception); if (dispose_image == (Image *) NULL) { coalesce_image=DestroyImage(coalesce_image); return((Image *) NULL); } dispose_image->background_color.alpha_trait=BlendPixelTrait; (void) CompositeImage(coalesce_image,next,CopyCompositeOp,MagickTrue, next->page.x,next->page.y,exception); next=GetNextImageInList(next); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { const char *attribute; /* Determine the bounds that was overlaid in the previous image. */ previous=GetPreviousImageInList(next); bounds=previous->page; bounds.width=previous->columns; bounds.height=previous->rows; if (bounds.x < 0) { bounds.width+=bounds.x; bounds.x=0; } if ((ssize_t) (bounds.x+bounds.width) > (ssize_t) coalesce_image->columns) bounds.width=coalesce_image->columns-bounds.x; if (bounds.y < 0) { bounds.height+=bounds.y; bounds.y=0; } if ((ssize_t) (bounds.y+bounds.height) > (ssize_t) coalesce_image->rows) bounds.height=coalesce_image->rows-bounds.y; /* Replace the dispose image with the new coalesced image. */ if (GetPreviousImageInList(next)->dispose != PreviousDispose) { dispose_image=DestroyImage(dispose_image); dispose_image=CloneImage(coalesce_image,0,0,MagickTrue,exception); if (dispose_image == (Image *) NULL) { coalesce_image=DestroyImageList(coalesce_image); return((Image *) NULL); } dispose_image->background_color.alpha_trait=BlendPixelTrait; } /* Clear the overlaid area of the coalesced bounds for background disposal */ if (next->previous->dispose == BackgroundDispose) ClearBounds(dispose_image,&bounds,exception); /* Next image is the dispose image, overlaid with next frame in sequence. */ coalesce_image->next=CloneImage(dispose_image,0,0,MagickTrue,exception); coalesce_image->next->previous=coalesce_image; previous=coalesce_image; coalesce_image=GetNextImageInList(coalesce_image); coalesce_image->background_color.alpha_trait=BlendPixelTrait; attribute=GetImageProperty(next,"webp:mux-blend",exception); if (attribute == (const char *) NULL) (void) CompositeImage(coalesce_image,next, next->alpha_trait != UndefinedPixelTrait ? OverCompositeOp : CopyCompositeOp,MagickTrue,next->page.x,next->page.y,exception); else (void) CompositeImage(coalesce_image,next, LocaleCompare(attribute,"AtopBackgroundAlphaBlend") == 0 ? OverCompositeOp : CopyCompositeOp,MagickTrue,next->page.x,next->page.y, exception); (void) CloneImageProfiles(coalesce_image,next); (void) CloneImageProperties(coalesce_image,next); (void) CloneImageArtifacts(coalesce_image,next); coalesce_image->page=previous->page; /* If a pixel goes opaque to transparent, use background dispose. */ if (IsBoundsCleared(previous,coalesce_image,&bounds,exception) != MagickFalse) coalesce_image->dispose=BackgroundDispose; else coalesce_image->dispose=NoneDispose; previous->dispose=coalesce_image->dispose; } dispose_image=DestroyImage(dispose_image); return(GetFirstImageInList(coalesce_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D i s p o s e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DisposeImages() returns the coalesced frames of a GIF animation as it would % appear after the GIF dispose method of that frame has been applied. That is % it returned the appearance of each frame before the next is overlaid. % % The format of the DisposeImages method is: % % Image *DisposeImages(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *DisposeImages(const Image *images,ExceptionInfo *exception) { Image *dispose_image, *dispose_images; RectangleInfo bounds; Image *image, *next; /* Run the image through the animation sequence */ assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=GetFirstImageInList(images); dispose_image=CloneImage(image,image->page.width,image->page.height, MagickTrue,exception); if (dispose_image == (Image *) NULL) return((Image *) NULL); dispose_image->page=image->page; dispose_image->page.x=0; dispose_image->page.y=0; dispose_image->dispose=NoneDispose; dispose_image->background_color.alpha_trait=BlendPixelTrait; dispose_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(dispose_image,exception); dispose_images=NewImageList(); for (next=image; image != (Image *) NULL; image=GetNextImageInList(image)) { Image *current_image; /* Overlay this frame's image over the previous disposal image. */ current_image=CloneImage(dispose_image,0,0,MagickTrue,exception); if (current_image == (Image *) NULL) { dispose_images=DestroyImageList(dispose_images); dispose_image=DestroyImage(dispose_image); return((Image *) NULL); } current_image->background_color.alpha_trait=BlendPixelTrait; (void) CompositeImage(current_image,next, next->alpha_trait != UndefinedPixelTrait ? OverCompositeOp : CopyCompositeOp, MagickTrue,next->page.x,next->page.y,exception); /* Handle Background dispose: image is displayed for the delay period. */ if (next->dispose == BackgroundDispose) { bounds=next->page; bounds.width=next->columns; bounds.height=next->rows; if (bounds.x < 0) { bounds.width+=bounds.x; bounds.x=0; } if ((ssize_t) (bounds.x+bounds.width) > (ssize_t) current_image->columns) bounds.width=current_image->columns-bounds.x; if (bounds.y < 0) { bounds.height+=bounds.y; bounds.y=0; } if ((ssize_t) (bounds.y+bounds.height) > (ssize_t) current_image->rows) bounds.height=current_image->rows-bounds.y; ClearBounds(current_image,&bounds,exception); } /* Select the appropriate previous/disposed image. */ if (next->dispose == PreviousDispose) current_image=DestroyImage(current_image); else { dispose_image=DestroyImage(dispose_image); dispose_image=current_image; current_image=(Image *) NULL; } /* Save the dispose image just calculated for return. */ { Image *dispose; dispose=CloneImage(dispose_image,0,0,MagickTrue,exception); if (dispose == (Image *) NULL) { dispose_images=DestroyImageList(dispose_images); dispose_image=DestroyImage(dispose_image); return((Image *) NULL); } dispose_image->background_color.alpha_trait=BlendPixelTrait; (void) CloneImageProfiles(dispose,next); (void) CloneImageProperties(dispose,next); (void) CloneImageArtifacts(dispose,next); dispose->page.x=0; dispose->page.y=0; dispose->dispose=next->dispose; AppendImageToList(&dispose_images,dispose); } } dispose_image=DestroyImage(dispose_image); return(GetFirstImageInList(dispose_images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o m p a r e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ComparePixels() Compare the two pixels and return true if the pixels % differ according to the given LayerType comparision method. % % This currently only used internally by CompareImagesBounds(). It is % doubtful that this sub-routine will be useful outside this module. % % The format of the ComparePixels method is: % % MagickBooleanType *ComparePixels(const LayerMethod method, % const PixelInfo *p,const PixelInfo *q) % % A description of each parameter follows: % % o method: What differences to look for. Must be one of % CompareAnyLayer, CompareClearLayer, CompareOverlayLayer. % % o p, q: the pixels to test for appropriate differences. % */ static MagickBooleanType ComparePixels(const LayerMethod method, const PixelInfo *p,const PixelInfo *q) { double o1, o2; /* Any change in pixel values */ if (method == CompareAnyLayer) return(IsFuzzyEquivalencePixelInfo(p,q) == MagickFalse ? MagickTrue : MagickFalse); o1 = (p->alpha_trait != UndefinedPixelTrait) ? p->alpha : OpaqueAlpha; o2 = (q->alpha_trait != UndefinedPixelTrait) ? q->alpha : OpaqueAlpha; /* Pixel goes from opaque to transprency. */ if (method == CompareClearLayer) return((MagickBooleanType) ( (o1 >= ((double) QuantumRange/2.0)) && (o2 < ((double) QuantumRange/2.0)) ) ); /* Overlay would change first pixel by second. */ if (method == CompareOverlayLayer) { if (o2 < ((double) QuantumRange/2.0)) return MagickFalse; return(IsFuzzyEquivalencePixelInfo(p,q) == MagickFalse ? MagickTrue : MagickFalse); } return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o m p a r e I m a g e B o u n d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompareImagesBounds() Given two images return the smallest rectangular area % by which the two images differ, accourding to the given 'Compare...' % layer method. % % This currently only used internally in this module, but may eventually % be used by other modules. % % The format of the CompareImagesBounds method is: % % RectangleInfo *CompareImagesBounds(const LayerMethod method, % const Image *image1,const Image *image2,ExceptionInfo *exception) % % A description of each parameter follows: % % o method: What differences to look for. Must be one of CompareAnyLayer, % CompareClearLayer, CompareOverlayLayer. % % o image1, image2: the two images to compare. % % o exception: return any errors or warnings in this structure. % */ static RectangleInfo CompareImagesBounds(const Image *alpha_image, const Image *beta_image,const LayerMethod method,ExceptionInfo *exception) { CacheView *alpha_view, *beta_view; MagickBooleanType status; PixelInfo zero; RectangleInfo bounds; ssize_t y; assert(alpha_image != (Image *) NULL); assert(alpha_image->signature == MagickCoreSignature); assert(beta_image != (Image *) NULL); assert(beta_image->signature == MagickCoreSignature); if (alpha_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", alpha_image->filename); SetGeometry(alpha_image,&bounds); bounds.x=(ssize_t) bounds.width; bounds.y=(ssize_t) bounds.height; bounds.width=0; bounds.height=0; alpha_view=AcquireVirtualCacheView(alpha_image,exception); beta_view=AcquireVirtualCacheView(beta_image,exception); GetPixelInfo(alpha_image,&zero); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(alpha_image,alpha_image,alpha_image->rows,1) #endif for (y=0; y < (ssize_t) alpha_image->rows; y++) { const Quantum *magick_restrict p, *magick_restrict q; PixelInfo alpha_pixel, beta_pixel; RectangleInfo bounding_box; ssize_t x; if (status == MagickFalse) continue; #if defined(MAGICKCORE_OPENMP_SUPPORT) # pragma omp critical (MagickCore_CompareImagesBound) #endif bounding_box=bounds; p=GetCacheViewVirtualPixels(alpha_view,0,y,alpha_image->columns,1, exception); q=GetCacheViewVirtualPixels(beta_view,0,y,alpha_image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; continue; } alpha_pixel=zero; beta_pixel=zero; for (x=0; x < (ssize_t) alpha_image->columns; x++) { GetPixelInfoPixel(alpha_image,p,&alpha_pixel); GetPixelInfoPixel(beta_image,q,&beta_pixel); if ((x < bounding_box.x) && (ComparePixels(method,&alpha_pixel,&beta_pixel) != MagickFalse)) bounding_box.x=x; if ((x > (ssize_t) bounding_box.width) && (ComparePixels(method,&alpha_pixel,&beta_pixel) != MagickFalse)) bounding_box.width=(size_t) x; if ((y < bounding_box.y) && (ComparePixels(method,&alpha_pixel,&beta_pixel) != MagickFalse)) bounding_box.y=y; if ((y > (ssize_t) bounding_box.height) && (ComparePixels(method,&alpha_pixel,&beta_pixel) != MagickFalse)) bounding_box.height=(size_t) y; if ((x < (ssize_t) bounding_box.width) && (y > (ssize_t) bounding_box.height) && (ComparePixels(method,&alpha_pixel,&beta_pixel) != MagickFalse)) { bounding_box.width=(size_t) x; bounding_box.height=(size_t) y; } p+=GetPixelChannels(alpha_image); q+=GetPixelChannels(beta_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) # pragma omp critical (MagickCore_CompareImagesBound) #endif { if (bounding_box.x < bounds.x) bounds.x=bounding_box.x; if (bounding_box.y < bounds.y) bounds.y=bounding_box.y; if (bounding_box.width > bounds.width) bounds.width=bounding_box.width; if (bounding_box.height > bounds.height) bounds.height=bounding_box.height; } } beta_view=DestroyCacheView(beta_view); alpha_view=DestroyCacheView(alpha_view); if ((bounds.width != 0) && (bounds.height != 0)) { bounds.width-=(bounds.x-1); bounds.height-=(bounds.y-1); } else { /* Images are identical. */ bounds.x=(-1); bounds.y=(-1); bounds.width=1; bounds.height=1; } return(bounds); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p a r e I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompareImagesLayers() compares each image with the next in a sequence and % returns the minimum bounding region of all the pixel differences (of the % LayerMethod specified) it discovers. % % Images do NOT have to be the same size, though it is best that all the % images are 'coalesced' (images are all the same size, on a flattened % canvas, so as to represent exactly how an specific frame should look). % % No GIF dispose methods are applied, so GIF animations must be coalesced % before applying this image operator to find differences to them. % % The format of the CompareImagesLayers method is: % % Image *CompareImagesLayers(const Image *images, % const LayerMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the layers type to compare images with. Must be one of... % CompareAnyLayer, CompareClearLayer, CompareOverlayLayer. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CompareImagesLayers(const Image *image, const LayerMethod method,ExceptionInfo *exception) { Image *image_a, *image_b, *layers; RectangleInfo *bounds; const Image *next; ssize_t i; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); assert((method == CompareAnyLayer) || (method == CompareClearLayer) || (method == CompareOverlayLayer)); /* Allocate bounds memory. */ next=GetFirstImageInList(image); bounds=(RectangleInfo *) AcquireQuantumMemory((size_t) GetImageListLength(next),sizeof(*bounds)); if (bounds == (RectangleInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); /* Set up first comparision images. */ image_a=CloneImage(next,next->page.width,next->page.height, MagickTrue,exception); if (image_a == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } image_a->background_color.alpha_trait=BlendPixelTrait; image_a->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(image_a,exception); image_a->page=next->page; image_a->page.x=0; image_a->page.y=0; (void) CompositeImage(image_a,next,CopyCompositeOp,MagickTrue,next->page.x, next->page.y,exception); /* Compute the bounding box of changes for the later images */ i=0; next=GetNextImageInList(next); for ( ; next != (const Image *) NULL; next=GetNextImageInList(next)) { image_b=CloneImage(image_a,0,0,MagickTrue,exception); if (image_b == (Image *) NULL) { image_a=DestroyImage(image_a); bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } image_b->background_color.alpha_trait=BlendPixelTrait; (void) CompositeImage(image_a,next,CopyCompositeOp,MagickTrue,next->page.x, next->page.y,exception); bounds[i]=CompareImagesBounds(image_b,image_a,method,exception); image_b=DestroyImage(image_b); i++; } image_a=DestroyImage(image_a); /* Clone first image in sequence. */ next=GetFirstImageInList(image); layers=CloneImage(next,0,0,MagickTrue,exception); if (layers == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } layers->background_color.alpha_trait=BlendPixelTrait; /* Deconstruct the image sequence. */ i=0; next=GetNextImageInList(next); for ( ; next != (const Image *) NULL; next=GetNextImageInList(next)) { if ((bounds[i].x == -1) && (bounds[i].y == -1) && (bounds[i].width == 1) && (bounds[i].height == 1)) { /* An empty frame is returned from CompareImageBounds(), which means the current frame is identical to the previous frame. */ i++; continue; } image_a=CloneImage(next,0,0,MagickTrue,exception); if (image_a == (Image *) NULL) break; image_a->background_color.alpha_trait=BlendPixelTrait; image_b=CropImage(image_a,&bounds[i],exception); image_a=DestroyImage(image_a); if (image_b == (Image *) NULL) break; AppendImageToList(&layers,image_b); i++; } bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); if (next != (Image *) NULL) { layers=DestroyImageList(layers); return((Image *) NULL); } return(GetFirstImageInList(layers)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + O p t i m i z e L a y e r F r a m e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeLayerFrames() takes a coalesced GIF animation, and compares each % frame against the three different 'disposal' forms of the previous frame. % From this it then attempts to select the smallest cropped image and % disposal method needed to reproduce the resulting image. % % Note that this not easy, and may require the expansion of the bounds % of previous frame, simply clear pixels for the next animation frame to % transparency according to the selected dispose method. % % The format of the OptimizeLayerFrames method is: % % Image *OptimizeLayerFrames(const Image *image, % const LayerMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the layers technique to optimize with. Must be one of... % OptimizeImageLayer, or OptimizePlusLayer. The Plus form allows % the addition of extra 'zero delay' frames to clear pixels from % the previous frame, and the removal of frames that done change, % merging the delay times together. % % o exception: return any errors or warnings in this structure. % */ /* Define a 'fake' dispose method where the frame is duplicated, (for OptimizePlusLayer) with a extra zero time delay frame which does a BackgroundDisposal to clear the pixels that need to be cleared. */ #define DupDispose ((DisposeType)9) /* Another 'fake' dispose method used to removed frames that don't change. */ #define DelDispose ((DisposeType)8) #define DEBUG_OPT_FRAME 0 static Image *OptimizeLayerFrames(const Image *image,const LayerMethod method, ExceptionInfo *exception) { ExceptionInfo *sans_exception; Image *prev_image, *dup_image, *bgnd_image, *optimized_image; RectangleInfo try_bounds, bgnd_bounds, dup_bounds, *bounds; MagickBooleanType add_frames, try_cleared, cleared; DisposeType *disposals; const Image *curr; ssize_t i; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); assert(method == OptimizeLayer || method == OptimizeImageLayer || method == OptimizePlusLayer); /* Are we allowed to add/remove frames from animation? */ add_frames=method == OptimizePlusLayer ? MagickTrue : MagickFalse; /* Ensure all the images are the same size. */ curr=GetFirstImageInList(image); for (; curr != (Image *) NULL; curr=GetNextImageInList(curr)) { if ((curr->columns != image->columns) || (curr->rows != image->rows)) ThrowImageException(OptionError,"ImagesAreNotTheSameSize"); if ((curr->page.x != 0) || (curr->page.y != 0) || (curr->page.width != image->page.width) || (curr->page.height != image->page.height)) ThrowImageException(OptionError,"ImagePagesAreNotCoalesced"); } /* Allocate memory (times 2 if we allow the use of frame duplications) */ curr=GetFirstImageInList(image); bounds=(RectangleInfo *) AcquireQuantumMemory((size_t) GetImageListLength(curr),(add_frames != MagickFalse ? 2UL : 1UL)* sizeof(*bounds)); if (bounds == (RectangleInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); disposals=(DisposeType *) AcquireQuantumMemory((size_t) GetImageListLength(image),(add_frames != MagickFalse ? 2UL : 1UL)* sizeof(*disposals)); if (disposals == (DisposeType *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Initialise Previous Image as fully transparent */ prev_image=CloneImage(curr,curr->columns,curr->rows,MagickTrue,exception); if (prev_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); return((Image *) NULL); } prev_image->page=curr->page; /* ERROR: <-- should not be need, but is! */ prev_image->page.x=0; prev_image->page.y=0; prev_image->dispose=NoneDispose; prev_image->background_color.alpha_trait=BlendPixelTrait; prev_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(prev_image,exception); /* Figure out the area of overlay of the first frame No pixel could be cleared as all pixels are already cleared. */ #if DEBUG_OPT_FRAME i=0; (void) FormatLocaleFile(stderr,"frame %.20g :-\n",(double) i); #endif disposals[0]=NoneDispose; bounds[0]=CompareImagesBounds(prev_image,curr,CompareAnyLayer,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "overlay: %.20gx%.20g%+.20g%+.20g\n\n", (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y ); #endif /* Compute the bounding box of changes for each pair of images. */ i=1; bgnd_image=(Image *) NULL; dup_image=(Image *) NULL; dup_bounds.width=0; dup_bounds.height=0; dup_bounds.x=0; dup_bounds.y=0; curr=GetNextImageInList(curr); for ( ; curr != (const Image *) NULL; curr=GetNextImageInList(curr)) { #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"frame %.20g :-\n",(double) i); #endif /* Assume none disposal is the best */ bounds[i]=CompareImagesBounds(curr->previous,curr,CompareAnyLayer,exception); cleared=IsBoundsCleared(curr->previous,curr,&bounds[i],exception); disposals[i-1]=NoneDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "overlay: %.20gx%.20g%+.20g%+.20g%s%s\n", (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y, bounds[i].x < 0?" (unchanged)":"", cleared?" (pixels cleared)":""); #endif if ( bounds[i].x < 0 ) { /* Image frame is exactly the same as the previous frame! If not adding frames leave it to be cropped down to a null image. Otherwise mark previous image for deleted, transfering its crop bounds to the current image. */ if ( add_frames && i>=2 ) { disposals[i-1]=DelDispose; disposals[i]=NoneDispose; bounds[i]=bounds[i-1]; i++; continue; } } else { /* Compare a none disposal against a previous disposal */ try_bounds=CompareImagesBounds(prev_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(prev_image,curr,&try_bounds,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "test_prev: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels were cleared)":""); #endif if ( (!try_cleared && cleared ) || try_bounds.width * try_bounds.height < bounds[i].width * bounds[i].height ) { cleared=try_cleared; bounds[i]=try_bounds; disposals[i-1]=PreviousDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"previous: accepted\n"); } else { (void) FormatLocaleFile(stderr,"previous: rejected\n"); #endif } /* If we are allowed lets try a complex frame duplication. It is useless if the previous image already clears pixels correctly. This method will always clear all the pixels that need to be cleared. */ dup_bounds.width=dup_bounds.height=0; /* no dup, no pixel added */ if ( add_frames ) { dup_image=CloneImage(curr->previous,0,0,MagickTrue,exception); if (dup_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); prev_image=DestroyImage(prev_image); return((Image *) NULL); } dup_image->background_color.alpha_trait=BlendPixelTrait; dup_bounds=CompareImagesBounds(dup_image,curr,CompareClearLayer,exception); ClearBounds(dup_image,&dup_bounds,exception); try_bounds=CompareImagesBounds(dup_image,curr,CompareAnyLayer,exception); if ( cleared || dup_bounds.width*dup_bounds.height +try_bounds.width*try_bounds.height < bounds[i].width * bounds[i].height ) { cleared=MagickFalse; bounds[i]=try_bounds; disposals[i-1]=DupDispose; /* to be finalised later, if found to be optimial */ } else dup_bounds.width=dup_bounds.height=0; } /* Now compare against a simple background disposal */ bgnd_image=CloneImage(curr->previous,0,0,MagickTrue,exception); if (bgnd_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); prev_image=DestroyImage(prev_image); if ( dup_image != (Image *) NULL) dup_image=DestroyImage(dup_image); return((Image *) NULL); } bgnd_image->background_color.alpha_trait=BlendPixelTrait; bgnd_bounds=bounds[i-1]; /* interum bounds of the previous image */ ClearBounds(bgnd_image,&bgnd_bounds,exception); try_bounds=CompareImagesBounds(bgnd_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "background: %s\n", try_cleared?"(pixels cleared)":""); #endif if ( try_cleared ) { /* Straight background disposal failed to clear pixels needed! Lets try expanding the disposal area of the previous frame, to include the pixels that are cleared. This guaranteed to work, though may not be the most optimized solution. */ try_bounds=CompareImagesBounds(curr->previous,curr,CompareClearLayer,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "expand_clear: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_bounds.x<0?" (no expand nessary)":""); #endif if ( bgnd_bounds.x < 0 ) bgnd_bounds = try_bounds; else { #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "expand_bgnd: %.20gx%.20g%+.20g%+.20g\n", (double) bgnd_bounds.width,(double) bgnd_bounds.height, (double) bgnd_bounds.x,(double) bgnd_bounds.y ); #endif if ( try_bounds.x < bgnd_bounds.x ) { bgnd_bounds.width+= bgnd_bounds.x-try_bounds.x; if ( bgnd_bounds.width < try_bounds.width ) bgnd_bounds.width = try_bounds.width; bgnd_bounds.x = try_bounds.x; } else { try_bounds.width += try_bounds.x - bgnd_bounds.x; if ( bgnd_bounds.width < try_bounds.width ) bgnd_bounds.width = try_bounds.width; } if ( try_bounds.y < bgnd_bounds.y ) { bgnd_bounds.height += bgnd_bounds.y - try_bounds.y; if ( bgnd_bounds.height < try_bounds.height ) bgnd_bounds.height = try_bounds.height; bgnd_bounds.y = try_bounds.y; } else { try_bounds.height += try_bounds.y - bgnd_bounds.y; if ( bgnd_bounds.height < try_bounds.height ) bgnd_bounds.height = try_bounds.height; } #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, " to : %.20gx%.20g%+.20g%+.20g\n", (double) bgnd_bounds.width,(double) bgnd_bounds.height, (double) bgnd_bounds.x,(double) bgnd_bounds.y ); #endif } ClearBounds(bgnd_image,&bgnd_bounds,exception); #if DEBUG_OPT_FRAME /* Something strange is happening with a specific animation * CompareAnyLayers (normal method) and CompareClearLayers returns the whole * image, which is not posibly correct! As verified by previous tests. * Something changed beyond the bgnd_bounds clearing. But without being able * to see, or writet he image at this point it is hard to tell what is wrong! * Only CompareOverlay seemed to return something sensible. */ try_bounds=CompareImagesBounds(bgnd_image,curr,CompareClearLayer,exception); (void) FormatLocaleFile(stderr, "expand_ctst: %.20gx%.20g%+.20g%+.20g\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y ); try_bounds=CompareImagesBounds(bgnd_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); (void) FormatLocaleFile(stderr, "expand_any : %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels cleared)":""); #endif try_bounds=CompareImagesBounds(bgnd_image,curr,CompareOverlayLayer,exception); #if DEBUG_OPT_FRAME try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); (void) FormatLocaleFile(stderr, "expand_test: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels cleared)":""); #endif } /* Test if this background dispose is smaller than any of the other methods we tryed before this (including duplicated frame) */ if ( cleared || bgnd_bounds.width*bgnd_bounds.height +try_bounds.width*try_bounds.height < bounds[i-1].width*bounds[i-1].height +dup_bounds.width*dup_bounds.height +bounds[i].width*bounds[i].height ) { cleared=MagickFalse; bounds[i-1]=bgnd_bounds; bounds[i]=try_bounds; if ( disposals[i-1] == DupDispose ) dup_image=DestroyImage(dup_image); disposals[i-1]=BackgroundDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"expand_bgnd: accepted\n"); } else { (void) FormatLocaleFile(stderr,"expand_bgnd: reject\n"); #endif } } /* Finalise choice of dispose, set new prev_image, and junk any extra images as appropriate, */ if ( disposals[i-1] == DupDispose ) { if (bgnd_image != (Image *) NULL) bgnd_image=DestroyImage(bgnd_image); prev_image=DestroyImage(prev_image); prev_image=dup_image, dup_image=(Image *) NULL; bounds[i+1]=bounds[i]; bounds[i]=dup_bounds; disposals[i-1]=DupDispose; disposals[i]=BackgroundDispose; i++; } else { if ( dup_image != (Image *) NULL) dup_image=DestroyImage(dup_image); if ( disposals[i-1] != PreviousDispose ) prev_image=DestroyImage(prev_image); if ( disposals[i-1] == BackgroundDispose ) prev_image=bgnd_image, bgnd_image=(Image *) NULL; if (bgnd_image != (Image *) NULL) bgnd_image=DestroyImage(bgnd_image); if ( disposals[i-1] == NoneDispose ) { prev_image=ReferenceImage(curr->previous); if (prev_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); return((Image *) NULL); } } } assert(prev_image != (Image *) NULL); disposals[i]=disposals[i-1]; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "final %.20g : %s %.20gx%.20g%+.20g%+.20g\n", (double) i-1, CommandOptionToMnemonic(MagickDisposeOptions,disposals[i-1]), (double) bounds[i-1].width,(double) bounds[i-1].height, (double) bounds[i-1].x,(double) bounds[i-1].y ); #endif #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "interum %.20g : %s %.20gx%.20g%+.20g%+.20g\n", (double) i, CommandOptionToMnemonic(MagickDisposeOptions,disposals[i]), (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y ); (void) FormatLocaleFile(stderr,"\n"); #endif i++; } prev_image=DestroyImage(prev_image); /* Optimize all images in sequence. */ sans_exception=AcquireExceptionInfo(); i=0; curr=GetFirstImageInList(image); optimized_image=NewImageList(); while ( curr != (const Image *) NULL ) { prev_image=CloneImage(curr,0,0,MagickTrue,exception); if (prev_image == (Image *) NULL) break; prev_image->background_color.alpha_trait=BlendPixelTrait; if ( disposals[i] == DelDispose ) { size_t time = 0; while ( disposals[i] == DelDispose ) { time +=(size_t) (curr->delay*1000* PerceptibleReciprocal((double) curr->ticks_per_second)); curr=GetNextImageInList(curr); i++; } time += (size_t)(curr->delay*1000* PerceptibleReciprocal((double) curr->ticks_per_second)); prev_image->ticks_per_second = 100L; prev_image->delay = time*prev_image->ticks_per_second/1000; } bgnd_image=CropImage(prev_image,&bounds[i],sans_exception); prev_image=DestroyImage(prev_image); if (bgnd_image == (Image *) NULL) break; bgnd_image->dispose=disposals[i]; if ( disposals[i] == DupDispose ) { bgnd_image->delay=0; bgnd_image->dispose=NoneDispose; } else curr=GetNextImageInList(curr); AppendImageToList(&optimized_image,bgnd_image); i++; } sans_exception=DestroyExceptionInfo(sans_exception); bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); if (curr != (Image *) NULL) { optimized_image=DestroyImageList(optimized_image); return((Image *) NULL); } return(GetFirstImageInList(optimized_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p t i m i z e I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeImageLayers() compares each image the GIF disposed forms of the % previous image in the sequence. From this it attempts to select the % smallest cropped image to replace each frame, while preserving the results % of the GIF animation. % % The format of the OptimizeImageLayers method is: % % Image *OptimizeImageLayers(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *OptimizeImageLayers(const Image *image, ExceptionInfo *exception) { return(OptimizeLayerFrames(image,OptimizeImageLayer,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p t i m i z e P l u s I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeImagePlusLayers() is exactly as OptimizeImageLayers(), but may % also add or even remove extra frames in the animation, if it improves % the total number of pixels in the resulting GIF animation. % % The format of the OptimizePlusImageLayers method is: % % Image *OptimizePlusImageLayers(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *OptimizePlusImageLayers(const Image *image, ExceptionInfo *exception) { return OptimizeLayerFrames(image,OptimizePlusLayer,exception); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p t i m i z e I m a g e T r a n s p a r e n c y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeImageTransparency() takes a frame optimized GIF animation, and % compares the overlayed pixels against the disposal image resulting from all % the previous frames in the animation. Any pixel that does not change the % disposal image (and thus does not effect the outcome of an overlay) is made % transparent. % % WARNING: This modifies the current images directly, rather than generate % a new image sequence. % % The format of the OptimizeImageTransperency method is: % % void OptimizeImageTransperency(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image sequence % % o exception: return any errors or warnings in this structure. % */ MagickExport void OptimizeImageTransparency(const Image *image, ExceptionInfo *exception) { Image *dispose_image; Image *next; /* Run the image through the animation sequence */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); next=GetFirstImageInList(image); dispose_image=CloneImage(next,next->page.width,next->page.height, MagickTrue,exception); if (dispose_image == (Image *) NULL) return; dispose_image->page=next->page; dispose_image->page.x=0; dispose_image->page.y=0; dispose_image->dispose=NoneDispose; dispose_image->background_color.alpha_trait=BlendPixelTrait; dispose_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(dispose_image,exception); while ( next != (Image *) NULL ) { Image *current_image; /* Overlay this frame's image over the previous disposal image */ current_image=CloneImage(dispose_image,0,0,MagickTrue,exception); if (current_image == (Image *) NULL) { dispose_image=DestroyImage(dispose_image); return; } current_image->background_color.alpha_trait=BlendPixelTrait; (void) CompositeImage(current_image,next,next->alpha_trait != UndefinedPixelTrait ? OverCompositeOp : CopyCompositeOp,MagickTrue,next->page.x,next->page.y, exception); /* At this point the image would be displayed, for the delay period ** Work out the disposal of the previous image */ if (next->dispose == BackgroundDispose) { RectangleInfo bounds=next->page; bounds.width=next->columns; bounds.height=next->rows; if (bounds.x < 0) { bounds.width+=bounds.x; bounds.x=0; } if ((ssize_t) (bounds.x+bounds.width) > (ssize_t) current_image->columns) bounds.width=current_image->columns-bounds.x; if (bounds.y < 0) { bounds.height+=bounds.y; bounds.y=0; } if ((ssize_t) (bounds.y+bounds.height) > (ssize_t) current_image->rows) bounds.height=current_image->rows-bounds.y; ClearBounds(current_image,&bounds,exception); } if (next->dispose != PreviousDispose) { dispose_image=DestroyImage(dispose_image); dispose_image=current_image; } else current_image=DestroyImage(current_image); /* Optimize Transparency of the next frame (if present) */ next=GetNextImageInList(next); if (next != (Image *) NULL) (void) CompositeImage(next,dispose_image,ChangeMaskCompositeOp, MagickTrue,-(next->page.x),-(next->page.y),exception); } dispose_image=DestroyImage(dispose_image); return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e D u p l i c a t e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveDuplicateLayers() removes any image that is exactly the same as the % next image in the given image list. Image size and virtual canvas offset % must also match, though not the virtual canvas size itself. % % No check is made with regards to image disposal setting, though it is the % dispose setting of later image that is kept. Also any time delays are also % added together. As such coalesced image animations should still produce the % same result, though with duplicte frames merged into a single frame. % % The format of the RemoveDuplicateLayers method is: % % void RemoveDuplicateLayers(Image **image,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list % % o exception: return any errors or warnings in this structure. % */ MagickExport void RemoveDuplicateLayers(Image **images,ExceptionInfo *exception) { RectangleInfo bounds; Image *image, *next; assert((*images) != (const Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", (*images)->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=GetFirstImageInList(*images); for ( ; (next=GetNextImageInList(image)) != (Image *) NULL; image=next) { if ((image->columns != next->columns) || (image->rows != next->rows) || (image->page.x != next->page.x) || (image->page.y != next->page.y)) continue; bounds=CompareImagesBounds(image,next,CompareAnyLayer,exception); if (bounds.x < 0) { /* Two images are the same, merge time delays and delete one. */ size_t time; time=(size_t) (1000.0*image->delay* PerceptibleReciprocal((double) image->ticks_per_second)); time+=(size_t) (1000.0*next->delay* PerceptibleReciprocal((double) next->ticks_per_second)); next->ticks_per_second=100L; next->delay=time*image->ticks_per_second/1000; next->iterations=image->iterations; *images=image; (void) DeleteImageFromList(images); } } *images=GetFirstImageInList(*images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e Z e r o D e l a y L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveZeroDelayLayers() removes any image that as a zero delay time. Such % images generally represent intermediate or partial updates in GIF % animations used for file optimization. They are not ment to be displayed % to users of the animation. Viewable images in an animation should have a % time delay of 3 or more centi-seconds (hundredths of a second). % % However if all the frames have a zero time delay, then either the animation % is as yet incomplete, or it is not a GIF animation. This a non-sensible % situation, so no image will be removed and a 'Zero Time Animation' warning % (exception) given. % % No warning will be given if no image was removed because all images had an % appropriate non-zero time delay set. % % Due to the special requirements of GIF disposal handling, GIF animations % should be coalesced first, before calling this function, though that is not % a requirement. % % The format of the RemoveZeroDelayLayers method is: % % void RemoveZeroDelayLayers(Image **image,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list % % o exception: return any errors or warnings in this structure. % */ MagickExport void RemoveZeroDelayLayers(Image **images, ExceptionInfo *exception) { Image *i; assert((*images) != (const Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*images)->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); i=GetFirstImageInList(*images); for ( ; i != (Image *) NULL; i=GetNextImageInList(i)) if ( i->delay != 0L ) break; if ( i == (Image *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "ZeroTimeAnimation","`%s'",GetFirstImageInList(*images)->filename); return; } i=GetFirstImageInList(*images); while ( i != (Image *) NULL ) { if ( i->delay == 0L ) { (void) DeleteImageFromList(&i); *images=i; } else i=GetNextImageInList(i); } *images=GetFirstImageInList(*images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p o s i t e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompositeLayers() compose the source image sequence over the destination % image sequence, starting with the current image in both lists. % % Each layer from the two image lists are composted together until the end of % one of the image lists is reached. The offset of each composition is also % adjusted to match the virtual canvas offsets of each layer. As such the % given offset is relative to the virtual canvas, and not the actual image. % % Composition uses given x and y offsets, as the 'origin' location of the % source images virtual canvas (not the real image) allowing you to compose a % list of 'layer images' into the destiantioni images. This makes it well % sutiable for directly composing 'Clears Frame Animations' or 'Coaleased % Animations' onto a static or other 'Coaleased Animation' destination image % list. GIF disposal handling is not looked at. % % Special case:- If one of the image sequences is the last image (just a % single image remaining), that image is repeatally composed with all the % images in the other image list. Either the source or destination lists may % be the single image, for this situation. % % In the case of a single destination image (or last image given), that image % will ve cloned to match the number of images remaining in the source image % list. % % This is equivelent to the "-layer Composite" Shell API operator. % % % The format of the CompositeLayers method is: % % void CompositeLayers(Image *destination, const CompositeOperator % compose, Image *source, const ssize_t x_offset, const ssize_t y_offset, % ExceptionInfo *exception); % % A description of each parameter follows: % % o destination: the destination images and results % % o source: source image(s) for the layer composition % % o compose, x_offset, y_offset: arguments passed on to CompositeImages() % % o exception: return any errors or warnings in this structure. % */ static inline void CompositeCanvas(Image *destination, const CompositeOperator compose,Image *source,ssize_t x_offset, ssize_t y_offset,ExceptionInfo *exception) { const char *value; x_offset+=source->page.x-destination->page.x; y_offset+=source->page.y-destination->page.y; value=GetImageArtifact(source,"compose:outside-overlay"); (void) CompositeImage(destination,source,compose, (value != (const char *) NULL) && (IsStringTrue(value) != MagickFalse) ? MagickFalse : MagickTrue,x_offset,y_offset,exception); } MagickExport void CompositeLayers(Image *destination, const CompositeOperator compose, Image *source,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { assert(destination != (Image *) NULL); assert(destination->signature == MagickCoreSignature); assert(source != (Image *) NULL); assert(source->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (source->debug != MagickFalse || destination->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s - %s", source->filename,destination->filename); /* Overlay single source image over destation image/list */ if ( source->next == (Image *) NULL ) while ( destination != (Image *) NULL ) { CompositeCanvas(destination, compose, source, x_offset, y_offset, exception); destination=GetNextImageInList(destination); } /* Overlay source image list over single destination. Multiple clones of destination image are created to match source list. Original Destination image becomes first image of generated list. As such the image list pointer does not require any change in caller. Some animation attributes however also needs coping in this case. */ else if ( destination->next == (Image *) NULL ) { Image *dest = CloneImage(destination,0,0,MagickTrue,exception); if (dest != (Image *) NULL) { dest->background_color.alpha_trait=BlendPixelTrait; CompositeCanvas(destination, compose, source, x_offset, y_offset, exception); /* copy source image attributes ? */ if ( source->next != (Image *) NULL ) { destination->delay=source->delay; destination->iterations=source->iterations; } source=GetNextImageInList(source); while (source != (Image *) NULL) { AppendImageToList(&destination, CloneImage(dest,0,0,MagickTrue,exception)); destination->background_color.alpha_trait=BlendPixelTrait; destination=GetLastImageInList(destination); CompositeCanvas(destination,compose,source,x_offset,y_offset, exception); destination->delay=source->delay; destination->iterations=source->iterations; source=GetNextImageInList(source); } dest=DestroyImage(dest); } } /* Overlay a source image list over a destination image list until either list runs out of images. (Does not repeat) */ else while ( source != (Image *) NULL && destination != (Image *) NULL ) { CompositeCanvas(destination, compose, source, x_offset, y_offset, exception); source=GetNextImageInList(source); destination=GetNextImageInList(destination); } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M e r g e I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MergeImageLayers() composes all the image layers from the current given % image onward to produce a single image of the merged layers. % % The inital canvas's size depends on the given LayerMethod, and is % initialized using the first images background color. The images % are then compositied onto that image in sequence using the given % composition that has been assigned to each individual image. % % The format of the MergeImageLayers is: % % Image *MergeImageLayers(Image *image,const LayerMethod method, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image list to be composited together % % o method: the method of selecting the size of the initial canvas. % % MergeLayer: Merge all layers onto a canvas just large enough % to hold all the actual images. The virtual canvas of the % first image is preserved but otherwise ignored. % % FlattenLayer: Use the virtual canvas size of first image. % Images which fall outside this canvas is clipped. % This can be used to 'fill out' a given virtual canvas. % % MosaicLayer: Start with the virtual canvas of the first image, % enlarging left and right edges to contain all images. % Images with negative offsets will be clipped. % % TrimBoundsLayer: Determine the overall bounds of all the image % layers just as in "MergeLayer", then adjust the canvas % and offsets to be relative to those bounds, without overlaying % the images. % % WARNING: a new image is not returned, the original image % sequence page data is modified instead. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MergeImageLayers(Image *image,const LayerMethod method, ExceptionInfo *exception) { #define MergeLayersTag "Merge/Layers" Image *canvas; MagickBooleanType proceed; RectangleInfo page; const Image *next; size_t number_images, height, width; ssize_t scene; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); /* Determine canvas image size, and its virtual canvas size and offset */ page=image->page; width=image->columns; height=image->rows; switch (method) { case TrimBoundsLayer: case MergeLayer: default: { next=GetNextImageInList(image); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { if (page.x > next->page.x) { width+=page.x-next->page.x; page.x=next->page.x; } if (page.y > next->page.y) { height+=page.y-next->page.y; page.y=next->page.y; } if ((ssize_t) width < (next->page.x+(ssize_t) next->columns-page.x)) width=(size_t) next->page.x+(ssize_t) next->columns-page.x; if ((ssize_t) height < (next->page.y+(ssize_t) next->rows-page.y)) height=(size_t) next->page.y+(ssize_t) next->rows-page.y; } break; } case FlattenLayer: { if (page.width > 0) width=page.width; if (page.height > 0) height=page.height; page.x=0; page.y=0; break; } case MosaicLayer: { if (page.width > 0) width=page.width; if (page.height > 0) height=page.height; for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) { if (method == MosaicLayer) { page.x=next->page.x; page.y=next->page.y; if ((ssize_t) width < (next->page.x+(ssize_t) next->columns)) width=(size_t) next->page.x+next->columns; if ((ssize_t) height < (next->page.y+(ssize_t) next->rows)) height=(size_t) next->page.y+next->rows; } } page.width=width; page.height=height; page.x=0; page.y=0; } break; } /* Set virtual canvas size if not defined. */ if (page.width == 0) page.width=page.x < 0 ? width : width+page.x; if (page.height == 0) page.height=page.y < 0 ? height : height+page.y; /* Handle "TrimBoundsLayer" method separately to normal 'layer merge'. */ if (method == TrimBoundsLayer) { number_images=GetImageListLength(image); for (scene=0; scene < (ssize_t) number_images; scene++) { image->page.x-=page.x; image->page.y-=page.y; image->page.width=width; image->page.height=height; proceed=SetImageProgress(image,MergeLayersTag,(MagickOffsetType) scene, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); if (image == (Image *) NULL) break; } return((Image *) NULL); } /* Create canvas size of width and height, and background color. */ canvas=CloneImage(image,width,height,MagickTrue,exception); if (canvas == (Image *) NULL) return((Image *) NULL); canvas->background_color.alpha_trait=BlendPixelTrait; (void) SetImageBackgroundColor(canvas,exception); canvas->page=page; canvas->dispose=UndefinedDispose; /* Compose images onto canvas, with progress monitor */ number_images=GetImageListLength(image); for (scene=0; scene < (ssize_t) number_images; scene++) { (void) CompositeImage(canvas,image,image->compose,MagickTrue,image->page.x- canvas->page.x,image->page.y-canvas->page.y,exception); proceed=SetImageProgress(image,MergeLayersTag,(MagickOffsetType) scene, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); if (image == (Image *) NULL) break; } return(canvas); }
clang-nwchem-s1_1.c
// mimic NWChem tgt_sd_t_s1_1 kernel but in C #include <stdio.h> void sd_t_s1_1(int l1, int l2, int l3, int l4, int l5, int l6, int u1, int u2, int u3, int u4, int u5, int u6) { float a[24][24][24][24][24][24]; float b[24][24][24][24][24][24]; int i1, i2, i3, i4, i5, i6; for (i1 = 0; i1 < 24; ++i1) for (i2 = 0; i2 < 24; ++i2) for (i3 = 0; i3 < 24; ++i3) for (i4 = 0; i4 < 24; ++i4) for (i5 = 0; i5 < 24; ++i5) for (i6 = 0; i6 < 24; ++i6) a[i1][i2][i3][i4][i5][i6] = 3.0; #pragma omp target teams distribute parallel for collapse(6) for (i1 = l1; i1 < u1; ++i1) for (i2 = l2; i2 < u2; ++i2) for (i3 = l3; i3 < u3; ++i3) for (i4 = l4; i4 < u4; ++i4) for (i5 = l5; i5 < u5; ++i5) for (i6 = l6; i6 < u6; ++i6) b[i1][i2][i3][i4][i5][i6] = a[i1][i2][i3][i4][i5][i6] + i3; for (i1 = l1; i1 < 4; ++i1) { for (i2 = l2; i2 < 4; ++i2) printf("%f ", b[i1][i2][1][1][1][1]); printf("\n"); } } int main() { sd_t_s1_1(0, 0, 0, 0, 0, 0, 24, 24, 24, 24, 24, 24); }
fx.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF X X % % F X X % % FFF X % % F X X % % F X X % % % % % % MagickCore Image Special Effects Methods % % % % Software Design % % Cristy % % October 1996 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % 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 declarations. */ #include "magick/studio.h" #include "magick/accelerate-private.h" #include "magick/annotate.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/cache.h" #include "magick/cache-view.h" #include "magick/channel.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/composite.h" #include "magick/decorate.h" #include "magick/distort.h" #include "magick/draw.h" #include "magick/effect.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/fx.h" #include "magick/fx-private.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/layer.h" #include "magick/list.h" #include "magick/log.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/opencl-private.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantum.h" #include "magick/quantum-private.h" #include "magick/random_.h" #include "magick/random-private.h" #include "magick/resample.h" #include "magick/resample-private.h" #include "magick/resize.h" #include "magick/resource_.h" #include "magick/splay-tree.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/transform.h" #include "magick/utility.h" /* Define declarations. */ #define LeftShiftOperator 0xf5U #define RightShiftOperator 0xf6U #define LessThanEqualOperator 0xf7U #define GreaterThanEqualOperator 0xf8U #define EqualOperator 0xf9U #define NotEqualOperator 0xfaU #define LogicalAndOperator 0xfbU #define LogicalOrOperator 0xfcU #define ExponentialNotation 0xfdU struct _FxInfo { const Image *images; char *expression; FILE *file; SplayTreeInfo *colors, *symbols; CacheView **view; RandomInfo *random_info; ExceptionInfo *exception; }; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e F x I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireFxInfo() allocates the FxInfo structure. % % The format of the AcquireFxInfo method is: % % FxInfo *AcquireFxInfo(Image *image,const char *expression) % % A description of each parameter follows: % % o image: the image. % % o expression: the expression. % */ MagickExport FxInfo *AcquireFxInfo(const Image *image,const char *expression) { char fx_op[2]; const Image *next; FxInfo *fx_info; register ssize_t i; fx_info=(FxInfo *) AcquireMagickMemory(sizeof(*fx_info)); if (fx_info == (FxInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) memset(fx_info,0,sizeof(*fx_info)); fx_info->exception=AcquireExceptionInfo(); fx_info->images=image; fx_info->colors=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory, RelinquishAlignedMemory); fx_info->symbols=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory, RelinquishMagickMemory); fx_info->view=(CacheView **) AcquireQuantumMemory(GetImageListLength( fx_info->images),sizeof(*fx_info->view)); if (fx_info->view == (CacheView **) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); i=0; next=GetFirstImageInList(fx_info->images); for ( ; next != (Image *) NULL; next=next->next) { fx_info->view[i]=AcquireVirtualCacheView(next,fx_info->exception); i++; } fx_info->random_info=AcquireRandomInfo(); fx_info->expression=ConstantString(expression); fx_info->file=stderr; (void) SubstituteString(&fx_info->expression," ",""); /* compact string */ /* Force right-to-left associativity for unary negation. */ (void) SubstituteString(&fx_info->expression,"-","-1.0*"); (void) SubstituteString(&fx_info->expression,"^-1.0*","^-"); (void) SubstituteString(&fx_info->expression,"E-1.0*","E-"); (void) SubstituteString(&fx_info->expression,"e-1.0*","e-"); /* Convert compound to simple operators. */ fx_op[1]='\0'; *fx_op=(char) LeftShiftOperator; (void) SubstituteString(&fx_info->expression,"<<",fx_op); *fx_op=(char) RightShiftOperator; (void) SubstituteString(&fx_info->expression,">>",fx_op); *fx_op=(char) LessThanEqualOperator; (void) SubstituteString(&fx_info->expression,"<=",fx_op); *fx_op=(char) GreaterThanEqualOperator; (void) SubstituteString(&fx_info->expression,">=",fx_op); *fx_op=(char) EqualOperator; (void) SubstituteString(&fx_info->expression,"==",fx_op); *fx_op=(char) NotEqualOperator; (void) SubstituteString(&fx_info->expression,"!=",fx_op); *fx_op=(char) LogicalAndOperator; (void) SubstituteString(&fx_info->expression,"&&",fx_op); *fx_op=(char) LogicalOrOperator; (void) SubstituteString(&fx_info->expression,"||",fx_op); *fx_op=(char) ExponentialNotation; (void) SubstituteString(&fx_info->expression,"**",fx_op); return(fx_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d d N o i s e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AddNoiseImage() adds random noise to the image. % % The format of the AddNoiseImage method is: % % Image *AddNoiseImage(const Image *image,const NoiseType noise_type, % ExceptionInfo *exception) % Image *AddNoiseImageChannel(const Image *image,const ChannelType channel, % const NoiseType noise_type,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o noise_type: The type of noise: Uniform, Gaussian, Multiplicative, % Impulse, Laplacian, or Poisson. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AddNoiseImage(const Image *image,const NoiseType noise_type, ExceptionInfo *exception) { Image *noise_image; noise_image=AddNoiseImageChannel(image,DefaultChannels,noise_type,exception); return(noise_image); } MagickExport Image *AddNoiseImageChannel(const Image *image, const ChannelType channel,const NoiseType noise_type,ExceptionInfo *exception) { #define AddNoiseImageTag "AddNoise/Image" CacheView *image_view, *noise_view; const char *option; double attenuate; Image *noise_image; MagickBooleanType status; MagickOffsetType progress; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif /* Initialize noise image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) noise_image=AccelerateAddNoiseImage(image,channel,noise_type,exception); if (noise_image != (Image *) NULL) return(noise_image); #endif noise_image=CloneImage(image,0,0,MagickTrue,exception); if (noise_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(noise_image,DirectClass) == MagickFalse) { InheritException(exception,&noise_image->exception); noise_image=DestroyImage(noise_image); return((Image *) NULL); } /* Add noise in each row. */ attenuate=1.0; option=GetImageArtifact(image,"attenuate"); if (option != (char *) NULL) attenuate=StringToDouble(option,(char **) NULL); status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); image_view=AcquireVirtualCacheView(image,exception); noise_view=AcquireAuthenticCacheView(noise_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,noise_image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict noise_indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(noise_view,0,y,noise_image->columns,1, exception); if ((p == (PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); noise_indexes=GetCacheViewAuthenticIndexQueue(noise_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(GenerateDifferentialNoise(random_info[id], GetPixelRed(p),noise_type,attenuate))); if (IsGrayColorspace(image->colorspace) != MagickFalse) { SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); } else { if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(GenerateDifferentialNoise( random_info[id],GetPixelGreen(p),noise_type,attenuate))); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(GenerateDifferentialNoise( random_info[id],GetPixelBlue(p),noise_type,attenuate))); } if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToQuantum(GenerateDifferentialNoise( random_info[id],GetPixelOpacity(p),noise_type,attenuate))); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(noise_indexes+x,ClampToQuantum( GenerateDifferentialNoise(random_info[id],GetPixelIndex( indexes+x),noise_type,attenuate))); p++; q++; } sync=SyncCacheViewAuthenticPixels(noise_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,AddNoiseImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } noise_view=DestroyCacheView(noise_view); image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) noise_image=DestroyImage(noise_image); return(noise_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B l u e S h i f t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BlueShiftImage() mutes the colors of the image to simulate a scene at % nighttime in the moonlight. % % The format of the BlueShiftImage method is: % % Image *BlueShiftImage(const Image *image,const double factor, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o factor: the shift factor. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *BlueShiftImage(const Image *image,const double factor, ExceptionInfo *exception) { #define BlueShiftImageTag "BlueShift/Image" CacheView *image_view, *shift_view; Image *shift_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Allocate blue shift image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); shift_image=CloneImage(image,0,0,MagickTrue,exception); if (shift_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(shift_image,DirectClass) == MagickFalse) { InheritException(exception,&shift_image->exception); shift_image=DestroyImage(shift_image); return((Image *) NULL); } /* Blue-shift DirectClass image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); shift_view=AcquireAuthenticCacheView(shift_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,shift_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; MagickPixelPacket pixel; Quantum quantum; register const PixelPacket *magick_restrict p; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(shift_view,0,y,shift_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { quantum=GetPixelRed(p); if (GetPixelGreen(p) < quantum) quantum=GetPixelGreen(p); if (GetPixelBlue(p) < quantum) quantum=GetPixelBlue(p); pixel.red=0.5*(GetPixelRed(p)+factor*quantum); pixel.green=0.5*(GetPixelGreen(p)+factor*quantum); pixel.blue=0.5*(GetPixelBlue(p)+factor*quantum); quantum=GetPixelRed(p); if (GetPixelGreen(p) > quantum) quantum=GetPixelGreen(p); if (GetPixelBlue(p) > quantum) quantum=GetPixelBlue(p); pixel.red=0.5*(pixel.red+factor*quantum); pixel.green=0.5*(pixel.green+factor*quantum); pixel.blue=0.5*(pixel.blue+factor*quantum); SetPixelRed(q,ClampToQuantum(pixel.red)); SetPixelGreen(q,ClampToQuantum(pixel.green)); SetPixelBlue(q,ClampToQuantum(pixel.blue)); p++; q++; } sync=SyncCacheViewAuthenticPixels(shift_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,BlueShiftImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); shift_view=DestroyCacheView(shift_view); if (status == MagickFalse) shift_image=DestroyImage(shift_image); return(shift_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C h a r c o a l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CharcoalImage() creates a new image that is a copy of an existing one with % the edge highlighted. It allocates the memory necessary for the new Image % structure and returns a pointer to the new image. % % The format of the CharcoalImage method is: % % Image *CharcoalImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the pixel neighborhood. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CharcoalImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { Image *charcoal_image, *clone_image, *edge_image; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); clone_image=CloneImage(image,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) return((Image *) NULL); edge_image=EdgeImage(clone_image,radius,exception); clone_image=DestroyImage(clone_image); if (edge_image == (Image *) NULL) return((Image *) NULL); charcoal_image=BlurImage(edge_image,radius,sigma,exception); edge_image=DestroyImage(edge_image); if (charcoal_image == (Image *) NULL) return((Image *) NULL); (void) NormalizeImage(charcoal_image); (void) NegateImage(charcoal_image,MagickFalse); (void) GrayscaleImage(charcoal_image,image->intensity); return(charcoal_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o l o r i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ColorizeImage() blends the fill color with each pixel in the image. % A percentage blend is specified with opacity. Control the application % of different color components by specifying a different percentage for % each component (e.g. 90/100/10 is 90% red, 100% green, and 10% blue). % % The format of the ColorizeImage method is: % % Image *ColorizeImage(const Image *image,const char *opacity, % const PixelPacket colorize,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o opacity: A character string indicating the level of opacity as a % percentage. % % o colorize: A color value. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ColorizeImage(const Image *image,const char *opacity, const PixelPacket colorize,ExceptionInfo *exception) { #define ColorizeImageTag "Colorize/Image" CacheView *colorize_view, *image_view; GeometryInfo geometry_info; Image *colorize_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket pixel; MagickStatusType flags; ssize_t y; /* Allocate colorized image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); colorize_image=CloneImage(image,0,0,MagickTrue,exception); if (colorize_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(colorize_image,DirectClass) == MagickFalse) { InheritException(exception,&colorize_image->exception); colorize_image=DestroyImage(colorize_image); return((Image *) NULL); } if ((IsGrayColorspace(image->colorspace) != MagickFalse) || (IsPixelGray(&colorize) != MagickFalse)) (void) SetImageColorspace(colorize_image,sRGBColorspace); if ((colorize_image->matte == MagickFalse) && (colorize.opacity != OpaqueOpacity)) (void) SetImageAlphaChannel(colorize_image,OpaqueAlphaChannel); if (opacity == (const char *) NULL) return(colorize_image); /* Determine RGB values of the pen color. */ flags=ParseGeometry(opacity,&geometry_info); pixel.red=geometry_info.rho; pixel.green=geometry_info.rho; pixel.blue=geometry_info.rho; pixel.opacity=(MagickRealType) OpaqueOpacity; if ((flags & SigmaValue) != 0) pixel.green=geometry_info.sigma; if ((flags & XiValue) != 0) pixel.blue=geometry_info.xi; if ((flags & PsiValue) != 0) pixel.opacity=geometry_info.psi; /* Colorize DirectClass image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); colorize_view=AcquireAuthenticCacheView(colorize_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,colorize_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register const PixelPacket *magick_restrict p; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(colorize_view,0,y,colorize_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,((GetPixelRed(p)*(100.0-pixel.red)+ colorize.red*pixel.red)/100.0)); SetPixelGreen(q,((GetPixelGreen(p)*(100.0-pixel.green)+ colorize.green*pixel.green)/100.0)); SetPixelBlue(q,((GetPixelBlue(p)*(100.0-pixel.blue)+ colorize.blue*pixel.blue)/100.0)); if (colorize_image->matte == MagickFalse) SetPixelOpacity(q,GetPixelOpacity(p)); else SetPixelOpacity(q,((GetPixelOpacity(p)*(100.0-pixel.opacity)+ colorize.opacity*pixel.opacity)/100.0)); p++; q++; } sync=SyncCacheViewAuthenticPixels(colorize_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ColorizeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); colorize_view=DestroyCacheView(colorize_view); if (status == MagickFalse) colorize_image=DestroyImage(colorize_image); return(colorize_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o l o r M a t r i x I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ColorMatrixImage() applies color transformation to an image. This method % permits saturation changes, hue rotation, luminance to alpha, and various % other effects. Although variable-sized transformation matrices can be used, % typically one uses a 5x5 matrix for an RGBA image and a 6x6 for CMYKA % (or RGBA with offsets). The matrix is similar to those used by Adobe Flash % except offsets are in column 6 rather than 5 (in support of CMYKA images) % and offsets are normalized (divide Flash offset by 255). % % The format of the ColorMatrixImage method is: % % Image *ColorMatrixImage(const Image *image, % const KernelInfo *color_matrix,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o color_matrix: the color matrix. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ColorMatrixImage(const Image *image, const KernelInfo *color_matrix,ExceptionInfo *exception) { #define ColorMatrixImageTag "ColorMatrix/Image" CacheView *color_view, *image_view; double ColorMatrix[6][6] = { { 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 }, { 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 }, { 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }, { 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 } }; Image *color_image; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t u, v, y; /* Create color matrix. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); i=0; for (v=0; v < (ssize_t) color_matrix->height; v++) for (u=0; u < (ssize_t) color_matrix->width; u++) { if ((v < 6) && (u < 6)) ColorMatrix[v][u]=color_matrix->values[i]; i++; } /* Initialize color image. */ color_image=CloneImage(image,0,0,MagickTrue,exception); if (color_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(color_image,DirectClass) == MagickFalse) { InheritException(exception,&color_image->exception); color_image=DestroyImage(color_image); return((Image *) NULL); } if (image->debug != MagickFalse) { char format[MaxTextExtent], *message; (void) LogMagickEvent(TransformEvent,GetMagickModule(), " ColorMatrix image with color matrix:"); message=AcquireString(""); for (v=0; v < 6; v++) { *message='\0'; (void) FormatLocaleString(format,MaxTextExtent,"%.20g: ",(double) v); (void) ConcatenateString(&message,format); for (u=0; u < 6; u++) { (void) FormatLocaleString(format,MaxTextExtent,"%+f ", ColorMatrix[v][u]); (void) ConcatenateString(&message,format); } (void) LogMagickEvent(TransformEvent,GetMagickModule(),"%s",message); } message=DestroyString(message); } /* ColorMatrix image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); color_view=AcquireAuthenticCacheView(color_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,color_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickRealType pixel; register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; register IndexPacket *magick_restrict color_indexes; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(color_view,0,y,color_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); color_indexes=GetCacheViewAuthenticIndexQueue(color_view); for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t v; size_t height; height=color_matrix->height > 6 ? 6UL : color_matrix->height; for (v=0; v < (ssize_t) height; v++) { pixel=ColorMatrix[v][0]*GetPixelRed(p)+ColorMatrix[v][1]* GetPixelGreen(p)+ColorMatrix[v][2]*GetPixelBlue(p); if (image->matte != MagickFalse) pixel+=ColorMatrix[v][3]*(QuantumRange-GetPixelOpacity(p)); if (image->colorspace == CMYKColorspace) pixel+=ColorMatrix[v][4]*GetPixelIndex(indexes+x); pixel+=QuantumRange*ColorMatrix[v][5]; switch (v) { case 0: SetPixelRed(q,ClampToQuantum(pixel)); break; case 1: SetPixelGreen(q,ClampToQuantum(pixel)); break; case 2: SetPixelBlue(q,ClampToQuantum(pixel)); break; case 3: { if (image->matte != MagickFalse) SetPixelAlpha(q,ClampToQuantum(pixel)); break; } case 4: { if (image->colorspace == CMYKColorspace) SetPixelIndex(color_indexes+x,ClampToQuantum(pixel)); break; } } } p++; q++; } if (SyncCacheViewAuthenticPixels(color_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ColorMatrixImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } color_view=DestroyCacheView(color_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) color_image=DestroyImage(color_image); return(color_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y F x I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyFxInfo() deallocates memory associated with an FxInfo structure. % % The format of the DestroyFxInfo method is: % % ImageInfo *DestroyFxInfo(ImageInfo *fx_info) % % A description of each parameter follows: % % o fx_info: the fx info. % */ MagickExport FxInfo *DestroyFxInfo(FxInfo *fx_info) { register ssize_t i; fx_info->exception=DestroyExceptionInfo(fx_info->exception); fx_info->expression=DestroyString(fx_info->expression); fx_info->symbols=DestroySplayTree(fx_info->symbols); fx_info->colors=DestroySplayTree(fx_info->colors); for (i=(ssize_t) GetImageListLength(fx_info->images)-1; i >= 0; i--) fx_info->view[i]=DestroyCacheView(fx_info->view[i]); fx_info->view=(CacheView **) RelinquishMagickMemory(fx_info->view); fx_info->random_info=DestroyRandomInfo(fx_info->random_info); fx_info=(FxInfo *) RelinquishMagickMemory(fx_info); return(fx_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + F x E v a l u a t e C h a n n e l E x p r e s s i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FxEvaluateChannelExpression() evaluates an expression and returns the % results. % % The format of the FxEvaluateExpression method is: % % MagickBooleanType FxEvaluateChannelExpression(FxInfo *fx_info, % const ChannelType channel,const ssize_t x,const ssize_t y, % double *alpha,Exceptioninfo *exception) % MagickBooleanType FxEvaluateExpression(FxInfo *fx_info,double *alpha, % Exceptioninfo *exception) % % A description of each parameter follows: % % o fx_info: the fx info. % % o channel: the channel. % % o x,y: the pixel position. % % o alpha: the result. % % o exception: return any errors or warnings in this structure. % */ static double FxChannelStatistics(FxInfo *fx_info,const Image *image, ChannelType channel,const char *symbol,ExceptionInfo *exception) { char channel_symbol[MaxTextExtent], key[MaxTextExtent], statistic[MaxTextExtent]; const char *value; register const char *p; for (p=symbol; (*p != '.') && (*p != '\0'); p++) ; *channel_symbol='\0'; if (*p == '.') { ssize_t option; (void) CopyMagickString(channel_symbol,p+1,MaxTextExtent); option=ParseCommandOption(MagickChannelOptions,MagickTrue,channel_symbol); if (option >= 0) channel=(ChannelType) option; } (void) FormatLocaleString(key,MaxTextExtent,"%p.%.20g.%s",(void *) image, (double) channel,symbol); value=(const char *) GetValueFromSplayTree(fx_info->symbols,key); if (value != (const char *) NULL) return(QuantumScale*StringToDouble(value,(char **) NULL)); (void) DeleteNodeFromSplayTree(fx_info->symbols,key); if (LocaleNCompare(symbol,"depth",5) == 0) { size_t depth; depth=GetImageChannelDepth(image,channel,exception); (void) FormatLocaleString(statistic,MaxTextExtent,"%.20g",(double) depth); } if (LocaleNCompare(symbol,"kurtosis",8) == 0) { double kurtosis, skewness; (void) GetImageChannelKurtosis(image,channel,&kurtosis,&skewness, exception); (void) FormatLocaleString(statistic,MaxTextExtent,"%.20g",kurtosis); } if (LocaleNCompare(symbol,"maxima",6) == 0) { double maxima, minima; (void) GetImageChannelRange(image,channel,&minima,&maxima,exception); (void) FormatLocaleString(statistic,MaxTextExtent,"%.20g",maxima); } if (LocaleNCompare(symbol,"mean",4) == 0) { double mean, standard_deviation; (void) GetImageChannelMean(image,channel,&mean,&standard_deviation, exception); (void) FormatLocaleString(statistic,MaxTextExtent,"%.20g",mean); } if (LocaleNCompare(symbol,"minima",6) == 0) { double maxima, minima; (void) GetImageChannelRange(image,channel,&minima,&maxima,exception); (void) FormatLocaleString(statistic,MaxTextExtent,"%.20g",minima); } if (LocaleNCompare(symbol,"skewness",8) == 0) { double kurtosis, skewness; (void) GetImageChannelKurtosis(image,channel,&kurtosis,&skewness, exception); (void) FormatLocaleString(statistic,MaxTextExtent,"%.20g",skewness); } if (LocaleNCompare(symbol,"standard_deviation",18) == 0) { double mean, standard_deviation; (void) GetImageChannelMean(image,channel,&mean,&standard_deviation, exception); (void) FormatLocaleString(statistic,MaxTextExtent,"%.20g", standard_deviation); } (void) AddValueToSplayTree(fx_info->symbols,ConstantString(key), ConstantString(statistic)); return(QuantumScale*StringToDouble(statistic,(char **) NULL)); } static double FxEvaluateSubexpression(FxInfo *,const ChannelType,const ssize_t, const ssize_t,const char *,const size_t,double *,ExceptionInfo *); static MagickOffsetType FxGCD(MagickOffsetType alpha,MagickOffsetType beta) { if (beta != 0) return(FxGCD(beta,alpha % beta)); return(alpha); } static inline const char *FxSubexpression(const char *expression, ExceptionInfo *exception) { const char *subexpression; register ssize_t level; level=0; subexpression=expression; while ((*subexpression != '\0') && ((level != 1) || (strchr(")",(int) *subexpression) == (char *) NULL))) { if (strchr("(",(int) *subexpression) != (char *) NULL) level++; else if (strchr(")",(int) *subexpression) != (char *) NULL) level--; subexpression++; } if (*subexpression == '\0') (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "UnbalancedParenthesis","`%s'",expression); return(subexpression); } static double FxGetSymbol(FxInfo *fx_info,const ChannelType channel, const ssize_t x,const ssize_t y,const char *expression,const size_t depth, ExceptionInfo *exception) { char *q, symbol[MaxTextExtent]; const char *p, *value; double alpha, beta; Image *image; MagickBooleanType status; MagickPixelPacket pixel; PointInfo point; register ssize_t i; size_t level; p=expression; i=GetImageIndexInList(fx_info->images); level=0; point.x=(double) x; point.y=(double) y; if (isalpha((int) ((unsigned char) *(p+1))) == 0) { char *subexpression; subexpression=AcquireString(expression); if (strchr("suv",(int) *p) != (char *) NULL) { switch (*p) { case 's': default: { i=GetImageIndexInList(fx_info->images); break; } case 'u': i=0; break; case 'v': i=1; break; } p++; if (*p == '[') { level++; q=subexpression; for (p++; *p != '\0'; ) { if (*p == '[') level++; else if (*p == ']') { level--; if (level == 0) break; } *q++=(*p++); } *q='\0'; alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression, depth,&beta,exception); i=(ssize_t) alpha; if (*p != '\0') p++; } if (*p == '.') p++; } if ((*p == 'p') && (isalpha((int) ((unsigned char) *(p+1))) == 0)) { p++; if (*p == '{') { level++; q=subexpression; for (p++; *p != '\0'; ) { if (*p == '{') level++; else if (*p == '}') { level--; if (level == 0) break; } *q++=(*p++); } *q='\0'; alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression, depth,&beta,exception); point.x=alpha; point.y=beta; if (*p != '\0') p++; } else if (*p == '[') { level++; q=subexpression; for (p++; *p != '\0'; ) { if (*p == '[') level++; else if (*p == ']') { level--; if (level == 0) break; } *q++=(*p++); } *q='\0'; alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression, depth,&beta,exception); point.x+=alpha; point.y+=beta; if (*p != '\0') p++; } if (*p == '.') p++; } subexpression=DestroyString(subexpression); } image=GetImageFromList(fx_info->images,i); if (image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "NoSuchImage","`%s'",expression); return(0.0); } i=GetImageIndexInList(image); GetMagickPixelPacket(image,&pixel); status=InterpolateMagickPixelPacket(image,fx_info->view[i],image->interpolate, point.x,point.y,&pixel,exception); (void) status; if ((strlen(p) > 2) && (LocaleCompare(p,"intensity") != 0) && (LocaleCompare(p,"luma") != 0) && (LocaleCompare(p,"luminance") != 0) && (LocaleCompare(p,"hue") != 0) && (LocaleCompare(p,"saturation") != 0) && (LocaleCompare(p,"lightness") != 0)) { char name[MaxTextExtent]; (void) CopyMagickString(name,p,MaxTextExtent); for (q=name+(strlen(name)-1); q > name; q--) { if (*q == ')') break; if (*q == '.') { *q='\0'; break; } } if ((strlen(name) > 2) && (GetValueFromSplayTree(fx_info->symbols,name) == (const char *) NULL)) { MagickPixelPacket *color; color=(MagickPixelPacket *) GetValueFromSplayTree(fx_info->colors, name); if (color != (MagickPixelPacket *) NULL) { pixel=(*color); p+=strlen(name); } else if (QueryMagickColor(name,&pixel,fx_info->exception) != MagickFalse) { (void) AddValueToSplayTree(fx_info->colors,ConstantString(name), CloneMagickPixelPacket(&pixel)); p+=strlen(name); } } } (void) CopyMagickString(symbol,p,MaxTextExtent); StripString(symbol); if (*symbol == '\0') { switch (channel) { case RedChannel: return(QuantumScale*pixel.red); case GreenChannel: return(QuantumScale*pixel.green); case BlueChannel: return(QuantumScale*pixel.blue); case OpacityChannel: { double alpha; if (pixel.matte == MagickFalse) return(1.0); alpha=(double) (QuantumScale*GetPixelAlpha(&pixel)); return(alpha); } case IndexChannel: { if (image->colorspace != CMYKColorspace) { (void) ThrowMagickException(exception,GetMagickModule(), ImageError,"ColorSeparatedImageRequired","`%s'", image->filename); return(0.0); } return(QuantumScale*pixel.index); } case DefaultChannels: return(QuantumScale*GetMagickPixelIntensity(image,&pixel)); default: break; } (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "UnableToParseExpression","`%s'",p); return(0.0); } switch (*symbol) { case 'A': case 'a': { if (LocaleCompare(symbol,"a") == 0) return((double) (QuantumScale*GetPixelAlpha(&pixel))); break; } case 'B': case 'b': { if (LocaleCompare(symbol,"b") == 0) return(QuantumScale*pixel.blue); break; } case 'C': case 'c': { if (LocaleNCompare(symbol,"channel",7) == 0) { GeometryInfo channel_info; MagickStatusType flags; flags=ParseGeometry(symbol+7,&channel_info); if (image->colorspace == CMYKColorspace) switch (channel) { case CyanChannel: { if ((flags & RhoValue) == 0) return(0.0); return(channel_info.rho); } case MagentaChannel: { if ((flags & SigmaValue) == 0) return(0.0); return(channel_info.sigma); } case YellowChannel: { if ((flags & XiValue) == 0) return(0.0); return(channel_info.xi); } case BlackChannel: { if ((flags & PsiValue) == 0) return(0.0); return(channel_info.psi); } case OpacityChannel: { if ((flags & ChiValue) == 0) return(0.0); return(channel_info.chi); } default: return(0.0); } switch (channel) { case RedChannel: { if ((flags & RhoValue) == 0) return(0.0); return(channel_info.rho); } case GreenChannel: { if ((flags & SigmaValue) == 0) return(0.0); return(channel_info.sigma); } case BlueChannel: { if ((flags & XiValue) == 0) return(0.0); return(channel_info.xi); } case OpacityChannel: { if ((flags & PsiValue) == 0) return(0.0); return(channel_info.psi); } case IndexChannel: { if ((flags & ChiValue) == 0) return(0.0); return(channel_info.chi); } default: return(0.0); } } if (LocaleCompare(symbol,"c") == 0) return(QuantumScale*pixel.red); break; } case 'D': case 'd': { if (LocaleNCompare(symbol,"depth",5) == 0) return(FxChannelStatistics(fx_info,image,channel,symbol,exception)); break; } case 'E': case 'e': { if (LocaleCompare(symbol,"extent") == 0) { if (image->extent != 0) return((double) image->extent); return((double) GetBlobSize(image)); } break; } case 'G': case 'g': { if (LocaleCompare(symbol,"g") == 0) return(QuantumScale*pixel.green); break; } case 'K': case 'k': { if (LocaleNCompare(symbol,"kurtosis",8) == 0) return(FxChannelStatistics(fx_info,image,channel,symbol,exception)); if (LocaleCompare(symbol,"k") == 0) { if (image->colorspace != CMYKColorspace) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"ColorSeparatedImageRequired","`%s'", image->filename); return(0.0); } return(QuantumScale*pixel.index); } break; } case 'H': case 'h': { if (LocaleCompare(symbol,"h") == 0) return((double) image->rows); if (LocaleCompare(symbol,"hue") == 0) { double hue, lightness, saturation; ConvertRGBToHSL(ClampToQuantum(pixel.red),ClampToQuantum(pixel.green), ClampToQuantum(pixel.blue),&hue,&saturation,&lightness); return(hue); } break; } case 'I': case 'i': { if ((LocaleCompare(symbol,"image.depth") == 0) || (LocaleCompare(symbol,"image.minima") == 0) || (LocaleCompare(symbol,"image.maxima") == 0) || (LocaleCompare(symbol,"image.mean") == 0) || (LocaleCompare(symbol,"image.kurtosis") == 0) || (LocaleCompare(symbol,"image.skewness") == 0) || (LocaleCompare(symbol,"image.standard_deviation") == 0)) return(FxChannelStatistics(fx_info,image,channel,symbol+6,exception)); if (LocaleCompare(symbol,"image.resolution.x") == 0) return(image->x_resolution); if (LocaleCompare(symbol,"image.resolution.y") == 0) return(image->y_resolution); if (LocaleCompare(symbol,"intensity") == 0) return(QuantumScale*GetMagickPixelIntensity(image,&pixel)); if (LocaleCompare(symbol,"i") == 0) return((double) x); break; } case 'J': case 'j': { if (LocaleCompare(symbol,"j") == 0) return((double) y); break; } case 'L': case 'l': { if (LocaleCompare(symbol,"lightness") == 0) { double hue, lightness, saturation; ConvertRGBToHSL(ClampToQuantum(pixel.red),ClampToQuantum(pixel.green), ClampToQuantum(pixel.blue),&hue,&saturation,&lightness); return(lightness); } if (LocaleCompare(symbol,"luma") == 0) { double luma; luma=0.212656*pixel.red+0.715158*pixel.green+0.072186*pixel.blue; return(QuantumScale*luma); } if (LocaleCompare(symbol,"luminance") == 0) { double luminance; luminance=0.212656*pixel.red+0.715158*pixel.green+0.072186*pixel.blue; return(QuantumScale*luminance); } break; } case 'M': case 'm': { if (LocaleNCompare(symbol,"maxima",6) == 0) return(FxChannelStatistics(fx_info,image,channel,symbol,exception)); if (LocaleNCompare(symbol,"mean",4) == 0) return(FxChannelStatistics(fx_info,image,channel,symbol,exception)); if (LocaleNCompare(symbol,"minima",6) == 0) return(FxChannelStatistics(fx_info,image,channel,symbol,exception)); if (LocaleCompare(symbol,"m") == 0) return(QuantumScale*pixel.green); break; } case 'N': case 'n': { if (LocaleCompare(symbol,"n") == 0) return((double) GetImageListLength(fx_info->images)); break; } case 'O': case 'o': { if (LocaleCompare(symbol,"o") == 0) return(QuantumScale*pixel.opacity); break; } case 'P': case 'p': { if (LocaleCompare(symbol,"page.height") == 0) return((double) image->page.height); if (LocaleCompare(symbol,"page.width") == 0) return((double) image->page.width); if (LocaleCompare(symbol,"page.x") == 0) return((double) image->page.x); if (LocaleCompare(symbol,"page.y") == 0) return((double) image->page.y); if (LocaleCompare(symbol,"printsize.x") == 0) return(PerceptibleReciprocal(image->x_resolution)*image->columns); if (LocaleCompare(symbol,"printsize.y") == 0) return(PerceptibleReciprocal(image->y_resolution)*image->rows); break; } case 'Q': case 'q': { if (LocaleCompare(symbol,"quality") == 0) return((double) image->quality); break; } case 'R': case 'r': { if (LocaleCompare(symbol,"resolution.x") == 0) return(image->x_resolution); if (LocaleCompare(symbol,"resolution.y") == 0) return(image->y_resolution); if (LocaleCompare(symbol,"r") == 0) return(QuantumScale*pixel.red); break; } case 'S': case 's': { if (LocaleCompare(symbol,"saturation") == 0) { double hue, lightness, saturation; ConvertRGBToHSL(ClampToQuantum(pixel.red),ClampToQuantum(pixel.green), ClampToQuantum(pixel.blue),&hue,&saturation,&lightness); return(saturation); } if (LocaleNCompare(symbol,"skewness",8) == 0) return(FxChannelStatistics(fx_info,image,channel,symbol,exception)); if (LocaleNCompare(symbol,"standard_deviation",18) == 0) return(FxChannelStatistics(fx_info,image,channel,symbol,exception)); break; } case 'T': case 't': { if (LocaleCompare(symbol,"t") == 0) return((double) GetImageIndexInList(fx_info->images)); break; } case 'W': case 'w': { if (LocaleCompare(symbol,"w") == 0) return((double) image->columns); break; } case 'Y': case 'y': { if (LocaleCompare(symbol,"y") == 0) return(QuantumScale*pixel.blue); break; } case 'Z': case 'z': { if (LocaleCompare(symbol,"z") == 0) { double depth; depth=(double) GetImageChannelDepth(image,channel,fx_info->exception); return(depth); } break; } default: break; } value=(const char *) GetValueFromSplayTree(fx_info->symbols,symbol); if (value != (const char *) NULL) return(StringToDouble(value,(char **) NULL)); (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "UnableToParseExpression","`%s'",symbol); return(0.0); } static const char *FxOperatorPrecedence(const char *expression, ExceptionInfo *exception) { typedef enum { UndefinedPrecedence, NullPrecedence, BitwiseComplementPrecedence, ExponentPrecedence, ExponentialNotationPrecedence, MultiplyPrecedence, AdditionPrecedence, ShiftPrecedence, RelationalPrecedence, EquivalencyPrecedence, BitwiseAndPrecedence, BitwiseOrPrecedence, LogicalAndPrecedence, LogicalOrPrecedence, TernaryPrecedence, AssignmentPrecedence, CommaPrecedence, SeparatorPrecedence } FxPrecedence; FxPrecedence precedence, target; register const char *subexpression; register int c; size_t level; c=(-1); level=0; subexpression=(const char *) NULL; target=NullPrecedence; while ((c != '\0') && (*expression != '\0')) { precedence=UndefinedPrecedence; if ((isspace((int) ((unsigned char) *expression)) != 0) || (c == (int) '@')) { expression++; continue; } switch (*expression) { case 'A': case 'a': { #if defined(MAGICKCORE_HAVE_ACOSH) if (LocaleNCompare(expression,"acosh",5) == 0) { expression+=5; break; } #endif #if defined(MAGICKCORE_HAVE_ASINH) if (LocaleNCompare(expression,"asinh",5) == 0) { expression+=5; break; } #endif #if defined(MAGICKCORE_HAVE_ATANH) if (LocaleNCompare(expression,"atanh",5) == 0) { expression+=5; break; } #endif if (LocaleNCompare(expression,"atan2",5) == 0) { expression+=5; break; } break; } case 'E': case 'e': { if ((isdigit(c) != 0) && ((LocaleNCompare(expression,"E+",2) == 0) || (LocaleNCompare(expression,"E-",2) == 0))) { expression+=2; /* scientific notation */ break; } } case 'J': case 'j': { if ((LocaleNCompare(expression,"j0",2) == 0) || (LocaleNCompare(expression,"j1",2) == 0)) { expression+=2; break; } break; } case '#': { while (isxdigit((int) ((unsigned char) *(expression+1))) != 0) expression++; break; } default: break; } if ((c == (int) '{') || (c == (int) '[')) level++; else if ((c == (int) '}') || (c == (int) ']')) level--; if (level == 0) switch ((unsigned char) *expression) { case '~': case '!': { precedence=BitwiseComplementPrecedence; break; } case '^': case '@': { precedence=ExponentPrecedence; break; } default: { if (((c != 0) && ((isdigit(c) != 0) || (strchr(")",c) != (char *) NULL))) && (((islower((int) ((unsigned char) *expression)) != 0) || (strchr("(",(int) ((unsigned char) *expression)) != (char *) NULL)) || ((isdigit(c) == 0) && (isdigit((int) ((unsigned char) *expression)) != 0))) && (strchr("xy",(int) ((unsigned char) *expression)) == (char *) NULL)) precedence=MultiplyPrecedence; break; } case '*': case '/': case '%': { precedence=MultiplyPrecedence; break; } case '+': case '-': { if ((strchr("(+-/*%:&^|<>~,",c) == (char *) NULL) || (isalpha(c) != 0)) precedence=AdditionPrecedence; break; } case LeftShiftOperator: case RightShiftOperator: { precedence=ShiftPrecedence; break; } case '<': case LessThanEqualOperator: case GreaterThanEqualOperator: case '>': { precedence=RelationalPrecedence; break; } case EqualOperator: case NotEqualOperator: { precedence=EquivalencyPrecedence; break; } case '&': { precedence=BitwiseAndPrecedence; break; } case '|': { precedence=BitwiseOrPrecedence; break; } case LogicalAndOperator: { precedence=LogicalAndPrecedence; break; } case LogicalOrOperator: { precedence=LogicalOrPrecedence; break; } case ExponentialNotation: { precedence=ExponentialNotationPrecedence; break; } case ':': case '?': { precedence=TernaryPrecedence; break; } case '=': { precedence=AssignmentPrecedence; break; } case ',': { precedence=CommaPrecedence; break; } case ';': { precedence=SeparatorPrecedence; break; } } if ((precedence == BitwiseComplementPrecedence) || (precedence == TernaryPrecedence) || (precedence == AssignmentPrecedence)) { if (precedence > target) { /* Right-to-left associativity. */ target=precedence; subexpression=expression; } } else if (precedence >= target) { /* Left-to-right associativity. */ target=precedence; subexpression=expression; } if (strchr("(",(int) *expression) != (char *) NULL) expression=FxSubexpression(expression,exception); c=(int) (*expression++); } return(subexpression); } static double FxEvaluateSubexpression(FxInfo *fx_info,const ChannelType channel, const ssize_t x,const ssize_t y,const char *expression,const size_t depth, double *beta,ExceptionInfo *exception) { #define FxMaxParenthesisDepth 58 #define FxMaxSubexpressionDepth 200 #define FxReturn(value) \ { \ subexpression=DestroyString(subexpression); \ return(value); \ } char *q, *subexpression; double alpha, gamma; register const char *p; *beta=0.0; subexpression=AcquireString(expression); *subexpression='\0'; if (depth > FxMaxSubexpressionDepth) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "UnableToParseExpression","`%s'",expression); FxReturn(0.0); } if (exception->severity >= ErrorException) FxReturn(0.0); while (isspace((int) ((unsigned char) *expression)) != 0) expression++; if (*expression == '\0') FxReturn(0.0); p=FxOperatorPrecedence(expression,exception); if (p != (const char *) NULL) { (void) CopyMagickString(subexpression,expression,(size_t) (p-expression+1)); alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,depth+1, beta,exception); switch ((unsigned char) *p) { case '~': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); *beta=(double) (~(size_t) *beta); FxReturn(*beta); } case '!': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); FxReturn(*beta == 0.0 ? 1.0 : 0.0); } case '^': { *beta=pow(alpha,FxEvaluateSubexpression(fx_info,channel,x,y,++p, depth+1,beta,exception)); FxReturn(*beta); } case '*': case ExponentialNotation: { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); FxReturn(alpha*(*beta)); } case '/': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); if (*beta == 0.0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"DivideByZero","`%s'",expression); FxReturn(0.0); } FxReturn(alpha/(*beta)); } case '%': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); *beta=fabs(floor((*beta)+0.5)); if (*beta == 0.0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"DivideByZero","`%s'",expression); FxReturn(0.0); } FxReturn(fmod(alpha,(double) *beta)); } case '+': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); FxReturn(alpha+(*beta)); } case '-': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); FxReturn(alpha-(*beta)); } case LeftShiftOperator: { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); if ((size_t) (gamma+0.5) > (8*sizeof(size_t))) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"ShiftCountOverflow","`%s'",subexpression); FxReturn(0.0); } *beta=(double) ((size_t) (alpha+0.5) << (size_t) (gamma+0.5)); FxReturn(*beta); } case RightShiftOperator: { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); if ((size_t) (gamma+0.5) > (8*sizeof(size_t))) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"ShiftCountOverflow","`%s'",subexpression); FxReturn(0.0); } *beta=(double) ((size_t) (alpha+0.5) >> (size_t) (gamma+0.5)); FxReturn(*beta); } case '<': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); FxReturn(alpha < *beta ? 1.0 : 0.0); } case LessThanEqualOperator: { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); FxReturn(alpha <= *beta ? 1.0 : 0.0); } case '>': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); FxReturn(alpha > *beta ? 1.0 : 0.0); } case GreaterThanEqualOperator: { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); FxReturn(alpha >= *beta ? 1.0 : 0.0); } case EqualOperator: { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); FxReturn(fabs(alpha-(*beta)) < MagickEpsilon ? 1.0 : 0.0); } case NotEqualOperator: { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); FxReturn(fabs(alpha-(*beta)) >= MagickEpsilon ? 1.0 : 0.0); } case '&': { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); *beta=(double) ((size_t) (alpha+0.5) & (size_t) (gamma+0.5)); FxReturn(*beta); } case '|': { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); *beta=(double) ((size_t) (alpha+0.5) | (size_t) (gamma+0.5)); FxReturn(*beta); } case LogicalAndOperator: { p++; if (alpha <= 0.0) { *beta=0.0; FxReturn(*beta); } gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,beta, exception); *beta=(gamma > 0.0) ? 1.0 : 0.0; FxReturn(*beta); } case LogicalOrOperator: { p++; if (alpha > 0.0) { *beta=1.0; FxReturn(*beta); } gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,beta, exception); *beta=(gamma > 0.0) ? 1.0 : 0.0; FxReturn(*beta); } case '?': { double gamma; (void) CopyMagickString(subexpression,++p,MaxTextExtent); q=subexpression; p=StringToken(":",&q); if (q == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"UnableToParseExpression","`%s'",subexpression); FxReturn(0.0); } if (fabs(alpha) >= MagickEpsilon) gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,beta, exception); else gamma=FxEvaluateSubexpression(fx_info,channel,x,y,q,depth+1,beta, exception); FxReturn(gamma); } case '=': { char numeric[MaxTextExtent]; q=subexpression; while (isalpha((int) ((unsigned char) *q)) != 0) q++; if (*q != '\0') { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"UnableToParseExpression","`%s'",subexpression); FxReturn(0.0); } ClearMagickException(exception); *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); (void) FormatLocaleString(numeric,MaxTextExtent,"%.20g",(double) *beta); (void) DeleteNodeFromSplayTree(fx_info->symbols,subexpression); (void) AddValueToSplayTree(fx_info->symbols,ConstantString( subexpression),ConstantString(numeric)); FxReturn(*beta); } case ',': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); FxReturn(alpha); } case ';': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); FxReturn(*beta); } default: { gamma=alpha*FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1, beta,exception); FxReturn(gamma); } } } if (strchr("(",(int) *expression) != (char *) NULL) { if (depth >= FxMaxParenthesisDepth) (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "ParenthesisNestedTooDeeply","`%s'",expression); (void) CopyMagickString(subexpression,expression+1,MaxTextExtent); if (strlen(subexpression) != 0) subexpression[strlen(subexpression)-1]='\0'; gamma=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,depth+1, beta,exception); FxReturn(gamma); } switch (*expression) { case '+': { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,depth+1, beta,exception); FxReturn(1.0*gamma); } case '-': { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,depth+1, beta,exception); FxReturn(-1.0*gamma); } case '~': { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,depth+1, beta,exception); FxReturn((double) (~(size_t) (gamma+0.5))); } case 'A': case 'a': { if (LocaleNCompare(expression,"abs",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); FxReturn(fabs(alpha)); } #if defined(MAGICKCORE_HAVE_ACOSH) if (LocaleNCompare(expression,"acosh",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5, depth+1,beta,exception); FxReturn(acosh(alpha)); } #endif if (LocaleNCompare(expression,"acos",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4, depth+1,beta,exception); FxReturn(acos(alpha)); } #if defined(MAGICKCORE_HAVE_J1) if (LocaleNCompare(expression,"airy",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4, depth+1,beta,exception); if (alpha == 0.0) FxReturn(1.0); gamma=2.0*j1((MagickPI*alpha))/(MagickPI*alpha); FxReturn(gamma*gamma); } #endif #if defined(MAGICKCORE_HAVE_ASINH) if (LocaleNCompare(expression,"asinh",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5, depth+1,beta,exception); FxReturn(asinh(alpha)); } #endif if (LocaleNCompare(expression,"asin",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4, depth+1,beta,exception); FxReturn(asin(alpha)); } if (LocaleNCompare(expression,"alt",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); FxReturn(((ssize_t) alpha) & 0x01 ? -1.0 : 1.0); } if (LocaleNCompare(expression,"atan2",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5, depth+1,beta,exception); FxReturn(atan2(alpha,*beta)); } #if defined(MAGICKCORE_HAVE_ATANH) if (LocaleNCompare(expression,"atanh",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5, depth+1,beta,exception); FxReturn(atanh(alpha)); } #endif if (LocaleNCompare(expression,"atan",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4, depth+1,beta,exception); FxReturn(atan(alpha)); } if (LocaleCompare(expression,"a") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); break; } case 'B': case 'b': { if (LocaleCompare(expression,"b") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); break; } case 'C': case 'c': { if (LocaleNCompare(expression,"ceil",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4, depth+1,beta,exception); FxReturn(ceil(alpha)); } if (LocaleNCompare(expression,"clamp",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5, depth+1,beta,exception); if (alpha < 0.0) FxReturn(0.0); if (alpha > 1.0) FxReturn(1.0); FxReturn(alpha); } if (LocaleNCompare(expression,"cosh",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4, depth+1,beta,exception); FxReturn(cosh(alpha)); } if (LocaleNCompare(expression,"cos",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); FxReturn(cos(alpha)); } if (LocaleCompare(expression,"c") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); break; } case 'D': case 'd': { if (LocaleNCompare(expression,"debug",5) == 0) { const char *type; alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5, depth+1,beta,exception); if (fx_info->images->colorspace == CMYKColorspace) switch (channel) { case CyanChannel: type="cyan"; break; case MagentaChannel: type="magenta"; break; case YellowChannel: type="yellow"; break; case OpacityChannel: type="opacity"; break; case BlackChannel: type="black"; break; default: type="unknown"; break; } else switch (channel) { case RedChannel: type="red"; break; case GreenChannel: type="green"; break; case BlueChannel: type="blue"; break; case OpacityChannel: type="opacity"; break; default: type="unknown"; break; } *subexpression='\0'; if (strlen(subexpression) > 1) (void) CopyMagickString(subexpression,expression+6,MaxTextExtent); if (strlen(subexpression) > 1) subexpression[strlen(subexpression)-1]='\0'; if (fx_info->file != (FILE *) NULL) (void) FormatLocaleFile(fx_info->file, "%s[%.20g,%.20g].%s: %s=%.*g\n",fx_info->images->filename, (double) x,(double) y,type,subexpression,GetMagickPrecision(), (double) alpha); FxReturn(0.0); } if (LocaleNCompare(expression,"drc",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); FxReturn((alpha/(*beta*(alpha-1.0)+1.0))); } break; } case 'E': case 'e': { if (LocaleCompare(expression,"epsilon") == 0) FxReturn(MagickEpsilon); #if defined(MAGICKCORE_HAVE_ERF) if (LocaleNCompare(expression,"erp",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); FxReturn(erf(alpha)); } #endif if (LocaleNCompare(expression,"exp",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); FxReturn(exp(alpha)); } if (LocaleCompare(expression,"e") == 0) FxReturn(2.7182818284590452354); break; } case 'F': case 'f': { if (LocaleNCompare(expression,"floor",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5, depth+1,beta,exception); FxReturn(floor(alpha)); } break; } case 'G': case 'g': { if (LocaleNCompare(expression,"gauss",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5, depth+1,beta,exception); gamma=exp((-alpha*alpha/2.0))/sqrt(2.0*MagickPI); FxReturn(gamma); } if (LocaleNCompare(expression,"gcd",3) == 0) { MagickOffsetType gcd; alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); gcd=FxGCD((MagickOffsetType) (alpha+0.5),(MagickOffsetType) (*beta+0.5)); FxReturn((double) gcd); } if (LocaleCompare(expression,"g") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); break; } case 'H': case 'h': { if (LocaleCompare(expression,"h") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); if (LocaleCompare(expression,"hue") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); if (LocaleNCompare(expression,"hypot",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5, depth+1,beta,exception); FxReturn(hypot(alpha,*beta)); } break; } case 'K': case 'k': { if (LocaleCompare(expression,"k") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); break; } case 'I': case 'i': { if (LocaleCompare(expression,"intensity") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); if (LocaleNCompare(expression,"int",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); FxReturn(floor(alpha)); } if (LocaleNCompare(expression,"isnan",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5, depth+1,beta,exception); FxReturn((double) !!IsNaN(alpha)); } if (LocaleCompare(expression,"i") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); break; } case 'J': case 'j': { if (LocaleCompare(expression,"j") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); #if defined(MAGICKCORE_HAVE_J0) if (LocaleNCompare(expression,"j0",2) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2, depth+1,beta,exception); FxReturn(j0(alpha)); } #endif #if defined(MAGICKCORE_HAVE_J1) if (LocaleNCompare(expression,"j1",2) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2, depth+1,beta,exception); FxReturn(j1(alpha)); } #endif #if defined(MAGICKCORE_HAVE_J1) if (LocaleNCompare(expression,"jinc",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4, depth+1,beta,exception); if (alpha == 0.0) FxReturn(1.0); gamma=(2.0*j1((MagickPI*alpha))/(MagickPI*alpha)); FxReturn(gamma); } #endif break; } case 'L': case 'l': { if (LocaleNCompare(expression,"ln",2) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2, depth+1,beta,exception); FxReturn(log(alpha)); } if (LocaleNCompare(expression,"logtwo",6) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+6, depth+1,beta,exception); FxReturn(log10(alpha)/log10(2.0)); } if (LocaleNCompare(expression,"log",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); FxReturn(log10(alpha)); } if (LocaleCompare(expression,"lightness") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); break; } case 'M': case 'm': { if (LocaleCompare(expression,"MaxRGB") == 0) FxReturn((double) QuantumRange); if (LocaleNCompare(expression,"maxima",6) == 0) break; if (LocaleNCompare(expression,"max",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); FxReturn(alpha > *beta ? alpha : *beta); } if (LocaleNCompare(expression,"minima",6) == 0) break; if (LocaleNCompare(expression,"min",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); FxReturn(alpha < *beta ? alpha : *beta); } if (LocaleNCompare(expression,"mod",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); gamma=alpha-floor((alpha*PerceptibleReciprocal(*beta)))*(*beta); FxReturn(gamma); } if (LocaleCompare(expression,"m") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); break; } case 'N': case 'n': { if (LocaleNCompare(expression,"not",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); FxReturn((double) (alpha < MagickEpsilon)); } if (LocaleCompare(expression,"n") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); break; } case 'O': case 'o': { if (LocaleCompare(expression,"Opaque") == 0) FxReturn(1.0); if (LocaleCompare(expression,"o") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); break; } case 'P': case 'p': { if (LocaleCompare(expression,"phi") == 0) FxReturn(MagickPHI); if (LocaleCompare(expression,"pi") == 0) FxReturn(MagickPI); if (LocaleNCompare(expression,"pow",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); FxReturn(pow(alpha,*beta)); } if (LocaleCompare(expression,"p") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); break; } case 'Q': case 'q': { if (LocaleCompare(expression,"QuantumRange") == 0) FxReturn((double) QuantumRange); if (LocaleCompare(expression,"QuantumScale") == 0) FxReturn(QuantumScale); break; } case 'R': case 'r': { if (LocaleNCompare(expression,"rand",4) == 0) { double alpha; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_FxEvaluateSubexpression) #endif alpha=GetPseudoRandomValue(fx_info->random_info); FxReturn(alpha); } if (LocaleNCompare(expression,"round",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5, depth+1,beta,exception); FxReturn(floor(alpha+0.5)); } if (LocaleCompare(expression,"r") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); break; } case 'S': case 's': { if (LocaleCompare(expression,"saturation") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); if (LocaleNCompare(expression,"sign",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4, depth+1,beta,exception); FxReturn(alpha < 0.0 ? -1.0 : 1.0); } if (LocaleNCompare(expression,"sinc",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4, depth+1,beta,exception); if (alpha == 0) FxReturn(1.0); gamma=(sin((MagickPI*alpha))/(MagickPI*alpha)); FxReturn(gamma); } if (LocaleNCompare(expression,"sinh",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4, depth+1,beta,exception); FxReturn(sinh(alpha)); } if (LocaleNCompare(expression,"sin",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); FxReturn(sin(alpha)); } if (LocaleNCompare(expression,"sqrt",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4, depth+1,beta,exception); FxReturn(sqrt(alpha)); } if (LocaleNCompare(expression,"squish",6) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+6, depth+1,beta,exception); FxReturn((1.0/(1.0+exp(-alpha)))); } if (LocaleCompare(expression,"s") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); break; } case 'T': case 't': { if (LocaleNCompare(expression,"tanh",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4, depth+1,beta,exception); FxReturn(tanh(alpha)); } if (LocaleNCompare(expression,"tan",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); FxReturn(tan(alpha)); } if (LocaleCompare(expression,"Transparent") == 0) FxReturn(0.0); if (LocaleNCompare(expression,"trunc",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5, depth+1,beta,exception); if (alpha >= 0.0) FxReturn(floor(alpha)); FxReturn(ceil(alpha)); } if (LocaleCompare(expression,"t") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); break; } case 'U': case 'u': { if (LocaleCompare(expression,"u") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); break; } case 'V': case 'v': { if (LocaleCompare(expression,"v") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); break; } case 'W': case 'w': { if (LocaleNCompare(expression,"while",5) == 0) { do { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5, depth+1,beta,exception); } while (fabs(alpha) >= MagickEpsilon); FxReturn(*beta); } if (LocaleCompare(expression,"w") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); break; } case 'Y': case 'y': { if (LocaleCompare(expression,"y") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); break; } case 'Z': case 'z': { if (LocaleCompare(expression,"z") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); break; } default: break; } q=(char *) expression; alpha=InterpretSiPrefixValue(expression,&q); if (q == expression) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); FxReturn(alpha); } MagickExport MagickBooleanType FxEvaluateExpression(FxInfo *fx_info, double *alpha,ExceptionInfo *exception) { MagickBooleanType status; status=FxEvaluateChannelExpression(fx_info,GrayChannel,0,0,alpha,exception); return(status); } MagickExport MagickBooleanType FxPreprocessExpression(FxInfo *fx_info, double *alpha,ExceptionInfo *exception) { FILE *file; MagickBooleanType status; file=fx_info->file; fx_info->file=(FILE *) NULL; status=FxEvaluateChannelExpression(fx_info,GrayChannel,0,0,alpha,exception); fx_info->file=file; return(status); } MagickExport MagickBooleanType FxEvaluateChannelExpression(FxInfo *fx_info, const ChannelType channel,const ssize_t x,const ssize_t y,double *alpha, ExceptionInfo *exception) { double beta; beta=0.0; *alpha=FxEvaluateSubexpression(fx_info,channel,x,y,fx_info->expression,0, &beta,exception); return(exception->severity == OptionError ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F x I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FxImage() applies a mathematical expression to the specified image. % % The format of the FxImage method is: % % Image *FxImage(const Image *image,const char *expression, % ExceptionInfo *exception) % Image *FxImageChannel(const Image *image,const ChannelType channel, % const char *expression,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o expression: A mathematical expression. % % o exception: return any errors or warnings in this structure. % */ static FxInfo **DestroyFxThreadSet(FxInfo **fx_info) { register ssize_t i; assert(fx_info != (FxInfo **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (fx_info[i] != (FxInfo *) NULL) fx_info[i]=DestroyFxInfo(fx_info[i]); fx_info=(FxInfo **) RelinquishMagickMemory(fx_info); return(fx_info); } static FxInfo **AcquireFxThreadSet(const Image *image,const char *expression, ExceptionInfo *exception) { char *fx_expression; double alpha; FxInfo **fx_info; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); fx_info=(FxInfo **) AcquireQuantumMemory(number_threads,sizeof(*fx_info)); if (fx_info == (FxInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return((FxInfo **) NULL); } (void) memset(fx_info,0,number_threads*sizeof(*fx_info)); if (*expression != '@') fx_expression=ConstantString(expression); else fx_expression=FileToString(expression+1,~0UL,exception); for (i=0; i < (ssize_t) number_threads; i++) { MagickBooleanType status; fx_info[i]=AcquireFxInfo(image,fx_expression); if (fx_info[i] == (FxInfo *) NULL) break; status=FxPreprocessExpression(fx_info[i],&alpha,exception); if (status == MagickFalse) break; } fx_expression=DestroyString(fx_expression); if (i < (ssize_t) number_threads) fx_info=DestroyFxThreadSet(fx_info); return(fx_info); } MagickExport Image *FxImage(const Image *image,const char *expression, ExceptionInfo *exception) { Image *fx_image; fx_image=FxImageChannel(image,GrayChannel,expression,exception); return(fx_image); } MagickExport Image *FxImageChannel(const Image *image,const ChannelType channel, const char *expression,ExceptionInfo *exception) { #define FxImageTag "Fx/Image" CacheView *fx_view; FxInfo **magick_restrict fx_info; Image *fx_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (expression == (const char *) NULL) return(CloneImage(image,0,0,MagickTrue,exception)); fx_info=AcquireFxThreadSet(image,expression,exception); if (fx_info == (FxInfo **) NULL) return((Image *) NULL); fx_image=CloneImage(image,0,0,MagickTrue,exception); if (fx_image == (Image *) NULL) { fx_info=DestroyFxThreadSet(fx_info); return((Image *) NULL); } if (SetImageStorageClass(fx_image,DirectClass) == MagickFalse) { InheritException(exception,&fx_image->exception); fx_info=DestroyFxThreadSet(fx_info); fx_image=DestroyImage(fx_image); return((Image *) NULL); } /* Fx image. */ status=MagickTrue; progress=0; fx_view=AcquireAuthenticCacheView(fx_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,fx_image,fx_image->rows,1) #endif for (y=0; y < (ssize_t) fx_image->rows; y++) { const int id = GetOpenMPThreadId(); double alpha; register IndexPacket *magick_restrict fx_indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(fx_view,0,y,fx_image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } fx_indexes=GetCacheViewAuthenticIndexQueue(fx_view); alpha=0.0; for (x=0; x < (ssize_t) fx_image->columns; x++) { if ((channel & RedChannel) != 0) { (void) FxEvaluateChannelExpression(fx_info[id],RedChannel,x,y, &alpha,exception); SetPixelRed(q,ClampToQuantum((MagickRealType) QuantumRange*alpha)); } if ((channel & GreenChannel) != 0) { (void) FxEvaluateChannelExpression(fx_info[id],GreenChannel,x,y, &alpha,exception); SetPixelGreen(q,ClampToQuantum((MagickRealType) QuantumRange*alpha)); } if ((channel & BlueChannel) != 0) { (void) FxEvaluateChannelExpression(fx_info[id],BlueChannel,x,y, &alpha,exception); SetPixelBlue(q,ClampToQuantum((MagickRealType) QuantumRange*alpha)); } if ((channel & OpacityChannel) != 0) { (void) FxEvaluateChannelExpression(fx_info[id],OpacityChannel,x,y, &alpha,exception); if (image->matte == MagickFalse) SetPixelOpacity(q,ClampToQuantum((MagickRealType) QuantumRange* alpha)); else SetPixelOpacity(q,ClampToQuantum((MagickRealType) (QuantumRange- QuantumRange*alpha))); } if (((channel & IndexChannel) != 0) && (fx_image->colorspace == CMYKColorspace)) { (void) FxEvaluateChannelExpression(fx_info[id],IndexChannel,x,y, &alpha,exception); SetPixelIndex(fx_indexes+x,ClampToQuantum((MagickRealType) QuantumRange*alpha)); } q++; } if (SyncCacheViewAuthenticPixels(fx_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,FxImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } fx_view=DestroyCacheView(fx_view); fx_info=DestroyFxThreadSet(fx_info); if (status == MagickFalse) fx_image=DestroyImage(fx_image); return(fx_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I m p l o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ImplodeImage() creates a new image that is a copy of an existing % one with the image pixels "implode" by the specified percentage. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ImplodeImage method is: % % Image *ImplodeImage(const Image *image,const double amount, % ExceptionInfo *exception) % % A description of each parameter follows: % % o implode_image: Method ImplodeImage returns a pointer to the image % after it is implode. A null image is returned if there is a memory % shortage. % % o image: the image. % % o amount: Define the extent of the implosion. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ImplodeImage(const Image *image,const double amount, ExceptionInfo *exception) { #define ImplodeImageTag "Implode/Image" CacheView *image_view, *implode_view; double radius; Image *implode_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; PointInfo center, scale; ssize_t y; /* Initialize implode image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); implode_image=CloneImage(image,0,0,MagickTrue,exception); if (implode_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(implode_image,DirectClass) == MagickFalse) { InheritException(exception,&implode_image->exception); implode_image=DestroyImage(implode_image); return((Image *) NULL); } if (implode_image->background_color.opacity != OpaqueOpacity) implode_image->matte=MagickTrue; /* Compute scaling factor. */ scale.x=1.0; scale.y=1.0; center.x=0.5*image->columns; center.y=0.5*image->rows; radius=center.x; if (image->columns > image->rows) scale.y=(double) image->columns/(double) image->rows; else if (image->columns < image->rows) { scale.x=(double) image->rows/(double) image->columns; radius=center.y; } /* Implode image. */ status=MagickTrue; progress=0; GetMagickPixelPacket(implode_image,&zero); image_view=AcquireVirtualCacheView(image,exception); implode_view=AcquireAuthenticCacheView(implode_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,implode_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double distance; MagickPixelPacket pixel; PointInfo delta; register IndexPacket *magick_restrict implode_indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(implode_view,0,y,implode_image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } implode_indexes=GetCacheViewAuthenticIndexQueue(implode_view); delta.y=scale.y*(double) (y-center.y); pixel=zero; for (x=0; x < (ssize_t) image->columns; x++) { /* Determine if the pixel is within an ellipse. */ delta.x=scale.x*(double) (x-center.x); distance=delta.x*delta.x+delta.y*delta.y; if (distance < (radius*radius)) { double factor; /* Implode the pixel. */ factor=1.0; if (distance > 0.0) factor=pow(sin((double) (MagickPI*sqrt((double) distance)/ radius/2)),-amount); status=InterpolateMagickPixelPacket(image,image_view, UndefinedInterpolatePixel,(double) (factor*delta.x/scale.x+ center.x),(double) (factor*delta.y/scale.y+center.y),&pixel, exception); if (status == MagickFalse) break; SetPixelPacket(implode_image,&pixel,q,implode_indexes+x); } q++; } if (SyncCacheViewAuthenticPixels(implode_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ImplodeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } implode_view=DestroyCacheView(implode_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) implode_image=DestroyImage(implode_image); return(implode_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o r p h I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % The MorphImages() method requires a minimum of two images. The first % image is transformed into the second by a number of intervening images % as specified by frames. % % The format of the MorphImage method is: % % Image *MorphImages(const Image *image,const size_t number_frames, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o number_frames: Define the number of in-between image to generate. % The more in-between frames, the smoother the morph. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MorphImages(const Image *image, const size_t number_frames,ExceptionInfo *exception) { #define MorphImageTag "Morph/Image" double alpha, beta; Image *morph_image, *morph_images; MagickBooleanType status; MagickOffsetType scene; register const Image *next; register ssize_t i; ssize_t y; /* Clone first frame in sequence. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); morph_images=CloneImage(image,0,0,MagickTrue,exception); if (morph_images == (Image *) NULL) return((Image *) NULL); if (GetNextImageInList(image) == (Image *) NULL) { /* Morph single image. */ for (i=1; i < (ssize_t) number_frames; i++) { morph_image=CloneImage(image,0,0,MagickTrue,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } AppendImageToList(&morph_images,morph_image); if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,MorphImageTag,(MagickOffsetType) i, number_frames); if (proceed == MagickFalse) status=MagickFalse; } } return(GetFirstImageInList(morph_images)); } /* Morph image sequence. */ status=MagickTrue; scene=0; next=image; for ( ; GetNextImageInList(next) != (Image *) NULL; next=GetNextImageInList(next)) { for (i=0; i < (ssize_t) number_frames; i++) { CacheView *image_view, *morph_view; beta=(double) (i+1.0)/(double) (number_frames+1.0); alpha=1.0-beta; morph_image=ResizeImage(next,(size_t) (alpha*next->columns+beta* GetNextImageInList(next)->columns+0.5),(size_t) (alpha* next->rows+beta*GetNextImageInList(next)->rows+0.5), next->filter,next->blur,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } if (SetImageStorageClass(morph_image,DirectClass) == MagickFalse) { InheritException(exception,&morph_image->exception); morph_image=DestroyImage(morph_image); return((Image *) NULL); } AppendImageToList(&morph_images,morph_image); morph_images=GetLastImageInList(morph_images); morph_image=ResizeImage(GetNextImageInList(next),morph_images->columns, morph_images->rows,GetNextImageInList(next)->filter, GetNextImageInList(next)->blur,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } image_view=AcquireVirtualCacheView(morph_image,exception); morph_view=AcquireAuthenticCacheView(morph_images,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(morph_image,morph_image,morph_image->rows,1) #endif for (y=0; y < (ssize_t) morph_images->rows; y++) { MagickBooleanType sync; register const PixelPacket *magick_restrict p; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,morph_image->columns,1, exception); q=GetCacheViewAuthenticPixels(morph_view,0,y,morph_images->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) morph_images->columns; x++) { SetPixelRed(q,ClampToQuantum(alpha* GetPixelRed(q)+beta*GetPixelRed(p))); SetPixelGreen(q,ClampToQuantum(alpha* GetPixelGreen(q)+beta*GetPixelGreen(p))); SetPixelBlue(q,ClampToQuantum(alpha* GetPixelBlue(q)+beta*GetPixelBlue(p))); SetPixelOpacity(q,ClampToQuantum(alpha* GetPixelOpacity(q)+beta*GetPixelOpacity(p))); p++; q++; } sync=SyncCacheViewAuthenticPixels(morph_view,exception); if (sync == MagickFalse) status=MagickFalse; } morph_view=DestroyCacheView(morph_view); image_view=DestroyCacheView(image_view); morph_image=DestroyImage(morph_image); } if (i < (ssize_t) number_frames) break; /* Clone last frame in sequence. */ morph_image=CloneImage(GetNextImageInList(next),0,0,MagickTrue,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } AppendImageToList(&morph_images,morph_image); morph_images=GetLastImageInList(morph_images); if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,MorphImageTag,scene, GetImageListLength(image)); if (proceed == MagickFalse) status=MagickFalse; } scene++; } if (GetNextImageInList(next) != (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } return(GetFirstImageInList(morph_images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P l a s m a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PlasmaImage() initializes an image with plasma fractal values. The image % must be initialized with a base color and the random number generator % seeded before this method is called. % % The format of the PlasmaImage method is: % % MagickBooleanType PlasmaImage(Image *image,const SegmentInfo *segment, % size_t attenuate,size_t depth) % % A description of each parameter follows: % % o image: the image. % % o segment: Define the region to apply plasma fractals values. % % o attenuate: Define the plasma attenuation factor. % % o depth: Limit the plasma recursion depth. % */ static inline Quantum PlasmaPixel(RandomInfo *random_info, const MagickRealType pixel,const double noise) { Quantum plasma; plasma=ClampToQuantum(pixel+noise*GetPseudoRandomValue(random_info)- noise/2.0); if (plasma <= 0) return((Quantum) 0); if (plasma >= QuantumRange) return(QuantumRange); return(plasma); } MagickExport MagickBooleanType PlasmaImageProxy(Image *image, CacheView *image_view,CacheView *u_view,CacheView *v_view, RandomInfo *random_info,const SegmentInfo *segment,size_t attenuate, size_t depth) { ExceptionInfo *exception; double plasma; PixelPacket u, v; ssize_t x, x_mid, y, y_mid; if ((fabs(segment->x2-segment->x1) <= MagickEpsilon) && (fabs(segment->y2-segment->y1) <= MagickEpsilon)) return(MagickTrue); if (depth != 0) { MagickBooleanType status; SegmentInfo local_info; /* Divide the area into quadrants and recurse. */ depth--; attenuate++; x_mid=(ssize_t) ceil((segment->x1+segment->x2)/2-0.5); y_mid=(ssize_t) ceil((segment->y1+segment->y2)/2-0.5); local_info=(*segment); local_info.x2=(double) x_mid; local_info.y2=(double) y_mid; (void) PlasmaImageProxy(image,image_view,u_view,v_view,random_info, &local_info,attenuate,depth); local_info=(*segment); local_info.y1=(double) y_mid; local_info.x2=(double) x_mid; (void) PlasmaImageProxy(image,image_view,u_view,v_view,random_info, &local_info,attenuate,depth); local_info=(*segment); local_info.x1=(double) x_mid; local_info.y2=(double) y_mid; (void) PlasmaImageProxy(image,image_view,u_view,v_view,random_info, &local_info,attenuate,depth); local_info=(*segment); local_info.x1=(double) x_mid; local_info.y1=(double) y_mid; status=PlasmaImageProxy(image,image_view,u_view,v_view,random_info, &local_info,attenuate,depth); return(status); } x_mid=(ssize_t) ceil((segment->x1+segment->x2)/2-0.5); y_mid=(ssize_t) ceil((segment->y1+segment->y2)/2-0.5); if ((fabs(segment->x1-x_mid) < MagickEpsilon) && (fabs(segment->x2-x_mid) < MagickEpsilon) && (fabs(segment->y1-y_mid) < MagickEpsilon) && (fabs(segment->y2-y_mid) < MagickEpsilon)) return(MagickFalse); /* Average pixels and apply plasma. */ exception=(&image->exception); plasma=(double) QuantumRange/(2.0*attenuate); if ((fabs(segment->x1-x_mid) > MagickEpsilon) || (fabs(segment->x2-x_mid) > MagickEpsilon)) { register PixelPacket *magick_restrict q; /* Left pixel. */ x=(ssize_t) ceil(segment->x1-0.5); (void) GetOneCacheViewVirtualPixel(u_view,x,(ssize_t) ceil(segment->y1-0.5),&u,exception); (void) GetOneCacheViewVirtualPixel(v_view,x,(ssize_t) ceil(segment->y2-0.5),&v,exception); q=QueueCacheViewAuthenticPixels(image_view,x,y_mid,1,1,exception); if (q == (PixelPacket *) NULL) return(MagickTrue); SetPixelRed(q,PlasmaPixel(random_info,(MagickRealType) (u.red+v.red)/2.0, plasma)); SetPixelGreen(q,PlasmaPixel(random_info,(MagickRealType) (u.green+ v.green)/2.0,plasma)); SetPixelBlue(q,PlasmaPixel(random_info,(MagickRealType) (u.blue+v.blue)/ 2.0,plasma)); (void) SyncCacheViewAuthenticPixels(image_view,exception); if (fabs(segment->x1-segment->x2) > MagickEpsilon) { /* Right pixel. */ x=(ssize_t) ceil(segment->x2-0.5); (void) GetOneCacheViewVirtualPixel(u_view,x,(ssize_t) ceil(segment->y1-0.5),&u,exception); (void) GetOneCacheViewVirtualPixel(v_view,x,(ssize_t) ceil(segment->y2-0.5),&v,exception); q=QueueCacheViewAuthenticPixels(image_view,x,y_mid,1,1,exception); if (q == (PixelPacket *) NULL) return(MagickTrue); SetPixelRed(q,PlasmaPixel(random_info,(MagickRealType) (u.red+v.red)/ 2.0,plasma)); SetPixelGreen(q,PlasmaPixel(random_info,(MagickRealType) (u.green+ v.green)/2.0,plasma)); SetPixelBlue(q,PlasmaPixel(random_info,(MagickRealType) (u.blue+ v.blue)/2.0,plasma)); (void) SyncCacheViewAuthenticPixels(image_view,exception); } } if ((fabs(segment->y1-y_mid) > MagickEpsilon) || (fabs(segment->y2-y_mid) > MagickEpsilon)) { if ((fabs(segment->x1-x_mid) > MagickEpsilon) || (fabs(segment->y2-y_mid) > MagickEpsilon)) { register PixelPacket *magick_restrict q; /* Bottom pixel. */ y=(ssize_t) ceil(segment->y2-0.5); (void) GetOneCacheViewVirtualPixel(u_view,(ssize_t) ceil(segment->x1-0.5),y,&u,exception); (void) GetOneCacheViewVirtualPixel(v_view,(ssize_t) ceil(segment->x2-0.5),y,&v,exception); q=QueueCacheViewAuthenticPixels(image_view,x_mid,y,1,1,exception); if (q == (PixelPacket *) NULL) return(MagickTrue); SetPixelRed(q,PlasmaPixel(random_info,(MagickRealType) (u.red+v.red)/ 2.0,plasma)); SetPixelGreen(q,PlasmaPixel(random_info,(MagickRealType) (u.green+ v.green)/2.0,plasma)); SetPixelBlue(q,PlasmaPixel(random_info,(MagickRealType) (u.blue+ v.blue)/2.0,plasma)); (void) SyncCacheViewAuthenticPixels(image_view,exception); } if (fabs(segment->y1-segment->y2) > MagickEpsilon) { register PixelPacket *magick_restrict q; /* Top pixel. */ y=(ssize_t) ceil(segment->y1-0.5); (void) GetOneCacheViewVirtualPixel(u_view,(ssize_t) ceil(segment->x1-0.5),y,&u,exception); (void) GetOneCacheViewVirtualPixel(v_view,(ssize_t) ceil(segment->x2-0.5),y,&v,exception); q=QueueCacheViewAuthenticPixels(image_view,x_mid,y,1,1,exception); if (q == (PixelPacket *) NULL) return(MagickTrue); SetPixelRed(q,PlasmaPixel(random_info,(MagickRealType) (u.red+ v.red)/2.0,plasma)); SetPixelGreen(q,PlasmaPixel(random_info,(MagickRealType) (u.green+ v.green)/2.0,plasma)); SetPixelBlue(q,PlasmaPixel(random_info,(MagickRealType) (u.blue+ v.blue)/2.0,plasma)); (void) SyncCacheViewAuthenticPixels(image_view,exception); } } if ((fabs(segment->x1-segment->x2) > MagickEpsilon) || (fabs(segment->y1-segment->y2) > MagickEpsilon)) { register PixelPacket *magick_restrict q; /* Middle pixel. */ x=(ssize_t) ceil(segment->x1-0.5); y=(ssize_t) ceil(segment->y1-0.5); (void) GetOneCacheViewVirtualPixel(u_view,x,y,&u,exception); x=(ssize_t) ceil(segment->x2-0.5); y=(ssize_t) ceil(segment->y2-0.5); (void) GetOneCacheViewVirtualPixel(v_view,x,y,&v,exception); q=QueueCacheViewAuthenticPixels(image_view,x_mid,y_mid,1,1,exception); if (q == (PixelPacket *) NULL) return(MagickTrue); SetPixelRed(q,PlasmaPixel(random_info,(MagickRealType) (u.red+v.red)/2.0, plasma)); SetPixelGreen(q,PlasmaPixel(random_info,(MagickRealType) (u.green+ v.green)/2.0,plasma)); SetPixelBlue(q,PlasmaPixel(random_info,(MagickRealType) (u.blue+v.blue)/ 2.0,plasma)); (void) SyncCacheViewAuthenticPixels(image_view,exception); } if ((fabs(segment->x2-segment->x1) < 3.0) && (fabs(segment->y2-segment->y1) < 3.0)) return(MagickTrue); return(MagickFalse); } MagickExport MagickBooleanType PlasmaImage(Image *image, const SegmentInfo *segment,size_t attenuate,size_t depth) { CacheView *image_view, *u_view, *v_view; MagickBooleanType status; RandomInfo *random_info; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); image_view=AcquireAuthenticCacheView(image,&image->exception); u_view=AcquireVirtualCacheView(image,&image->exception); v_view=AcquireVirtualCacheView(image,&image->exception); random_info=AcquireRandomInfo(); status=PlasmaImageProxy(image,image_view,u_view,v_view,random_info,segment, attenuate,depth); random_info=DestroyRandomInfo(random_info); v_view=DestroyCacheView(v_view); u_view=DestroyCacheView(u_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o l a r o i d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PolaroidImage() simulates a Polaroid picture. % % The format of the AnnotateImage method is: % % Image *PolaroidImage(const Image *image,const DrawInfo *draw_info, % const double angle,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o angle: Apply the effect along this angle. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PolaroidImage(const Image *image,const DrawInfo *draw_info, const double angle,ExceptionInfo *exception) { const char *value; Image *bend_image, *caption_image, *flop_image, *picture_image, *polaroid_image, *rotate_image, *trim_image; size_t height; ssize_t quantum; /* Simulate a Polaroid picture. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); quantum=(ssize_t) MagickMax(MagickMax((double) image->columns,(double) image->rows)/25.0,10.0); height=image->rows+2*quantum; caption_image=(Image *) NULL; value=GetImageProperty(image,"Caption"); if (value != (const char *) NULL) { char *caption; /* Generate caption image. */ caption_image=CloneImage(image,image->columns,1,MagickTrue,exception); if (caption_image == (Image *) NULL) return((Image *) NULL); caption=InterpretImageProperties((ImageInfo *) NULL,(Image *) image, value); if (caption != (char *) NULL) { char geometry[MaxTextExtent]; DrawInfo *annotate_info; MagickBooleanType status; ssize_t count; TypeMetric metrics; annotate_info=CloneDrawInfo((const ImageInfo *) NULL,draw_info); (void) CloneString(&annotate_info->text,caption); count=FormatMagickCaption(caption_image,annotate_info,MagickTrue, &metrics,&caption); status=SetImageExtent(caption_image,image->columns,(size_t) ((count+1)*(metrics.ascent-metrics.descent)+0.5)); if (status == MagickFalse) caption_image=DestroyImage(caption_image); else { caption_image->background_color=image->border_color; (void) SetImageBackgroundColor(caption_image); (void) CloneString(&annotate_info->text,caption); (void) FormatLocaleString(geometry,MaxTextExtent,"+0+%.20g", metrics.ascent); if (annotate_info->gravity == UndefinedGravity) (void) CloneString(&annotate_info->geometry,AcquireString( geometry)); (void) AnnotateImage(caption_image,annotate_info); height+=caption_image->rows; } annotate_info=DestroyDrawInfo(annotate_info); caption=DestroyString(caption); } } picture_image=CloneImage(image,image->columns+2*quantum,height,MagickTrue, exception); if (picture_image == (Image *) NULL) { if (caption_image != (Image *) NULL) caption_image=DestroyImage(caption_image); return((Image *) NULL); } picture_image->background_color=image->border_color; (void) SetImageBackgroundColor(picture_image); (void) CompositeImage(picture_image,OverCompositeOp,image,quantum,quantum); if (caption_image != (Image *) NULL) { (void) CompositeImage(picture_image,OverCompositeOp,caption_image, quantum,(ssize_t) (image->rows+3*quantum/2)); caption_image=DestroyImage(caption_image); } (void) QueryColorDatabase("none",&picture_image->background_color,exception); (void) SetImageAlphaChannel(picture_image,OpaqueAlphaChannel); rotate_image=RotateImage(picture_image,90.0,exception); picture_image=DestroyImage(picture_image); if (rotate_image == (Image *) NULL) return((Image *) NULL); picture_image=rotate_image; bend_image=WaveImage(picture_image,0.01*picture_image->rows,2.0* picture_image->columns,exception); picture_image=DestroyImage(picture_image); if (bend_image == (Image *) NULL) return((Image *) NULL); InheritException(&bend_image->exception,exception); picture_image=bend_image; rotate_image=RotateImage(picture_image,-90.0,exception); picture_image=DestroyImage(picture_image); if (rotate_image == (Image *) NULL) return((Image *) NULL); picture_image=rotate_image; picture_image->background_color=image->background_color; polaroid_image=ShadowImage(picture_image,80.0,2.0,quantum/3,quantum/3, exception); if (polaroid_image == (Image *) NULL) { picture_image=DestroyImage(picture_image); return(picture_image); } flop_image=FlopImage(polaroid_image,exception); polaroid_image=DestroyImage(polaroid_image); if (flop_image == (Image *) NULL) { picture_image=DestroyImage(picture_image); return(picture_image); } polaroid_image=flop_image; (void) CompositeImage(polaroid_image,OverCompositeOp,picture_image, (ssize_t) (-0.01*picture_image->columns/2.0),0L); picture_image=DestroyImage(picture_image); (void) QueryColorDatabase("none",&polaroid_image->background_color,exception); rotate_image=RotateImage(polaroid_image,angle,exception); polaroid_image=DestroyImage(polaroid_image); if (rotate_image == (Image *) NULL) return((Image *) NULL); polaroid_image=rotate_image; trim_image=TrimImage(polaroid_image,exception); polaroid_image=DestroyImage(polaroid_image); if (trim_image == (Image *) NULL) return((Image *) NULL); polaroid_image=trim_image; return(polaroid_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e p i a T o n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSepiaToneImage() applies a special effect to the image, similar to the % effect achieved in a photo darkroom by sepia toning. Threshold ranges from % 0 to QuantumRange and is a measure of the extent of the sepia toning. A % threshold of 80% is a good starting point for a reasonable tone. % % The format of the SepiaToneImage method is: % % Image *SepiaToneImage(const Image *image,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: the tone threshold. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SepiaToneImage(const Image *image,const double threshold, ExceptionInfo *exception) { #define SepiaToneImageTag "SepiaTone/Image" CacheView *image_view, *sepia_view; Image *sepia_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Initialize sepia-toned image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); sepia_image=CloneImage(image,0,0,MagickTrue,exception); if (sepia_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(sepia_image,DirectClass) == MagickFalse) { InheritException(exception,&sepia_image->exception); sepia_image=DestroyImage(sepia_image); return((Image *) NULL); } /* Tone each row of the image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); sepia_view=AcquireAuthenticCacheView(sepia_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,sepia_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(sepia_view,0,y,sepia_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double intensity, tone; intensity=GetPixelIntensity(image,p); tone=intensity > threshold ? (double) QuantumRange : intensity+ (double) QuantumRange-threshold; SetPixelRed(q,ClampToQuantum(tone)); tone=intensity > (7.0*threshold/6.0) ? (double) QuantumRange : intensity+(double) QuantumRange-7.0*threshold/6.0; SetPixelGreen(q,ClampToQuantum(tone)); tone=intensity < (threshold/6.0) ? 0 : intensity-threshold/6.0; SetPixelBlue(q,ClampToQuantum(tone)); tone=threshold/7.0; if ((double) GetPixelGreen(q) < tone) SetPixelGreen(q,ClampToQuantum(tone)); if ((double) GetPixelBlue(q) < tone) SetPixelBlue(q,ClampToQuantum(tone)); SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncCacheViewAuthenticPixels(sepia_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,SepiaToneImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } sepia_view=DestroyCacheView(sepia_view); image_view=DestroyCacheView(image_view); (void) NormalizeImage(sepia_image); (void) ContrastImage(sepia_image,MagickTrue); if (status == MagickFalse) sepia_image=DestroyImage(sepia_image); return(sepia_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h a d o w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShadowImage() simulates a shadow from the specified image and returns it. % % The format of the ShadowImage method is: % % Image *ShadowImage(const Image *image,const double opacity, % const double sigma,const ssize_t x_offset,const ssize_t y_offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o opacity: percentage transparency. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o x_offset: the shadow x-offset. % % o y_offset: the shadow y-offset. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShadowImage(const Image *image,const double opacity, const double sigma,const ssize_t x_offset,const ssize_t y_offset, ExceptionInfo *exception) { #define ShadowImageTag "Shadow/Image" CacheView *image_view; Image *border_image, *clone_image, *shadow_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo border_info; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); clone_image=CloneImage(image,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) return((Image *) NULL); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(clone_image,sRGBColorspace); (void) SetImageVirtualPixelMethod(clone_image,EdgeVirtualPixelMethod); clone_image->compose=OverCompositeOp; border_info.width=(size_t) floor(2.0*sigma+0.5); border_info.height=(size_t) floor(2.0*sigma+0.5); border_info.x=0; border_info.y=0; (void) QueryColorDatabase("none",&clone_image->border_color,exception); border_image=BorderImage(clone_image,&border_info,exception); clone_image=DestroyImage(clone_image); if (border_image == (Image *) NULL) return((Image *) NULL); if (border_image->matte == MagickFalse) (void) SetImageAlphaChannel(border_image,OpaqueAlphaChannel); /* Shadow image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(border_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(border_image,border_image,border_image->rows,1) #endif for (y=0; y < (ssize_t) border_image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,border_image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) border_image->columns; x++) { SetPixelRed(q,border_image->background_color.red); SetPixelGreen(q,border_image->background_color.green); SetPixelBlue(q,border_image->background_color.blue); if (border_image->matte == MagickFalse) SetPixelOpacity(q,border_image->background_color.opacity); else SetPixelOpacity(q,ClampToQuantum((double) (QuantumRange- GetPixelAlpha(q)*opacity/100.0))); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ShadowImageTag,progress, border_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); shadow_image=BlurImageChannel(border_image,AlphaChannel,0.0,sigma,exception); border_image=DestroyImage(border_image); if (shadow_image == (Image *) NULL) return((Image *) NULL); if (shadow_image->page.width == 0) shadow_image->page.width=shadow_image->columns; if (shadow_image->page.height == 0) shadow_image->page.height=shadow_image->rows; shadow_image->page.width+=x_offset-(ssize_t) border_info.width; shadow_image->page.height+=y_offset-(ssize_t) border_info.height; shadow_image->page.x+=x_offset-(ssize_t) border_info.width; shadow_image->page.y+=y_offset-(ssize_t) border_info.height; return(shadow_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S k e t c h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SketchImage() simulates a pencil sketch. We convolve the image with a % Gaussian operator of the given radius and standard deviation (sigma). For % reasonable results, radius should be larger than sigma. Use a radius of 0 % and SketchImage() selects a suitable radius for you. Angle gives the angle % of the sketch. % % The format of the SketchImage method is: % % Image *SketchImage(const Image *image,const double radius, % const double sigma,const double angle,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian, in pixels, not counting % the center pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o angle: Apply the effect along this angle. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SketchImage(const Image *image,const double radius, const double sigma,const double angle,ExceptionInfo *exception) { CacheView *random_view; Image *blend_image, *blur_image, *dodge_image, *random_image, *sketch_image; MagickBooleanType status; MagickPixelPacket zero; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif /* Sketch image. */ random_image=CloneImage(image,image->columns << 1,image->rows << 1, MagickTrue,exception); if (random_image == (Image *) NULL) return((Image *) NULL); random_view=AcquireAuthenticCacheView(random_image,exception); status=MagickTrue; GetMagickPixelPacket(random_image,&zero); random_info=AcquireRandomInfoThreadSet(); random_view=AcquireAuthenticCacheView(random_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(random_image,random_image,random_image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) random_image->rows; y++) { const int id = GetOpenMPThreadId(); MagickPixelPacket pixel; register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(random_view,0,y,random_image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(random_view); pixel=zero; for (x=0; x < (ssize_t) random_image->columns; x++) { pixel.red=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); pixel.green=pixel.red; pixel.blue=pixel.red; if (image->colorspace == CMYKColorspace) pixel.index=pixel.red; SetPixelPacket(random_image,&pixel,q,indexes+x); q++; } if (SyncCacheViewAuthenticPixels(random_view,exception) == MagickFalse) status=MagickFalse; } random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) { random_view=DestroyCacheView(random_view); random_image=DestroyImage(random_image); return(random_image); } random_view=DestroyCacheView(random_view); blur_image=MotionBlurImage(random_image,radius,sigma,angle,exception); random_image=DestroyImage(random_image); if (blur_image == (Image *) NULL) return((Image *) NULL); dodge_image=EdgeImage(blur_image,radius,exception); blur_image=DestroyImage(blur_image); if (dodge_image == (Image *) NULL) return((Image *) NULL); (void) NormalizeImage(dodge_image); (void) NegateImage(dodge_image,MagickFalse); (void) TransformImage(&dodge_image,(char *) NULL,"50%"); sketch_image=CloneImage(image,0,0,MagickTrue,exception); if (sketch_image == (Image *) NULL) { dodge_image=DestroyImage(dodge_image); return((Image *) NULL); } (void) CompositeImage(sketch_image,ColorDodgeCompositeOp,dodge_image,0,0); dodge_image=DestroyImage(dodge_image); blend_image=CloneImage(image,0,0,MagickTrue,exception); if (blend_image == (Image *) NULL) { sketch_image=DestroyImage(sketch_image); return((Image *) NULL); } (void) SetImageArtifact(blend_image,"compose:args","20x80"); (void) CompositeImage(sketch_image,BlendCompositeOp,blend_image,0,0); blend_image=DestroyImage(blend_image); return(sketch_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S o l a r i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SolarizeImage() applies a special effect to the image, similar to the effect % achieved in a photo darkroom by selectively exposing areas of photo % sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a % measure of the extent of the solarization. % % The format of the SolarizeImage method is: % % MagickBooleanType SolarizeImage(Image *image,const double threshold) % MagickBooleanType SolarizeImageChannel(Image *image, % const ChannelType channel,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o threshold: Define the extent of the solarization. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SolarizeImage(Image *image, const double threshold) { MagickBooleanType status; status=SolarizeImageChannel(image,DefaultChannels,threshold, &image->exception); return(status); } MagickExport MagickBooleanType SolarizeImageChannel(Image *image, const ChannelType channel,const double threshold,ExceptionInfo *exception) { #define SolarizeImageTag "Solarize/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace); if (image->storage_class == PseudoClass) { register ssize_t i; /* Solarize colormap. */ for (i=0; i < (ssize_t) image->colors; i++) { if ((channel & RedChannel) != 0) if ((double) image->colormap[i].red > threshold) image->colormap[i].red=QuantumRange-image->colormap[i].red; if ((channel & GreenChannel) != 0) if ((double) image->colormap[i].green > threshold) image->colormap[i].green=QuantumRange-image->colormap[i].green; if ((channel & BlueChannel) != 0) if ((double) image->colormap[i].blue > threshold) image->colormap[i].blue=QuantumRange-image->colormap[i].blue; } } /* Solarize image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) if ((double) GetPixelRed(q) > threshold) SetPixelRed(q,QuantumRange-GetPixelRed(q)); if ((channel & GreenChannel) != 0) if ((double) GetPixelGreen(q) > threshold) SetPixelGreen(q,QuantumRange-GetPixelGreen(q)); if ((channel & BlueChannel) != 0) if ((double) GetPixelBlue(q) > threshold) SetPixelBlue(q,QuantumRange-GetPixelBlue(q)); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,SolarizeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t e g a n o I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SteganoImage() hides a digital watermark within the image. Recover % the hidden watermark later to prove that the authenticity of an image. % Offset defines the start position within the image to hide the watermark. % % The format of the SteganoImage method is: % % Image *SteganoImage(const Image *image,Image *watermark, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o watermark: the watermark image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SteganoImage(const Image *image,const Image *watermark, ExceptionInfo *exception) { #define GetBit(alpha,i) ((((size_t) (alpha) >> (size_t) (i)) & 0x01) != 0) #define SetBit(alpha,i,set) (alpha)=(Quantum) ((set) != 0 ? (size_t) (alpha) \ | (one << (size_t) (i)) : (size_t) (alpha) & ~(one << (size_t) (i))) #define SteganoImageTag "Stegano/Image" CacheView *stegano_view, *watermark_view; Image *stegano_image; int c; MagickBooleanType status; PixelPacket pixel; register PixelPacket *q; register ssize_t x; size_t depth, one; ssize_t i, j, k, y; /* Initialize steganographic image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(watermark != (const Image *) NULL); assert(watermark->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); one=1UL; stegano_image=CloneImage(image,0,0,MagickTrue,exception); if (stegano_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(stegano_image,DirectClass) == MagickFalse) { InheritException(exception,&stegano_image->exception); stegano_image=DestroyImage(stegano_image); return((Image *) NULL); } stegano_image->depth=MAGICKCORE_QUANTUM_DEPTH; /* Hide watermark in low-order bits of image. */ c=0; i=0; j=0; depth=stegano_image->depth; k=image->offset; status=MagickTrue; watermark_view=AcquireVirtualCacheView(watermark,exception); stegano_view=AcquireAuthenticCacheView(stegano_image,exception); for (i=(ssize_t) depth-1; (i >= 0) && (j < (ssize_t) depth); i--) { for (y=0; (y < (ssize_t) watermark->rows) && (j < (ssize_t) depth); y++) { for (x=0; (x < (ssize_t) watermark->columns) && (j < (ssize_t) depth); x++) { (void) GetOneCacheViewVirtualPixel(watermark_view,x,y,&pixel,exception); if ((k/(ssize_t) stegano_image->columns) >= (ssize_t) stegano_image->rows) break; q=GetCacheViewAuthenticPixels(stegano_view,k % (ssize_t) stegano_image->columns,k/(ssize_t) stegano_image->columns,1,1, exception); if (q == (PixelPacket *) NULL) break; switch (c) { case 0: { SetBit(GetPixelRed(q),j,GetBit(ClampToQuantum(GetPixelIntensity( image,&pixel)),i)); break; } case 1: { SetBit(GetPixelGreen(q),j,GetBit(ClampToQuantum(GetPixelIntensity( image,&pixel)),i)); break; } case 2: { SetBit(GetPixelBlue(q),j,GetBit(ClampToQuantum(GetPixelIntensity( image,&pixel)),i)); break; } } if (SyncCacheViewAuthenticPixels(stegano_view,exception) == MagickFalse) break; c++; if (c == 3) c=0; k++; if (k == (ssize_t) (stegano_image->columns*stegano_image->columns)) k=0; if (k == image->offset) j++; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,SteganoImageTag,(MagickOffsetType) (depth-i),depth); if (proceed == MagickFalse) status=MagickFalse; } } stegano_view=DestroyCacheView(stegano_view); watermark_view=DestroyCacheView(watermark_view); if (stegano_image->storage_class == PseudoClass) (void) SyncImage(stegano_image); if (status == MagickFalse) stegano_image=DestroyImage(stegano_image); return(stegano_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t e r e o A n a g l y p h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StereoAnaglyphImage() combines two images and produces a single image that % is the composite of a left and right image of a stereo pair. Special % red-green stereo glasses are required to view this effect. % % The format of the StereoAnaglyphImage method is: % % Image *StereoImage(const Image *left_image,const Image *right_image, % ExceptionInfo *exception) % Image *StereoAnaglyphImage(const Image *left_image, % const Image *right_image,const ssize_t x_offset,const ssize_t y_offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o left_image: the left image. % % o right_image: the right image. % % o exception: return any errors or warnings in this structure. % % o x_offset: amount, in pixels, by which the left image is offset to the % right of the right image. % % o y_offset: amount, in pixels, by which the left image is offset to the % bottom of the right image. % % */ MagickExport Image *StereoImage(const Image *left_image, const Image *right_image,ExceptionInfo *exception) { return(StereoAnaglyphImage(left_image,right_image,0,0,exception)); } MagickExport Image *StereoAnaglyphImage(const Image *left_image, const Image *right_image,const ssize_t x_offset,const ssize_t y_offset, ExceptionInfo *exception) { #define StereoImageTag "Stereo/Image" const Image *image; Image *stereo_image; MagickBooleanType status; ssize_t y; assert(left_image != (const Image *) NULL); assert(left_image->signature == MagickCoreSignature); if (left_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", left_image->filename); assert(right_image != (const Image *) NULL); assert(right_image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=left_image; if ((left_image->columns != right_image->columns) || (left_image->rows != right_image->rows)) ThrowImageException(ImageError,"LeftAndRightImageSizesDiffer"); /* Initialize stereo image attributes. */ stereo_image=CloneImage(left_image,left_image->columns,left_image->rows, MagickTrue,exception); if (stereo_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(stereo_image,DirectClass) == MagickFalse) { InheritException(exception,&stereo_image->exception); stereo_image=DestroyImage(stereo_image); return((Image *) NULL); } (void) SetImageColorspace(stereo_image,sRGBColorspace); /* Copy left image to red channel and right image to blue channel. */ status=MagickTrue; for (y=0; y < (ssize_t) stereo_image->rows; y++) { register const PixelPacket *magick_restrict p, *magick_restrict q; register ssize_t x; register PixelPacket *magick_restrict r; p=GetVirtualPixels(left_image,-x_offset,y-y_offset,image->columns,1, exception); q=GetVirtualPixels(right_image,0,y,right_image->columns,1,exception); r=QueueAuthenticPixels(stereo_image,0,y,stereo_image->columns,1,exception); if ((p == (PixelPacket *) NULL) || (q == (PixelPacket *) NULL) || (r == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) stereo_image->columns; x++) { SetPixelRed(r,GetPixelRed(p)); SetPixelGreen(r,GetPixelGreen(q)); SetPixelBlue(r,GetPixelBlue(q)); SetPixelOpacity(r,(GetPixelOpacity(p)+q->opacity)/2); p++; q++; r++; } if (SyncAuthenticPixels(stereo_image,exception) == MagickFalse) break; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,StereoImageTag,(MagickOffsetType) y, stereo_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } if (status == MagickFalse) stereo_image=DestroyImage(stereo_image); return(stereo_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S w i r l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SwirlImage() swirls the pixels about the center of the image, where % degrees indicates the sweep of the arc through which each pixel is moved. % You get a more dramatic effect as the degrees move from 1 to 360. % % The format of the SwirlImage method is: % % Image *SwirlImage(const Image *image,double degrees, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o degrees: Define the tightness of the swirling effect. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SwirlImage(const Image *image,double degrees, ExceptionInfo *exception) { #define SwirlImageTag "Swirl/Image" CacheView *image_view, *swirl_view; double radius; Image *swirl_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; PointInfo center, scale; ssize_t y; /* Initialize swirl image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); swirl_image=CloneImage(image,0,0,MagickTrue,exception); if (swirl_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(swirl_image,DirectClass) == MagickFalse) { InheritException(exception,&swirl_image->exception); swirl_image=DestroyImage(swirl_image); return((Image *) NULL); } if (swirl_image->background_color.opacity != OpaqueOpacity) swirl_image->matte=MagickTrue; /* Compute scaling factor. */ center.x=(double) image->columns/2.0; center.y=(double) image->rows/2.0; radius=MagickMax(center.x,center.y); scale.x=1.0; scale.y=1.0; if (image->columns > image->rows) scale.y=(double) image->columns/(double) image->rows; else if (image->columns < image->rows) scale.x=(double) image->rows/(double) image->columns; degrees=(double) DegreesToRadians(degrees); /* Swirl image. */ status=MagickTrue; progress=0; GetMagickPixelPacket(swirl_image,&zero); image_view=AcquireVirtualCacheView(image,exception); swirl_view=AcquireAuthenticCacheView(swirl_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,swirl_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double distance; MagickPixelPacket pixel; PointInfo delta; register IndexPacket *magick_restrict swirl_indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(swirl_view,0,y,swirl_image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } swirl_indexes=GetCacheViewAuthenticIndexQueue(swirl_view); delta.y=scale.y*(double) (y-center.y); pixel=zero; for (x=0; x < (ssize_t) image->columns; x++) { /* Determine if the pixel is within an ellipse. */ delta.x=scale.x*(double) (x-center.x); distance=delta.x*delta.x+delta.y*delta.y; if (distance < (radius*radius)) { double cosine, factor, sine; /* Swirl the pixel. */ factor=1.0-sqrt(distance)/radius; sine=sin((double) (degrees*factor*factor)); cosine=cos((double) (degrees*factor*factor)); status=InterpolateMagickPixelPacket(image,image_view, UndefinedInterpolatePixel,(double) ((cosine*delta.x-sine*delta.y)/ scale.x+center.x),(double) ((sine*delta.x+cosine*delta.y)/scale.y+ center.y),&pixel,exception); if (status == MagickFalse) break; SetPixelPacket(swirl_image,&pixel,q,swirl_indexes+x); } q++; } if (SyncCacheViewAuthenticPixels(swirl_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,SwirlImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } swirl_view=DestroyCacheView(swirl_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) swirl_image=DestroyImage(swirl_image); return(swirl_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TintImage() applies a color vector to each pixel in the image. The length % of the vector is 0 for black and white and at its maximum for the midtones. % The vector weighting function is f(x)=(1-(4.0*((x-0.5)*(x-0.5)))) % % The format of the TintImage method is: % % Image *TintImage(const Image *image,const char *opacity, % const PixelPacket tint,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o opacity: A color value used for tinting. % % o tint: A color value used for tinting. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *TintImage(const Image *image,const char *opacity, const PixelPacket tint,ExceptionInfo *exception) { #define TintImageTag "Tint/Image" CacheView *image_view, *tint_view; GeometryInfo geometry_info; Image *tint_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket color_vector, pixel; MagickStatusType flags; ssize_t y; /* Allocate tint image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); tint_image=CloneImage(image,0,0,MagickTrue,exception); if (tint_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(tint_image,DirectClass) == MagickFalse) { InheritException(exception,&tint_image->exception); tint_image=DestroyImage(tint_image); return((Image *) NULL); } if ((IsGrayColorspace(image->colorspace) != MagickFalse) && (IsPixelGray(&tint) == MagickFalse)) (void) SetImageColorspace(tint_image,sRGBColorspace); if (opacity == (const char *) NULL) return(tint_image); /* Determine RGB values of the tint color. */ flags=ParseGeometry(opacity,&geometry_info); pixel.red=geometry_info.rho; pixel.green=geometry_info.rho; pixel.blue=geometry_info.rho; pixel.opacity=(MagickRealType) OpaqueOpacity; if ((flags & SigmaValue) != 0) pixel.green=geometry_info.sigma; if ((flags & XiValue) != 0) pixel.blue=geometry_info.xi; if ((flags & PsiValue) != 0) pixel.opacity=geometry_info.psi; color_vector.red=(MagickRealType) (pixel.red*tint.red/100.0- PixelPacketIntensity(&tint)); color_vector.green=(MagickRealType) (pixel.green*tint.green/100.0- PixelPacketIntensity(&tint)); color_vector.blue=(MagickRealType) (pixel.blue*tint.blue/100.0- PixelPacketIntensity(&tint)); /* Tint image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); tint_view=AcquireAuthenticCacheView(tint_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,tint_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(tint_view,0,y,tint_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double weight; MagickPixelPacket pixel; weight=QuantumScale*GetPixelRed(p)-0.5; pixel.red=(MagickRealType) GetPixelRed(p)+color_vector.red*(1.0-(4.0* (weight*weight))); SetPixelRed(q,ClampToQuantum(pixel.red)); weight=QuantumScale*GetPixelGreen(p)-0.5; pixel.green=(MagickRealType) GetPixelGreen(p)+color_vector.green*(1.0- (4.0*(weight*weight))); SetPixelGreen(q,ClampToQuantum(pixel.green)); weight=QuantumScale*GetPixelBlue(p)-0.5; pixel.blue=(MagickRealType) GetPixelBlue(p)+color_vector.blue*(1.0-(4.0* (weight*weight))); SetPixelBlue(q,ClampToQuantum(pixel.blue)); SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncCacheViewAuthenticPixels(tint_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,TintImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } tint_view=DestroyCacheView(tint_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) tint_image=DestroyImage(tint_image); return(tint_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % V i g n e t t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % VignetteImage() softens the edges of the image in vignette style. % % The format of the VignetteImage method is: % % Image *VignetteImage(const Image *image,const double radius, % const double sigma,const ssize_t x,const ssize_t y, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the pixel neighborhood. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o x, y: Define the x and y ellipse offset. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *VignetteImage(const Image *image,const double radius, const double sigma,const ssize_t x,const ssize_t y,ExceptionInfo *exception) { char ellipse[MaxTextExtent]; DrawInfo *draw_info; Image *blur_image, *canvas_image, *oval_image, *vignette_image; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); canvas_image=CloneImage(image,0,0,MagickTrue,exception); if (canvas_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(canvas_image,DirectClass) == MagickFalse) { InheritException(exception,&canvas_image->exception); canvas_image=DestroyImage(canvas_image); return((Image *) NULL); } canvas_image->matte=MagickTrue; oval_image=CloneImage(canvas_image,canvas_image->columns,canvas_image->rows, MagickTrue,exception); if (oval_image == (Image *) NULL) { canvas_image=DestroyImage(canvas_image); return((Image *) NULL); } (void) QueryColorDatabase("#000000",&oval_image->background_color,exception); (void) SetImageBackgroundColor(oval_image); draw_info=CloneDrawInfo((const ImageInfo *) NULL,(const DrawInfo *) NULL); (void) QueryColorDatabase("#ffffff",&draw_info->fill,exception); (void) QueryColorDatabase("#ffffff",&draw_info->stroke,exception); (void) FormatLocaleString(ellipse,MaxTextExtent, "ellipse %g,%g,%g,%g,0.0,360.0",image->columns/2.0, image->rows/2.0,image->columns/2.0-x,image->rows/2.0-y); draw_info->primitive=AcquireString(ellipse); (void) DrawImage(oval_image,draw_info); draw_info=DestroyDrawInfo(draw_info); blur_image=BlurImage(oval_image,radius,sigma,exception); oval_image=DestroyImage(oval_image); if (blur_image == (Image *) NULL) { canvas_image=DestroyImage(canvas_image); return((Image *) NULL); } blur_image->matte=MagickFalse; (void) CompositeImage(canvas_image,CopyOpacityCompositeOp,blur_image,0,0); blur_image=DestroyImage(blur_image); vignette_image=MergeImageLayers(canvas_image,FlattenLayer,exception); canvas_image=DestroyImage(canvas_image); if (vignette_image != (Image *) NULL) (void) TransformImageColorspace(vignette_image,image->colorspace); return(vignette_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W a v e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WaveImage() creates a "ripple" effect in the image by shifting the pixels % vertically along a sine wave whose amplitude and wavelength is specified % by the given parameters. % % The format of the WaveImage method is: % % Image *WaveImage(const Image *image,const double amplitude, % const double wave_length,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o amplitude, wave_length: Define the amplitude and wave length of the % sine wave. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *WaveImage(const Image *image,const double amplitude, const double wave_length,ExceptionInfo *exception) { #define WaveImageTag "Wave/Image" CacheView *image_view, *wave_view; Image *wave_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; MagickRealType *sine_map; register ssize_t i; ssize_t y; /* Initialize wave image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); wave_image=CloneImage(image,image->columns,(size_t) (image->rows+2.0* fabs(amplitude)),MagickTrue,exception); if (wave_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(wave_image,DirectClass) == MagickFalse) { InheritException(exception,&wave_image->exception); wave_image=DestroyImage(wave_image); return((Image *) NULL); } if (wave_image->background_color.opacity != OpaqueOpacity) wave_image->matte=MagickTrue; /* Allocate sine map. */ sine_map=(MagickRealType *) AcquireQuantumMemory((size_t) wave_image->columns, sizeof(*sine_map)); if (sine_map == (MagickRealType *) NULL) { wave_image=DestroyImage(wave_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) wave_image->columns; i++) sine_map[i]=fabs(amplitude)+amplitude*sin((double) ((2.0*MagickPI*i)/ wave_length)); /* Wave image. */ status=MagickTrue; progress=0; GetMagickPixelPacket(wave_image,&zero); image_view=AcquireVirtualCacheView(image,exception); wave_view=AcquireAuthenticCacheView(wave_image,exception); (void) SetCacheViewVirtualPixelMethod(image_view, BackgroundVirtualPixelMethod); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,wave_image,wave_image->rows,1) #endif for (y=0; y < (ssize_t) wave_image->rows; y++) { MagickPixelPacket pixel; register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(wave_view,0,y,wave_image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(wave_view); pixel=zero; for (x=0; x < (ssize_t) wave_image->columns; x++) { status=InterpolateMagickPixelPacket(image,image_view, UndefinedInterpolatePixel,(double) x,(double) (y-sine_map[x]),&pixel, exception); if (status == MagickFalse) break; SetPixelPacket(wave_image,&pixel,q,indexes+x); q++; } if (SyncCacheViewAuthenticPixels(wave_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,WaveImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } wave_view=DestroyCacheView(wave_view); image_view=DestroyCacheView(image_view); sine_map=(MagickRealType *) RelinquishMagickMemory(sine_map); if (status == MagickFalse) wave_image=DestroyImage(wave_image); return(wave_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W a v e l e t D e n o i s e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WaveletDenoiseImage() removes noise from the image using a wavelet % transform. The wavelet transform is a fast hierarchical scheme for % processing an image using a set of consecutive lowpass and high_pass filters, % followed by a decimation. This results in a decomposition into different % scales which can be regarded as different “frequency bands”, determined by % the mother wavelet. Adapted from dcraw.c by David Coffin. % % The format of the WaveletDenoiseImage method is: % % Image *WaveletDenoiseImage(const Image *image,const double threshold, % const double softness,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: set the threshold for smoothing. % % o softness: attenuate the smoothing threshold. % % o exception: return any errors or warnings in this structure. % */ static inline void HatTransform(const float *magick_restrict pixels, const size_t stride,const size_t extent,const size_t scale,float *kernel) { const float *magick_restrict p, *magick_restrict q, *magick_restrict r; register ssize_t i; p=pixels; q=pixels+scale*stride, r=pixels+scale*stride; for (i=0; i < (ssize_t) scale; i++) { kernel[i]=0.25f*(*p+(*p)+(*q)+(*r)); p+=stride; q-=stride; r+=stride; } for ( ; i < (ssize_t) (extent-scale); i++) { kernel[i]=0.25f*(2.0f*(*p)+*(p-scale*stride)+*(p+scale*stride)); p+=stride; } q=p-scale*stride; r=pixels+stride*(extent-2); for ( ; i < (ssize_t) extent; i++) { kernel[i]=0.25f*(*p+(*p)+(*q)+(*r)); p+=stride; q+=stride; r-=stride; } } MagickExport Image *WaveletDenoiseImage(const Image *image, const double threshold,const double softness,ExceptionInfo *exception) { CacheView *image_view, *noise_view; float *kernel, *pixels; Image *noise_image; MagickBooleanType status; MagickSizeType number_pixels; MemoryInfo *pixels_info; size_t max_channels; ssize_t channel; static const double noise_levels[]= { 0.8002, 0.2735, 0.1202, 0.0585, 0.0291, 0.0152, 0.0080, 0.0044 }; /* Initialize noise image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); noise_image=(Image *) NULL; #if defined(MAGICKCORE_OPENCL_SUPPORT) noise_image=AccelerateWaveletDenoiseImage(image,threshold,exception); if (noise_image != (Image *) NULL) return(noise_image); #endif noise_image=CloneImage(image,0,0,MagickTrue,exception); if (noise_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(noise_image,DirectClass) == MagickFalse) { noise_image=DestroyImage(noise_image); return((Image *) NULL); } if (AcquireMagickResource(WidthResource,3*image->columns) == MagickFalse) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); pixels_info=AcquireVirtualMemory(3*image->columns,image->rows* sizeof(*pixels)); kernel=(float *) AcquireQuantumMemory(MagickMax(image->rows,image->columns)+1, GetOpenMPMaximumThreads()*sizeof(*kernel)); if ((pixels_info == (MemoryInfo *) NULL) || (kernel == (float *) NULL)) { if (kernel != (float *) NULL) kernel=(float *) RelinquishMagickMemory(kernel); if (pixels_info != (MemoryInfo *) NULL) pixels_info=RelinquishVirtualMemory(pixels_info); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(float *) GetVirtualMemoryBlob(pixels_info); status=MagickTrue; number_pixels=image->columns*image->rows; max_channels=(size_t) (image->colorspace == CMYKColorspace ? 4 : 3); image_view=AcquireAuthenticCacheView(image,exception); noise_view=AcquireAuthenticCacheView(noise_image,exception); for (channel=0; channel < (ssize_t) max_channels; channel++) { register ssize_t i; size_t high_pass, low_pass; ssize_t level, y; if (status == MagickFalse) continue; /* Copy channel from image to wavelet pixel array. */ i=0; for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; ssize_t x; p=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) { status=MagickFalse; break; } indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { switch (channel) { case 0: pixels[i]=(float) GetPixelRed(p); break; case 1: pixels[i]=(float) GetPixelGreen(p); break; case 2: pixels[i]=(float) GetPixelBlue(p); break; case 3: pixels[i]=(float) indexes[x]; break; default: break; } i++; p++; } } /* Low pass filter outputs are called approximation kernel & high pass filters are referred to as detail kernel. The detail kernel have high values in the noisy parts of the signal. */ high_pass=0; for (level=0; level < 5; level++) { double magnitude; ssize_t x, y; low_pass=(size_t) (number_pixels*((level & 0x01)+1)); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,1) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register float *magick_restrict p, *magick_restrict q; register ssize_t x; p=kernel+id*image->columns; q=pixels+y*image->columns; HatTransform(q+high_pass,1,image->columns,(size_t) (1UL << level),p); q+=low_pass; for (x=0; x < (ssize_t) image->columns; x++) *q++=(*p++); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,1) \ magick_number_threads(image,image,image->columns,1) #endif for (x=0; x < (ssize_t) image->columns; x++) { const int id = GetOpenMPThreadId(); register float *magick_restrict p, *magick_restrict q; register ssize_t y; p=kernel+id*image->rows; q=pixels+x+low_pass; HatTransform(q,image->columns,image->rows,(size_t) (1UL << level),p); for (y=0; y < (ssize_t) image->rows; y++) { *q=(*p++); q+=image->columns; } } /* To threshold, each coefficient is compared to a threshold value and attenuated / shrunk by some factor. */ magnitude=threshold*noise_levels[level]; for (i=0; i < (ssize_t) number_pixels; ++i) { pixels[high_pass+i]-=pixels[low_pass+i]; if (pixels[high_pass+i] < -magnitude) pixels[high_pass+i]+=magnitude-softness*magnitude; else if (pixels[high_pass+i] > magnitude) pixels[high_pass+i]-=magnitude-softness*magnitude; else pixels[high_pass+i]*=softness; if (high_pass != 0) pixels[i]+=pixels[high_pass+i]; } high_pass=low_pass; } /* Reconstruct image from the thresholded wavelet kernel. */ i=0; for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register IndexPacket *magick_restrict noise_indexes; register PixelPacket *magick_restrict q; register ssize_t x; q=GetCacheViewAuthenticPixels(noise_view,0,y,noise_image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; break; } noise_indexes=GetCacheViewAuthenticIndexQueue(noise_view); for (x=0; x < (ssize_t) image->columns; x++) { float pixel; pixel=pixels[i]+pixels[low_pass+i]; switch (channel) { case 0: SetPixelRed(q,ClampToQuantum(pixel)); break; case 1: SetPixelGreen(q,ClampToQuantum(pixel)); break; case 2: SetPixelBlue(q,ClampToQuantum(pixel)); break; case 3: SetPixelIndex(noise_indexes+x,ClampToQuantum(pixel)); break; default: break; } i++; q++; } sync=SyncCacheViewAuthenticPixels(noise_view,exception); if (sync == MagickFalse) status=MagickFalse; } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,AddNoiseImageTag,(MagickOffsetType) channel,max_channels); if (proceed == MagickFalse) status=MagickFalse; } } noise_view=DestroyCacheView(noise_view); image_view=DestroyCacheView(image_view); kernel=(float *) RelinquishMagickMemory(kernel); pixels_info=RelinquishVirtualMemory(pixels_info); return(noise_image); }
bml_normalize_ellsort_typed.c
#include "../../macros.h" #include "../../typed.h" #include "../bml_allocate.h" #include "../bml_normalize.h" #include "../bml_parallel.h" #include "../bml_types.h" #include "bml_add_ellsort.h" #include "bml_allocate_ellsort.h" #include "bml_normalize_ellsort.h" #include "bml_scale_ellsort.h" #include "bml_types_ellsort.h" #include <complex.h> #include <float.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef _OPENMP #include <omp.h> #endif /* Normalize ellsort matrix given Gershgorin bounds. * * \ingroup normalize_group * * \param A The matrix * \param mineval Calculated min value * \param maxeval Calculated max value */ void TYPED_FUNC( bml_normalize_ellsort) ( bml_matrix_ellsort_t * A, double mineval, double maxeval) { double maxminusmin = maxeval - mineval; double gershfact = maxeval / maxminusmin; REAL_T scalar = (REAL_T) - 1.0 / maxminusmin; double threshold = 0.0; bml_scale_inplace_ellsort(&scalar, A); bml_add_identity_ellsort(A, gershfact, threshold); } /** Calculate Gershgorin bounds for an ellsort matrix. * * \ingroup normalize_group * * \param A The matrix * \param nrows Number of rows to use * returns mineval Calculated min value * returns maxeval Calculated max value */ void *TYPED_FUNC( bml_gershgorin_ellsort) ( bml_matrix_ellsort_t * A) { REAL_T radius, absham, dvalue; double emin = DBL_MAX; double emax = DBL_MIN; double *eval = bml_allocate_memory(sizeof(double) * 2); int N = A->N; int M = A->M; int *A_nnz = (int *) A->nnz; int *A_index = (int *) A->index; int *A_localRowMin = A->domain->localRowMin; int *A_localRowMax = A->domain->localRowMax; int myRank = bml_getMyRank(); REAL_T rad[N]; REAL_T dval[N]; REAL_T *A_value = (REAL_T *) A->value; #pragma omp parallel for \ shared(N, M, A_nnz, A_index, A_value) \ shared(A_localRowMin, A_localRowMax, myRank) \ shared(rad, dval) \ private(absham, radius, dvalue) \ reduction(max:emax) \ reduction(min:emin) //for (int i = 0; i < N; i++) for (int i = A_localRowMin[myRank]; i < A_localRowMax[myRank]; i++) { radius = 0.0; dvalue = 0.0; for (int j = 0; j < A_nnz[i]; j++) { if (i == A_index[ROWMAJOR(i, j, N, M)]) dvalue = A_value[ROWMAJOR(i, j, N, M)]; else { absham = ABS(A_value[ROWMAJOR(i, j, N, M)]); radius += (double) absham; } } dval[i] = dvalue; rad[i] = radius; /* emax = (emax > REAL_PART(dvalue + radius) ? emax : REAL_PART(dvalue + radius)); emin = (emin < REAL_PART(dvalue - radius) ? emin : REAL_PART(dvalue - radius)); */ } //for (int i = 0; i < N; i++) for (int i = A_localRowMin[myRank]; i < A_localRowMax[myRank]; i++) { if (REAL_PART(dval[i] + rad[i]) > emax) emax = REAL_PART(dval[i] + rad[i]); if (REAL_PART(dval[i] - rad[i]) < emin) emin = REAL_PART(dval[i] - rad[i]); } //printf("%d: emin = %e emax = %e\n", myRank, emin, emax); #ifdef DO_MPI if (bml_getNRanks() > 1 && A->distribution_mode == distributed) { bml_minRealReduce(&emin); bml_maxRealReduce(&emax); } #endif eval[0] = emin; eval[1] = emax; return eval; } /** Calculate Gershgorin bounds for a partial ellsort matrix. * * \ingroup normalize_group * * \param A The matrix * \param nrows Number of rows to use * returns mineval Calculated min value * returns maxeval Calculated max value */ void *TYPED_FUNC( bml_gershgorin_partial_ellsort) ( bml_matrix_ellsort_t * A, int nrows) { REAL_T radius, absham, dvalue; double emin = DBL_MAX; double emax = DBL_MIN; double *eval = bml_allocate_memory(sizeof(double) * 2); int N = A->N; int M = A->M; int *A_nnz = (int *) A->nnz; int *A_index = (int *) A->index; REAL_T rad[N]; REAL_T dval[N]; REAL_T *A_value = (REAL_T *) A->value; #pragma omp parallel for \ shared(N, M, A_nnz, A_index, A_value) \ shared(rad, dval) \ private(absham, radius, dvalue) \ reduction(max:emax) \ reduction(min:emin) for (int i = 0; i < nrows; i++) { radius = 0.0; dvalue = 0.0; for (int j = 0; j < A_nnz[i]; j++) { if (i == A_index[ROWMAJOR(i, j, N, M)]) dvalue = A_value[ROWMAJOR(i, j, N, M)]; else { absham = ABS(A_value[ROWMAJOR(i, j, N, M)]); radius += (double) absham; } } dval[i] = dvalue; rad[i] = radius; } for (int i = 0; i < nrows; i++) { if (REAL_PART(dval[i] + rad[i]) > emax) emax = REAL_PART(dval[i] + rad[i]); if (REAL_PART(dval[i] - rad[i]) < emin) emin = REAL_PART(dval[i] - rad[i]); } eval[0] = emin; eval[1] = emax; return eval; }
GB_binop__lt_uint64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__lt_uint64) // A.*B function (eWiseMult): GB (_AemultB_08__lt_uint64) // A.*B function (eWiseMult): GB (_AemultB_02__lt_uint64) // A.*B function (eWiseMult): GB (_AemultB_04__lt_uint64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__lt_uint64) // A*D function (colscale): GB (_AxD__lt_uint64) // D*A function (rowscale): GB (_DxB__lt_uint64) // C+=B function (dense accum): GB (_Cdense_accumB__lt_uint64) // C+=b function (dense accum): GB (_Cdense_accumb__lt_uint64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__lt_uint64) // C=scalar+B GB (_bind1st__lt_uint64) // C=scalar+B' GB (_bind1st_tran__lt_uint64) // C=A+scalar GB (_bind2nd__lt_uint64) // C=A'+scalar GB (_bind2nd_tran__lt_uint64) // C type: bool // A type: uint64_t // A pattern? 0 // B type: uint64_t // B pattern? 0 // BinaryOp: cij = (aij < bij) #define GB_ATYPE \ uint64_t #define GB_BTYPE \ uint64_t #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint64_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint64_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x < y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LT || GxB_NO_UINT64 || GxB_NO_LT_UINT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__lt_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__lt_uint64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__lt_uint64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type uint64_t uint64_t bwork = (*((uint64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__lt_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__lt_uint64) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__lt_uint64) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; uint64_t alpha_scalar ; uint64_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint64_t *) alpha_scalar_in)) ; beta_scalar = (*((uint64_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__lt_uint64) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__lt_uint64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__lt_uint64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__lt_uint64) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__lt_uint64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; uint64_t x = (*((uint64_t *) x_input)) ; uint64_t *Bx = (uint64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint64_t bij = GBX (Bx, p, false) ; Cx [p] = (x < bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__lt_uint64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; uint64_t *Ax = (uint64_t *) Ax_input ; uint64_t y = (*((uint64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint64_t aij = GBX (Ax, p, false) ; Cx [p] = (aij < y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x < aij) ; \ } GrB_Info GB (_bind1st_tran__lt_uint64) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t x = (*((const uint64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij < y) ; \ } GrB_Info GB (_bind2nd_tran__lt_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t y = (*((const uint64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unop__identity_int16_int16.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_int16_int16) // op(A') function: GB (_unop_tran__identity_int16_int16) // C type: int16_t // A type: int16_t // cast: int16_t cij = aij // unaryop: cij = aij #define GB_ATYPE \ int16_t #define GB_CTYPE \ int16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ int16_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int16_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int16_t z = aij ; \ Cx [pC] = z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 1 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_int16_int16) ( int16_t *Cx, // Cx and Ax may be aliased const int16_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (int16_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int16_t aij = Ax [p] ; int16_t z = aij ; Cx [p] = z ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; int16_t aij = Ax [p] ; int16_t z = aij ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_int16_int16) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
task-dependency.c
/* * task-dependency.c -- Archer testcase */ //===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // // See tools/archer/LICENSE.txt for details. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // RUN: %libarcher-compile-and-run-race | FileCheck %s // REQUIRES: tsan #include "ompt/ompt-signal.h" #include <omp.h> #include <stdio.h> #include <unistd.h> int main(int argc, char *argv[]) { int var = 0, a = 0; #pragma omp parallel num_threads(2) shared(var, a) #pragma omp master { #pragma omp task shared(var, a) depend(out : var) { OMPT_SIGNAL(a); var++; } #pragma omp task shared(a) depend(in : var) { OMPT_SIGNAL(a); OMPT_WAIT(a, 3); } #pragma omp task shared(var) // depend(in: var) is missing here! { var++; OMPT_SIGNAL(a); } // Give other thread time to steal the task. OMPT_WAIT(a, 2); } int error = (var != 2); fprintf(stderr, "DONE\n"); return error; } // CHECK: WARNING: ThreadSanitizer: data race // CHECK-NEXT: {{(Write|Read)}} of size 4 // CHECK-NEXT: #0 {{.*}}task-dependency.c:41 // CHECK: Previous write of size 4 // CHECK-NEXT: #0 {{.*}}task-dependency.c:30 // CHECK: DONE // CHECK: ThreadSanitizer: reported 1 warnings
GB_unaryop__abs_uint32_fp64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__abs_uint32_fp64 // op(A') function: GB_tran__abs_uint32_fp64 // C type: uint32_t // A type: double // cast: uint32_t cij ; GB_CAST_UNSIGNED(cij,aij,32) // unaryop: cij = aij #define GB_ATYPE \ double #define GB_CTYPE \ uint32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ double aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, x) \ uint32_t z ; GB_CAST_UNSIGNED(z,x,32) ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_UINT32 || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_uint32_fp64 ( uint32_t *restrict Cx, const double *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__abs_uint32_fp64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
graph.c
#include "graph.h" // Returns an array of graph nodes built from a csr format matrix node* buildGraph(int vertices, const int* colIDs, const int* rowDel){ // Allocate memory for graph array node* graph = calloc(vertices, sizeof(node)); // Go through nodes and initialize them #pragma omp parallel shared(graph, vertices, colIDs, rowDel) default(none) { #pragma omp single for (int i = 0; i < vertices; i++) { graph[i].id = i; graph[i].level = INT_MAX; // Count neighbors graph[i].neighborsNum = rowDel[i + 1] - rowDel[i]; // Add neighbors to the neighbors list graph[i].neighbors = malloc(graph[i].neighborsNum * sizeof(int)); } #pragma omp for for (int i = 0; i < vertices; i++) { for (int k = rowDel[graph[i].id], elCounter = 0; k < rowDel[graph[i].id + 1]; k++) { if (colIDs[k] != graph[i].id) { graph[i].neighbors[elCounter] = colIDs[k]; elCounter++; }else{ graph[i].neighborsNum--; } } } } return graph; } node* buildGraphSequential(int vertices, const int* colIDs, const int* rowDel){ // Allocate memory for graph array node* graph = calloc(vertices, sizeof(node)); // Go through nodes and initialize them for(int i = 0; i < vertices; i++){ graph[i].id = i; graph[i].level = INT_MAX; // Count neighbors graph[i].neighborsNum = rowDel[i+1] - rowDel[i]; // Add neighbors to the neighbors list graph[i].neighbors = malloc(graph[i].neighborsNum * sizeof(int)); int elCounter = 0; for(int k = rowDel[graph[i].id]; k < rowDel[graph[i].id + 1]; k++){ if(colIDs[k] == graph[i].id){ graph[i].neighborsNum--; } if(colIDs[k] != graph[i].id){ graph[i].neighbors[elCounter] = colIDs[k]; elCounter++; } } } return graph; } // Return a list of nodes-neighbors, children, and the count of children of a node that are on a specified level int neighborsAtLevel(node* graph, node* n, int level, node** children){ // Count children int childrenCount = 0; // Place children in the children array for(int j = 0; j < n->neighborsNum; j++){ if(graph[n->neighbors[j]].level == level){ children[childrenCount++] = &graph[n->neighbors[j]]; } } // Return children count return childrenCount; } // Get the height, width and number of nodes on each level of the graph void graphHeightWidthCounts(node* graph, int vertices, int* height, int* width, int** levelCounts){ // Allocate shared arrays int maxThreads = omp_get_max_threads(); int* localcount = calloc(maxThreads * vertices, sizeof(int)); int* localmax = calloc(maxThreads, sizeof(int)); #pragma omp parallel shared(localcount, localmax, graph, vertices, height, levelCounts) default(none) { int tid = omp_get_thread_num(); int teamThreads = omp_get_team_size(omp_get_level()); #pragma omp for schedule(guided) nowait for(int i = 0; i < vertices; i++){ localcount[tid * vertices + graph[i].level]++; if(localmax[tid] < graph[i].level){ localmax[tid] = graph[i].level; } } #pragma omp single { // Determine height (max_level) *height = 0; for (int k = 0; k < teamThreads; k++) { if (*height < localmax[k]) { *height = localmax[k]; } } // Form counts *levelCounts = calloc(*height + 1, sizeof(int)); } #pragma omp for schedule(guided) nowait for(int i = 0; i < *height + 1; i++){ for(int id = 0; id < teamThreads; id++){ (*levelCounts)[i] += localcount[id * vertices + i]; } } } // Determine width (maximum number of nodes on a level) *width = *levelCounts[0]; for(int j = 1; j < *height + 1; j++){ if((*levelCounts)[j] > *width){ *width = (*levelCounts)[j]; } } // Free memory free(localcount); free(localmax); } // Returns a pointer to an array with the nodes at a specific level. node** graphVerticesAt(node* graph, int vertices, int level, int levelNodes){ // Allocate returned array node** verticesAtLevel = calloc(levelNodes, sizeof(node*)); int verticesAtLevelIdx = 0; // Scan graph adding vertices at level to the results array for(int i = 0; i < vertices; i++){ if(graph[i].level == level){ verticesAtLevel[verticesAtLevelIdx] = &graph[i]; verticesAtLevelIdx++; } } return verticesAtLevel; } // Returns an array with the prefix sums of the provided counts array int* prefixSums(int* counts, int height){ // Create a copy of the provided array to act upon and return // maxLevel + 1 because levels start from 0 int* prefix_sums; prefix_sums = malloc((height + 1) * sizeof(int)); memcpy(prefix_sums, counts, (height + 1) * sizeof(int)); // Check if work is worth done sequentially if(height < PREFIX_SUMS_SEQ_LIMIT){ prefixSumsSeq(prefix_sums, height + 1); return prefix_sums; } // Get and set maximum number of threads and calculate work per thread and number of switching stages int maxThreads = PREFIX_SUMS_THREADS; // omp_set_num_threads(maxThreads); // We assume a system with threads at a power of 2 int num_changes = (int)log2(maxThreads); // Chunk up the work int chunk = (height + 1) / maxThreads; int remainder = (height + 1) % maxThreads; int workIndexes[maxThreads + 1]; workIndexes[0] = 0; for(int i = 1, sum = 0; i < maxThreads + 1; i++){ sum += chunk; if(i <= remainder) sum++; workIndexes[i] = sum; } // Parallel calculate local prefix sums int cPrefix[maxThreads], cTotal[maxThreads], lPrefix[maxThreads], lTotal[maxThreads]; #pragma omp parallel shared(prefix_sums, workIndexes, cPrefix, cTotal, lPrefix, lTotal, maxThreads, num_changes) \ default(none) num_threads(PREFIX_SUMS_THREADS) { int tid = omp_get_thread_num(); int elementsNum = workIndexes[tid+1] - workIndexes[tid]; prefixSumsSeq(prefix_sums + workIndexes[tid], elementsNum); cPrefix[tid] = cTotal[tid] = prefix_sums[workIndexes[tid+1] - 1]; lPrefix[tid] = lTotal[tid] = prefix_sums[workIndexes[tid+1] - 1]; #pragma omp barrier for(int i = 0; i < num_changes; i++){ int tidn = tid ^ ((int)pow(2, i)); if((tidn < maxThreads) && (tidn != tid)){ if(tidn > tid){ lPrefix[tidn] += cTotal[tid]; lTotal[tidn] += cTotal[tid]; }else{ lTotal[tidn] += cTotal[tid]; } } // Sync threads before writing to the cross arrays (cTotal/cPrefix) #pragma omp barrier cPrefix[tid] = lPrefix[tid]; cTotal[tid] = lTotal[tid]; #pragma omp barrier } if(tid != 0){ for(int j = workIndexes[tid]; j < workIndexes[tid+1]; j++){ prefix_sums[j] += cPrefix[tid - 1]; } } } return prefix_sums; } // Sequential prefix sums on array void prefixSumsSeq(int* array, int elements){ int sum = 0; for(int i = 0; i < elements; i++){ sum += array[i]; array[i] = sum; } }
pooling_2x2_pack4.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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. static void pooling2x2s2_max_pack4_sse(const Mat& bottom_blob, Mat& top_blob, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; const int tailstep = (w - 2 * outw + w) * 4; #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < inch; q++) { const Mat img0 = bottom_blob.channel(q); float* outptr = top_blob.channel(q); const float* r0 = img0.row(0); const float* r1 = img0.row(1); for (int i = 0; i < outh; i++) { int j = 0; for (; j < outw; j++) { __m128 _r00 = _mm_loadu_ps(r0); __m128 _r01 = _mm_loadu_ps(r0 + 4); __m128 _r10 = _mm_loadu_ps(r1); __m128 _r11 = _mm_loadu_ps(r1 + 4); __m128 _max0 = _mm_max_ps(_r00, _r01); __m128 _max1 = _mm_max_ps(_r10, _r11); __m128 _max = _mm_max_ps(_max0, _max1); _mm_storeu_ps(outptr, _max); r0 += 8; r1 += 8; outptr += 4; } r0 += tailstep; r1 += tailstep; } } }
shared-clauseModificado.c
#include <stdio.h> #ifdef _OPENMP #include <omp.h> #endif void main(){ int i, n=7; int a[n]; for(i=0;i<n;i++){ a[i]=i+1; } #pragma omp parallel for shared(a,n) default(none) for(i=0;i<n;i++) a[i]+=i; printf("Después de parallel for:\n"); for(i=0;i<n;i++) printf("a[%d] = %d\n",i,a[i]); }//fin del main
eppsteinPAR.h
#pragma once #ifndef BRONKERBOSCHEPPSTEINPAR_H #define BRONKERBOSCHEPPSTEINPAR_H #include "../general.h" #include <ctime> #include <gms/algorithms/preprocessing/preprocessing.h> #include "../sequential/tomita.h" #include <gms/third_party/fast_range.h> #include <gms/third_party/fast_statistics.h> #include <parallel/algorithm> #include <gms/common/papi/papiw.h> namespace BkEppsteinPar { template <class SGraph, class Set = typename SGraph::Set> std::vector<Set> mceBench(const SGraph &rgraph, const pvector<NodeId> &ordering) { #ifdef BK_COUNT BK_CLIQUE_COUNTER = 0; //initialize counter #endif auto vCount = rgraph.num_nodes(); std::vector<Set> sol = {}; PAPIW::INIT_PARALLEL(PAPI_RES_STL, PAPI_TOT_CYC); // Init PAPIW #pragma omp parallel shared(rgraph, sol, ordering) { PAPIW::START(); #pragma omp for schedule(dynamic) for (NodeId v = 0; v < vCount; v++) { auto &neigh = rgraph.out_neigh(v); Set cand = {}; Set fini = {}; Set Q(v); for (auto w : neigh) { if (ordering[w] > ordering[v]) cand.union_inplace(w); else fini.union_inplace(w); } BkTomita::expand(cand, fini, Q, sol, rgraph); } PAPIW::STOP(); } PAPIW::PRINT(); return sol; } template <const auto Order, class SGraph, class Set = typename SGraph::Set> std::vector<Set> mce(const SGraph &rgraph) { #ifdef BK_COUNT BK_CLIQUE_COUNTER = 0; //initialize counter #endif pvector<NodeId> ordering(rgraph.num_nodes()); Order(rgraph, ordering); return mceBench(rgraph, ordering); } } // namespace BkEppsteinPar #endif /*BRONKERBOSCHEPPSTEIN_H*/
Utility.h
// // Created by salmon on 18-2-26. // #ifndef SIMPLA_SPDMUTILITIES_H #define SIMPLA_SPDMUTILITIES_H #include <complex> #include <cstddef> #include <iomanip> #include <iostream> #include <list> #include <map> #include <set> #include <sstream> #include <string> #include <utility> #include <vector> #include "TypeTraits.h" namespace simpla { namespace tags { struct split { split(std::size_t _left = 1, std::size_t _right = 1) : my_left(_left), my_right(_right) {} ~split() = default; virtual std::size_t left() const { return my_left; } virtual std::size_t right() const { return my_right; } std::size_t my_left = 1, my_right = 1; }; //! Type enables transmission of splitting proportion from partitioners to range objects /** * In order to make use of such facility Range objects must implement * splitting constructor with this type passed and initialize static * constant boolean field 'is_splittable_in_proportion' with the value * of 'true' */ class proportional_split : public split { public: proportional_split(std::size_t _left = 1, std::size_t _right = 1) { split::my_left = _left; split::my_right = _right; } proportional_split(proportional_split const &) = delete; ~proportional_split() {} }; } // namespace tags namespace utility { /** * std:: */ template <typename T> void swap(std::complex<T> &lhs, std::complex<T> &rhs) { std::swap(lhs, rhs); } template <typename T> void swap(T &lhs, T &rhs, std::enable_if_t<traits::rank<T>::value == 0> *_p = nullptr) { std::swap(lhs, rhs); } template <typename TL, typename TR> void swap(TL &&lhs, TR &rhs, std::enable_if_t<(traits::is_similar<TL, TR>::value) && (traits::rank<TL>::value > 0)> *_p = nullptr) { for (std::size_t i = 0; i < traits::extent<TL>::value; ++i) { swap(lhs[i], rhs[i]); } } template <typename TL, typename TR> void swap(TL &lhs, TR &&rhs, std::enable_if_t<(traits::is_similar<TL, TR>::value) && (traits::rank<TL>::value > 0)> *_p = nullptr) { for (std::size_t i = 0; i < traits::extent<TL>::value; ++i) { swap(lhs[i], rhs[i]); } } template <typename TL, typename TR> void swap(TL &&lhs, TR &&rhs, std::enable_if_t<(traits::is_similar<TL, TR>::value) && (traits::rank<TL>::value > 0)> *_p = nullptr) { for (std::size_t i = 0; i < traits::extent<TL>::value; ++i) { swap(lhs[i], rhs[i]); } } template <typename TL, typename TR> void swap(TL &lhs, TR &rhs, std::enable_if_t<(traits::is_similar<TL, TR>::value) && (traits::rank<TL>::value > 0)> *_p = nullptr) { for (std::size_t i = 0; i < traits::extent<TL>::value; ++i) { swap(lhs[i], rhs[i]); } } template <std::size_t I, typename... U> decltype(auto) get(std::tuple<U...> &v) { return std::get<I>(v); }; template <std::size_t I, typename... U> decltype(auto) get(std::tuple<U...> const &v) { return std::get<I>(v); }; template <std::size_t I, typename... U> decltype(auto) get(std::tuple<U...> &&v) { return std::get<I>(v); }; template <std::size_t I, typename U> decltype(auto) get(U &u, std::enable_if_t<traits::rank<U>::value == 0> *_p = nullptr) { return (u); }; template <std::size_t I, typename U> decltype(auto) get(U &&u, std::enable_if_t<traits::rank<U>::value == 0> *_p = nullptr) { return std::move(u); }; template <std::size_t I, typename U> decltype(auto) get(U &u, std::enable_if_t<(traits::rank<U>::value > 0)> *_p = nullptr) { static_assert(I < traits::extent<U>::value, "out of range"); return u[I]; }; template <std::size_t I, typename U> decltype(auto) get(U &&u, std::enable_if_t<(traits::rank<U>::value > 0)> *_p = nullptr) { static_assert(I < traits::extent<U>::value, "out of range"); return std::move(u[I]); }; template <typename V> auto sum_n(V const &v) { return v; } template <typename V, typename... Others> auto sum_n(V const &v, Others &&... others) { return v + sum_n(std::forward<Others>(others)...); } template <typename V> auto product_n(V const &v) { return v; } template <typename V, typename... Others> auto product_n(V const &v, Others &&... others) { return v * product_n(std::forward<Others>(others)...); } /** * not std:: */ template <typename T, typename V> V Fill(T &v, V start, V inc = 0, std::enable_if_t<traits::rank<T>::value == 0 && !traits::is_range<T>::value> *_p = nullptr) { v = start; return start + inc; } template <typename T, typename V> V Fill(T &v, V start, V inc = 0, std::enable_if_t<(traits::rank<T>::value > 0)> *_p = nullptr) { for (decltype(auto) item : v) { start = Fill(item, start, inc); } return start; } template <typename TL, typename TR> bool IsEqual(TL const &lhs, TR const &rhs, std::enable_if_t<!traits::is_similar<TL, TR>::value && traits::rank<TR>::value != 0> *_p = nullptr) { return false; } template <typename TL, typename TR> bool IsEqual(TL const &lhs, TR const &rhs, std::enable_if_t<!traits::is_similar<TL, TR>::value && traits::rank<TR>::value == 0> *_p = nullptr) { bool res = true; for (auto const &item : lhs) { res = res && IsEqual(item, rhs); if (!res) { break; } } return res; } template <typename TL, typename TR> bool IsEqual(TL const &lhs, TR const &rhs, std::enable_if_t<traits::is_similar<TL, TR>::value && traits::rank<TR>::value == 0> *_p = nullptr) { return lhs == rhs; } template <typename TL, typename TR> bool IsEqual(TL const &lhs, TR const &rhs, std::enable_if_t<traits::is_similar<TL, TR>::value && traits::rank<TR>::value != 0> *_p = nullptr) { int n = 0; bool res = true; for (auto const &item : lhs) { res = res && IsEqual(item, rhs[n]); ++n; if (!res) { break; } } return res; } template <typename TL, typename TR> bool IsEqualP(TL const &lhs, TR const *rhs, std::enable_if_t<traits::rank<TL>::value == 0> *_p = nullptr) { return lhs == *rhs; } template <typename TL, typename TR> bool IsEqualP(TL const &lhs, TR const *rhs, std::enable_if_t<traits::rank<TL>::value != 0> *_p = nullptr) { bool res = true; for (auto const &item : lhs) { res = res && IsEqualP(item, rhs); rhs += traits::number_of_elements<traits::remove_extent_t<TL>>::value; if (!res) { break; } } return res; } template <typename OS, typename TV> OS &FancyPrint(OS &os, TV const &t, int indent = 0, unsigned tab_width = 1, char left = '{', char split = ',', char right = '}', std::enable_if_t<(traits::rank<TV>::value == 0)> *_p = nullptr) { os << t; return os; }; template <typename OS, typename TV> OS &FancyPrint(OS &os, TV const &t, int indent = 0, unsigned tab_width = 1, char left = '{', char split = ',', char right = '}', std::enable_if_t<(traits::rank<TV>::value != 0)> *_p = nullptr) { os << std::setw(indent + tab_width) << left; if (traits::rank<TV>::value > 1) { os << std::endl; } bool is_first = true; for (decltype(auto) item : t) { if (is_first) { is_first = false; } else { os << split; if (traits::rank<TV>::value > 1) { os << std::endl; } } FancyPrint(os, item, indent + tab_width, tab_width, left, split, right); } if (traits::rank<TV>::value > 1) { os << std::endl << std::setw(indent + 1); } os << right; return os; }; template <typename OS, typename TV, typename TI> TV FancyPrintP(OS &os, TV v, unsigned int ndim, TI const *dims, int indent = 0, unsigned tab_width = 1, char left = '{', char split = ',', char right = '}') { os << left; if (ndim > 1) { os << std::endl; } for (std::size_t s = 0; s < dims[0]; ++s) { if (s > 0) { if (ndim > 1) { os << split << std::endl << std::setw(indent + tab_width); } else { os << split << std::setw(tab_width); } } else if (ndim > 1) { os << std::setw(indent + tab_width); } if (ndim == 1) { os << *v; ++v; } else { v = FancyPrintP(os, v, ndim - 1, dims + 1, indent + tab_width, tab_width, left, split, right); } } if (ndim > 1) { os << std::endl << std::setw(indent); } os << right; return v; }; /** @ingroup design_pattern * * @addtogroup singleton Singleton * @{ * * @brief singleton * * @note Meyers Singleton, * Ref:Andrei Alexandrescu Chap 6.4 * Modern C++ Design Generic Programming and Design Patterns Applied 2001 Addison Wesley , */ template <class T> class SingletonHolder { public: static T &instance() { if (!pInstance_) { //#pragma omp critical // TOD add some for mt critical if (!pInstance_) { static T tmp; pInstance_ = &tmp; } } return *pInstance_; } protected: SingletonHolder() {} ~SingletonHolder() {} static T *volatile pInstance_; }; template <class T> T *volatile SingletonHolder<T>::pInstance_ = 0; } // namespace utility { } // namespace simpla { #define SP_FILE_LINE_STAMP \ (std::string("[ ") + (__FILE__) + ":" + std::to_string(__LINE__) + ":0: " + (__PRETTY_FUNCTION__) + " ] :") #define ERR_UNIMPLEMENTED throw(std::runtime_error("\nERROR:" + SP_FILE_LINE_STAMP + "UNIMPLEMENTED!")) #define ERR_OUT_OF_RANGE(_MSG_) throw(std::out_of_range("\nERROR:" + SP_FILE_LINE_STAMP + "OUT_OF_RANGE!" + _MSG_)) namespace simpla { /** * @ingroup toolbox * @addtogroup fancy_print Fancy print * @{ */ template <typename TV, typename TI> inline TV const *printNdArray(std::ostream &os, TV const *v, int rank, TI const *d, bool is_first = true, bool is_last = true, std::string const &left_brace = "{", std::string const &sep = ",", std::string const &right_brace = "}", bool is_slow_first = true, int tab_width = 0, int indent = 0) { constexpr int ELE_NUM_PER_LINE = 10; if (rank == 1) { os << left_brace; for (int s = 0; s < d[0]; ++s) { if (s > 0) { os << sep; } if (s % ELE_NUM_PER_LINE == 0 && s != 0) { os << std::endl; } if (tab_width > 0) { os << std::setw(10) << " "; } os << (*v); ++v; } os << right_brace; } else { os << left_brace; for (int s = 0; s < d[0]; ++s) { if (s > 0) { os << sep; // if (rank > 1) { os << std::endl << std::setw(tab_width) << " "; } } v = printNdArray(os, v, rank - 1, d + 1, s == 0, s == d[0] - 1, left_brace, sep, right_brace, is_slow_first, tab_width, indent + 1); } os << right_brace; return (v); } // if (is_last) { os << std::endl; } return v; } namespace detail { template <std::size_t... IDX, typename V, typename I> auto GetValue(std::integer_sequence<std::size_t, IDX...>, V const &v, I const *idx) { return v(idx[IDX]...); }; } template <int NDIMS, typename TV, typename TI> std::ostream &FancyPrintNdSlowFirst(std::ostream &os, TV const &v, int depth, int *idx, TI const *lo, TI const *hi, int indent = 0, int tab_width = 0, std::string const &left_brace = "{", std::string const &sep = ",", std::string const &right_brace = "}") { if (depth >= NDIMS) { return os; } if (depth == NDIMS - 1) { os << std::setw(indent) << left_brace; idx[NDIMS - 1] = lo[NDIMS - 1]; os << std::setw(tab_width) << detail::GetValue(std::make_index_sequence<NDIMS>(), v, idx); for (idx[NDIMS - 1] = lo[NDIMS - 1] + 1; idx[NDIMS - 1] < hi[NDIMS - 1]; ++idx[NDIMS - 1]) { os << sep << std::setw(tab_width) << detail::GetValue(std::make_index_sequence<NDIMS>(), v, idx); } os << right_brace; } else { os << std::setw(indent) << left_brace << std::endl; idx[depth] = lo[depth]; FancyPrintNdSlowFirst<NDIMS>(os, v, depth + 1, idx, lo, hi, indent + 1, tab_width, left_brace, sep, right_brace); for (idx[depth] = lo[depth] + 1; idx[depth] < hi[depth]; ++idx[depth]) { os << sep << std::endl; FancyPrintNdSlowFirst<NDIMS>(os, v, depth + 1, idx, lo, hi, indent + 1, tab_width, left_brace, sep, right_brace); } os << std::endl << std::setw(indent) << right_brace; } return os; } template <int NDIMS, typename TV, typename TI> std::ostream &FancyPrintNdFastFirst(std::ostream &os, TV const &v, int depth, int *idx, TI const *lo, TI const *hi, int indent = 0, int tab_width = 0, std::string const &left_brace = "{", std::string const &sep = ",", std::string const &right_brace = "}") { if (depth < 0) { return os; } if (depth == 0) { os << std::setw(indent + depth) << left_brace; idx[0] = lo[0]; os << std::setw(tab_width) << detail::GetValue(std::make_index_sequence<NDIMS>(), v, idx); for (idx[0] = lo[0] + 1; idx[0] < hi[0]; ++idx[0]) { os << "," << std::setw(tab_width) << detail::GetValue(std::make_index_sequence<NDIMS>(), v, idx); } os << right_brace; } else { os << std::setw(indent) << left_brace << std::endl; idx[depth] = lo[depth]; FancyPrintNdFastFirst<NDIMS>(os, v, depth - 1, idx, lo, hi, indent + 1, tab_width, left_brace, sep, right_brace); for (idx[depth] = lo[depth] + 1; idx[depth] < hi[depth]; ++idx[depth]) { os << "," << std::endl; FancyPrintNdFastFirst<NDIMS>(os, v, depth - 1, idx, lo, hi, indent + 1, tab_width, left_brace, sep, right_brace); } os << std::endl << std::setw(indent) << right_brace; } return os; } template <int NDIMS, typename TV, typename TI> std::ostream &FancyPrintNd(std::ostream &os, TV const &v, TI const *lo, TI const *hi, bool is_slow_first = true, int indent = 0, int tab_width = 8, std::string const &left_brace = "{", std::string const &sep = ",", std::string const &right_brace = "}") { constexpr int ELE_NUM_PER_LINE = 10; int idx[NDIMS]; if (is_slow_first) { FancyPrintNdSlowFirst<NDIMS>(os, v, 0, idx, lo, hi, indent, tab_width, left_brace, sep, right_brace); } else { FancyPrintNdFastFirst<NDIMS>(os, v, NDIMS - 1, idx, lo, hi, indent, tab_width, left_brace, sep, right_brace); } return os; } template <typename TX, typename TY, typename... Others> std::istream &get_(std::istream &is, size_t num, std::map<TX, TY, Others...> &a) { for (size_t s = 0; s < num; ++s) { TX x; TY y; is >> x >> y; a.emplace(x, y); } return is; } template <typename V> std::ostream &FancyPrint(std::ostream &os, V const *d, std::size_t ndims, std::size_t const *extents, int indent) { printNdArray(os, d, ndims, extents, true, false, "[", ",", "]", true, 0, indent); return os; } template <typename TI> std::ostream &PrintArray1(std::ostream &os, TI const &ib, TI const &ie, int indent = 0); template <typename TI> std::ostream &PrintArray1(std::ostream &os, TI const *d, int num, int indent = 0); template <typename TI> std::ostream &PrintKeyValue(std::ostream &os, TI const &ib, TI const &ie, int indent = 0); template <typename TI, typename TFUN> std::ostream &ContainerOutPut3(std::ostream &os, TI const &ib, TI const &ie, TFUN const &fun, int indent = 0); template <typename T> std::ostream &FancyPrint(std::ostream &os, T const &d, int indent, std::enable_if_t<(traits::rank<T>::value == 0)> *_p = nullptr) { os << d; return os; } template <typename T> std::ostream &FancyPrint(std::ostream &os, T const &d, int indent, std::enable_if_t<(traits::rank<T>::value > 0)> *_p = nullptr) { os << "["; FancyPrint(os, d[0], indent + 1); for (size_t i = 1; i < std::extent<T, 0>::value; ++i) { os << ", "; if (std::rank<T>::value > 1) { os << std::endl << std::setw(indent) << " "; } FancyPrint(os, d[i], indent + 1); } os << "]"; return os; } inline std::ostream &FancyPrint(std::ostream &os, bool const &d, int indent) { os << std::boolalpha << d; return os; } inline std::ostream &FancyPrint(std::ostream &os, std::string const &s, int indent) { os << "\"" << s << "\""; return os; } template <typename T> std::ostream &FancyPrint(std::ostream &os, const std::complex<T> &tv, int indent = 0) { os << "{" << tv.real() << "," << tv.imag() << "}"; return (os); } template <typename T1, typename T2> std::ostream &FancyPrint(std::ostream &os, std::pair<T1, T2> const &p, int indent = 0) { os << p.first << " = { " << p.second << " }"; return (os); } template <typename T1, typename T2> std::ostream &FancyPrint(std::ostream &os, std::map<T1, T2> const &p, int indent = 0) { for (auto const &v : p) os << v << "," << std::endl; return (os); } template <typename U, typename... Others> std::ostream &FancyPrint(std::ostream &os, std::vector<U, Others...> const &d, int indent = 0) { os << "[ "; PrintArray1(os, d.begin(), d.end(), indent); os << " ]"; return os; } template <typename U, typename... Others> std::ostream &FancyPrint(std::ostream &os, std::list<U, Others...> const &d, int indent = 0) { return PrintArray1(os, d.begin(), d.end(), indent); } template <typename U, typename... Others> std::ostream &FancyPrint(std::ostream &os, std::set<U, Others...> const &d, int indent = 0) { return PrintArray1(os, d.begin(), d.end(), indent); } template <typename U, typename... Others> std::ostream &FancyPrint(std::ostream &os, std::multiset<U, Others...> const &d, int indent = 0) { return PrintArray1(os, d.begin(), d.end(), indent); } template <typename TX, typename TY, typename... Others> std::ostream &FancyPrint(std::ostream &os, std::map<TX, TY, Others...> const &d, int indent = 0) { return PrintKeyValue(os, d.begin(), d.end(), indent); } template <typename TX, typename TY, typename... Others> std::ostream &FancyPrint(std::ostream &os, std::multimap<TX, TY, Others...> const &d, int indent = 0) { return PrintKeyValue(os, d.begin(), d.end(), indent); } // template <typename T, int... M> // std::ostream &FancyPrint(std::ostream &os, algebra::declare::nTuple_<T, M...> const &v) { // return algebra::_detail::printNd_(os, v.m_data_, int_sequence<M...>()); //} namespace _impl { template <typename... Args> std::ostream &print_helper(std::ostream &os, std::tuple<Args...> const &v, std::integral_constant<int, 0>, int indent = 0) { return os; }; template <typename... Args, int N> std::ostream &print_helper(std::ostream &os, std::tuple<Args...> const &v, std::integral_constant<int, N>, int indent = 0) { os << ", "; FancyPrint(os, std::get<sizeof...(Args) - N>(v), indent); print_helper(os, v, std::integral_constant<int, N - 1>(), indent); return os; }; } template <typename T, typename... Args> std::ostream &FancyPrint(std::ostream &os, std::tuple<T, Args...> const &v, int indent = 0) { os << "{ "; FancyPrint(os, std::get<0>(v), indent); _impl::print_helper(os, v, std::integral_constant<int, sizeof...(Args)>(), indent + 1); os << "}"; return os; }; template <typename TI> std::ostream &PrintArray1(std::ostream &os, TI const &ib, TI const &ie, int indent) { if (ib == ie) { return os; } TI it = ib; FancyPrint(os, *it, indent + 1); size_t s = 0; ++it; for (; it != ie; ++it) { os << ", "; FancyPrint(os, *it, indent + 1); ++s; if (s % 10 == 0) { os << std::endl; } } return os; } // template <typename TI> // std::ostream &PrintArry1(std::ostream &os, TI const *d, int num, int tab_width) { // if (num == 0) { return os; } // FancyPrint(os, d[0], tab_width + 1); // for (int s = 1; s < num; ++s) { // os << ", "; // FancyPrint(os, d[s], tab_width + 1); // if (s % 10 == 0) { os << std::endl; } // } // // return os; //} template <typename TI> std::ostream &PrintKeyValue(std::ostream &os, TI const &ib, TI const &ie, int indent) { if (ib == ie) { return os; } TI it = ib; FancyPrint(os, it->first, indent); os << "="; FancyPrint(os, it->second, indent + 1); ++it; for (; it != ie; ++it) { os << " , " << std::endl << std::setw(indent) << " "; FancyPrint(os, it->first, indent); os << " = "; FancyPrint(os, it->second, indent + 1); } return os; } std::size_t MakeUUID(); } // namespace simpla namespace std { template <typename T> std::ostream &operator<<(std::ostream &os, const std::complex<T> &v) { return simpla::FancyPrint(os, v, 0); } template <typename T1, typename T2> std::ostream &operator<<(std::ostream &os, std::pair<T1, T2> const &v) { return simpla::FancyPrint(os, v, 0); } template <typename T1, typename T2> std::ostream &operator<<(std::ostream &os, std::map<T1, T2> const &v) { return simpla::FancyPrint(os, v, 0); } template <typename TV, typename... Others> std::istream &operator>>(std::istream &is, std::vector<TV, Others...> &a) { for (auto it = a.begin(); it != a.end(); ++it) { is >> *it; } // for (auto &v : a) { is >> v; } // std::Duplicate(std::istream_iterator<TV>(is), std::istream_iterator<TV>(), // std::back_inserter(a)); return is; } template <typename U, typename... Others> std::ostream &operator<<(std::ostream &os, std::vector<U, Others...> const &v) { return simpla::FancyPrint(os, v, 0); } template <typename U, typename... Others> std::ostream &operator<<(std::ostream &os, std::list<U, Others...> const &v) { return simpla::FancyPrint(os, v, 0); } template <typename U, typename... Others> std::ostream &operator<<(std::ostream &os, std::set<U, Others...> const &v) { return simpla::FancyPrint(os, v, 0); } template <typename U, typename... Others> std::ostream &operator<<(std::ostream &os, std::multiset<U, Others...> const &v) { return simpla::FancyPrint(os, v, 0); } template <typename TX, typename TY, typename... Others> std::ostream &operator<<(std::ostream &os, std::map<TX, TY, Others...> const &v) { return simpla::FancyPrint(os, v, 0); } template <typename TX, typename TY, typename... Others> std::ostream &operator<<(std::ostream &os, std::multimap<TX, TY, Others...> const &v) { return simpla::FancyPrint(os, v, 0); } template <typename T, typename... Args> std::ostream &operator<<(std::ostream &os, std::tuple<T, Args...> const &v) { return simpla::FancyPrint(os, v, 0); }; } // namespace std{ #endif // SIMPLA_SPDMUTILITIES_H
displacement_lagrangemultiplier_mixed_frictional_contact_criteria.h
// KRATOS ___| | | | // \___ \ __| __| | | __| __| | | __| _` | | // | | | | | ( | | | | ( | | // _____/ \__|_| \__,_|\___|\__|\__,_|_| \__,_|_| MECHANICS // // License: BSD License // license: StructuralMechanicsApplication/license.txt // // Main authors: Vicente Mataix Ferrandiz // #if !defined(KRATOS_DISPLACEMENT_LAGRANGE_MULTIPLIER_MIXED_FRICTIONAL_CONTACT_CRITERIA_H) #define KRATOS_DISPLACEMENT_LAGRANGE_MULTIPLIER_MIXED_FRICTIONAL_CONTACT_CRITERIA_H /* System includes */ /* External includes */ /* Project includes */ #include "utilities/table_stream_utility.h" #include "utilities/color_utilities.h" #include "solving_strategies/convergencecriterias/convergence_criteria.h" #include "custom_utilities/active_set_utilities.h" #include "custom_utilities/contact_utilities.h" #include "utilities/constraint_utilities.h" namespace Kratos { ///@addtogroup ContactStructuralMechanicsApplication ///@{ ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@name Kratos Classes ///@{ /** * @class DisplacementLagrangeMultiplierMixedFrictionalContactCriteria * @ingroup ContactStructuralMechanicsApplication * @brief Convergence criteria for contact problems * @details This class implements a convergence control based on nodal displacement and * lagrange multiplier values. The error is evaluated separately for each of them, and * relative and absolute tolerances for both must be specified. * @author Vicente Mataix Ferrandiz */ template< class TSparseSpace, class TDenseSpace > class DisplacementLagrangeMultiplierMixedFrictionalContactCriteria : public ConvergenceCriteria< TSparseSpace, TDenseSpace > { public: ///@name Type Definitions ///@{ /// Pointer definition of DisplacementLagrangeMultiplierMixedFrictionalContactCriteria KRATOS_CLASS_POINTER_DEFINITION( DisplacementLagrangeMultiplierMixedFrictionalContactCriteria ); /// Local Flags KRATOS_DEFINE_LOCAL_FLAG( ENSURE_CONTACT ); KRATOS_DEFINE_LOCAL_FLAG( PRINTING_OUTPUT ); KRATOS_DEFINE_LOCAL_FLAG( TABLE_IS_INITIALIZED ); KRATOS_DEFINE_LOCAL_FLAG( PURE_SLIP ); KRATOS_DEFINE_LOCAL_FLAG( INITIAL_RESIDUAL_IS_SET ); /// The base class definition (and it subclasses) typedef ConvergenceCriteria< TSparseSpace, TDenseSpace > BaseType; typedef typename BaseType::TDataType TDataType; typedef typename BaseType::DofsArrayType DofsArrayType; typedef typename BaseType::TSystemMatrixType TSystemMatrixType; typedef typename BaseType::TSystemVectorType TSystemVectorType; /// The sparse space used typedef TSparseSpace SparseSpaceType; /// The r_table stream definition TODO: Replace by logger typedef TableStreamUtility::Pointer TablePrinterPointerType; /// The index type definition typedef std::size_t IndexType; /// The key type definition typedef std::size_t KeyType; /// The epsilon tolerance definition static constexpr double Tolerance = std::numeric_limits<double>::epsilon(); ///@} ///@name Life Cycle ///@{ /** * @brief Default constructor. * @param DispRatioTolerance Relative tolerance for displacement residual error * @param DispAbsTolerance Absolute tolerance for displacement residual error * @param LMRatioTolerance Relative tolerance for lagrange multiplier residual error * @param LMAbsTolerance Absolute tolerance for lagrange multiplier residual error * @param NormalTangentRatio Ratio between the normal and tangent that will accepted as converged * @param EnsureContact To check if the contact is lost * @param pTable The pointer to the output r_table * @param PrintingOutput If the output is going to be printed in a txt file */ explicit DisplacementLagrangeMultiplierMixedFrictionalContactCriteria( const TDataType DispRatioTolerance, const TDataType DispAbsTolerance, const TDataType LMNormalRatioTolerance, const TDataType LMNormalAbsTolerance, const TDataType LMTangentStickRatioTolerance, const TDataType LMTangentStickAbsTolerance, const TDataType LMTangentSlipRatioTolerance, const TDataType LMTangentSlipAbsTolerance, const TDataType NormalTangentRatio, const bool EnsureContact = false, const bool PureSlip = false, const bool PrintingOutput = false ) : BaseType() { // Set local flags mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ENSURE_CONTACT, EnsureContact); mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT, PrintingOutput); mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::TABLE_IS_INITIALIZED, false); mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP, PureSlip); mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET, false); // The displacement residual mDispRatioTolerance = DispRatioTolerance; mDispAbsTolerance = DispAbsTolerance; // The normal contact residual mLMNormalRatioTolerance = LMNormalRatioTolerance; mLMNormalAbsTolerance = LMNormalAbsTolerance; // The tangent contact residual mLMTangentStickRatioTolerance = LMTangentStickRatioTolerance; mLMTangentStickAbsTolerance = LMTangentStickAbsTolerance; mLMTangentSlipRatioTolerance = LMTangentSlipRatioTolerance; mLMTangentSlipAbsTolerance = LMTangentSlipAbsTolerance; // We get the ratio between the normal and tangent that will accepted as converged mNormalTangentRatio = NormalTangentRatio; } /** * @brief Default constructor (parameters) * @param ThisParameters The configuration parameters */ explicit DisplacementLagrangeMultiplierMixedFrictionalContactCriteria( Parameters ThisParameters = Parameters(R"({})")) : BaseType() { // The default parameters Parameters default_parameters = Parameters(R"( { "ensure_contact" : false, "pure_slip" : false, "print_convergence_criterion" : false, "residual_relative_tolerance" : 1.0e-4, "residual_absolute_tolerance" : 1.0e-9, "contact_displacement_relative_tolerance" : 1.0e-4, "contact_displacement_absolute_tolerance" : 1.0e-9, "frictional_stick_contact_displacement_relative_tolerance" : 1.0e-4, "frictional_stick_contact_residual_relative_tolerance" : 1.0e-9, "frictional_slip_contact_displacement_relative_tolerance" : 1.0e-4, "frictional_slip_contact_residual_relative_tolerance" : 1.0e-9, "ratio_normal_tangent_threshold" : 1.0e-4 })" ); ThisParameters.ValidateAndAssignDefaults(default_parameters); // The displacement residual mDispRatioTolerance = ThisParameters["residual_relative_tolerance"].GetDouble(); mDispAbsTolerance = ThisParameters["residual_absolute_tolerance"].GetDouble(); // The normal contact solution mLMNormalRatioTolerance = ThisParameters["contact_displacement_relative_tolerance"].GetDouble(); mLMNormalAbsTolerance = ThisParameters["contact_displacement_absolute_tolerance"].GetDouble(); // The tangent contact solution mLMTangentStickRatioTolerance = ThisParameters["frictional_stick_contact_displacement_relative_tolerance"].GetDouble(); mLMTangentStickAbsTolerance = ThisParameters["frictional_stick_contact_residual_relative_tolerance"].GetDouble(); mLMTangentSlipRatioTolerance = ThisParameters["frictional_slip_contact_displacement_relative_tolerance"].GetDouble(); mLMTangentSlipAbsTolerance = ThisParameters["frictional_slip_contact_residual_relative_tolerance"].GetDouble(); // We get the ratio between the normal and tangent that will accepted as converged mNormalTangentRatio = ThisParameters["ratio_normal_tangent_threshold"].GetDouble(); // Set local flags mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ENSURE_CONTACT, ThisParameters["ensure_contact"].GetBool()); mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT, ThisParameters["print_convergence_criterion"].GetBool()); mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::TABLE_IS_INITIALIZED, false); mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP, ThisParameters["pure_slip"].GetBool()); mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET, false); } //* Copy constructor. DisplacementLagrangeMultiplierMixedFrictionalContactCriteria( DisplacementLagrangeMultiplierMixedFrictionalContactCriteria const& rOther ) :BaseType(rOther) ,mOptions(rOther.mOptions) ,mDispRatioTolerance(rOther.mDispRatioTolerance) ,mDispAbsTolerance(rOther.mDispAbsTolerance) ,mDispInitialResidualNorm(rOther.mDispInitialResidualNorm) ,mDispCurrentResidualNorm(rOther.mDispCurrentResidualNorm) ,mLMNormalRatioTolerance(rOther.mLMNormalRatioTolerance) ,mLMNormalAbsTolerance(rOther.mLMNormalAbsTolerance) ,mLMTangentStickRatioTolerance(rOther.mLMTangentStickRatioTolerance) ,mLMTangentStickAbsTolerance(rOther.mLMTangentStickAbsTolerance) ,mLMTangentSlipRatioTolerance(rOther.mLMTangentSlipRatioTolerance) ,mLMTangentSlipAbsTolerance(rOther.mLMTangentSlipAbsTolerance) ,mNormalTangentRatio(rOther.mNormalTangentRatio) { } /// Destructor. ~DisplacementLagrangeMultiplierMixedFrictionalContactCriteria() override = default; ///@} ///@name Operators ///@{ /** * @brief Compute relative and absolute error. * @param rModelPart Reference to the ModelPart containing the contact problem. * @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver) * @param rA System matrix (unused) * @param rDx Vector of results (variations on nodal variables) * @param rb RHS vector (residual) * @return true if convergence is achieved, false otherwise */ bool PostCriteria( ModelPart& rModelPart, DofsArrayType& rDofSet, const TSystemMatrixType& rA, const TSystemVectorType& rDx, const TSystemVectorType& rb ) override { if (SparseSpaceType::Size(rb) != 0) { //if we are solving for something // Getting process info ProcessInfo& r_process_info = rModelPart.GetProcessInfo(); // Initialize TDataType disp_residual_solution_norm = 0.0, normal_lm_solution_norm = 0.0, normal_lm_increase_norm = 0.0, tangent_lm_stick_solution_norm = 0.0, tangent_lm_slip_solution_norm = 0.0, tangent_lm_stick_increase_norm = 0.0, tangent_lm_slip_increase_norm = 0.0; IndexType disp_dof_num(0),lm_dof_num(0),lm_stick_dof_num(0),lm_slip_dof_num(0); // The nodes array auto& r_nodes_array = rModelPart.Nodes(); // First iterator const auto it_dof_begin = rDofSet.begin(); // Auxiliar values std::size_t dof_id = 0; TDataType residual_dof_value = 0.0, dof_value = 0.0, dof_incr = 0.0; // The number of active dofs const std::size_t number_active_dofs = rb.size(); // Loop over Dofs #pragma omp parallel for firstprivate(dof_id, residual_dof_value, dof_value, dof_incr) reduction(+:disp_residual_solution_norm,normal_lm_solution_norm,normal_lm_increase_norm,disp_dof_num,lm_dof_num, lm_stick_dof_num, lm_slip_dof_num) for (int i = 0; i < static_cast<int>(rDofSet.size()); i++) { auto it_dof = it_dof_begin + i; dof_id = it_dof->EquationId(); // Check dof id is solved if (dof_id < number_active_dofs) { if (mActiveDofs[dof_id]) { const auto& r_curr_var = it_dof->GetVariable(); if (r_curr_var == VECTOR_LAGRANGE_MULTIPLIER_X) { // The normal of the node (TODO: how to solve this without accesing all the time to the database?) const auto it_node = r_nodes_array.find(it_dof->Id()); dof_value = it_dof->GetSolutionStepValue(0); dof_incr = rDx[dof_id]; const double mu = it_node->GetValue(FRICTION_COEFFICIENT); if (mu < std::numeric_limits<double>::epsilon()) { normal_lm_solution_norm += std::pow(dof_value, 2); normal_lm_increase_norm += std::pow(dof_incr, 2); } else { const double normal_x = it_node->FastGetSolutionStepValue(NORMAL_X); const TDataType normal_dof_value = dof_value * normal_x; const TDataType normal_dof_incr = dof_incr * normal_x; normal_lm_solution_norm += std::pow(normal_dof_value, 2); normal_lm_increase_norm += std::pow(normal_dof_incr, 2); if (it_node->Is(SLIP) || mOptions.Is(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) { tangent_lm_slip_solution_norm += std::pow(dof_value - normal_dof_value, 2); tangent_lm_slip_increase_norm += std::pow(dof_incr - normal_dof_incr, 2); ++lm_slip_dof_num; } else { tangent_lm_stick_solution_norm += std::pow(dof_value - normal_dof_value, 2); tangent_lm_stick_increase_norm += std::pow(dof_incr - normal_dof_incr, 2); ++lm_stick_dof_num; } } ++lm_dof_num; } else if (r_curr_var == VECTOR_LAGRANGE_MULTIPLIER_Y) { // The normal of the node (TODO: how to solve this without accesing all the time to the database?) const auto it_node = r_nodes_array.find(it_dof->Id()); dof_value = it_dof->GetSolutionStepValue(0); dof_incr = rDx[dof_id]; const double mu = it_node->GetValue(FRICTION_COEFFICIENT); if (mu < std::numeric_limits<double>::epsilon()) { normal_lm_solution_norm += std::pow(dof_value, 2); normal_lm_increase_norm += std::pow(dof_incr, 2); } else { const double normal_y = it_node->FastGetSolutionStepValue(NORMAL_Y); const TDataType normal_dof_value = dof_value * normal_y; const TDataType normal_dof_incr = dof_incr * normal_y; normal_lm_solution_norm += std::pow(normal_dof_value, 2); normal_lm_increase_norm += std::pow(normal_dof_incr, 2); if (it_node->Is(SLIP) || mOptions.Is(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) { tangent_lm_slip_solution_norm += std::pow(dof_value - normal_dof_value, 2); tangent_lm_slip_increase_norm += std::pow(dof_incr - normal_dof_incr, 2); ++lm_slip_dof_num; } else { tangent_lm_stick_solution_norm += std::pow(dof_value - normal_dof_value, 2); tangent_lm_stick_increase_norm += std::pow(dof_incr - normal_dof_incr, 2); ++lm_stick_dof_num; } } ++lm_dof_num; } else if (r_curr_var == VECTOR_LAGRANGE_MULTIPLIER_Z) { // The normal of the node (TODO: how to solve this without accesing all the time to the database?) const auto it_node = r_nodes_array.find(it_dof->Id()); dof_value = it_dof->GetSolutionStepValue(0); dof_incr = rDx[dof_id]; const double mu = it_node->GetValue(FRICTION_COEFFICIENT); if (mu < std::numeric_limits<double>::epsilon()) { normal_lm_solution_norm += std::pow(dof_value, 2); normal_lm_increase_norm += std::pow(dof_incr, 2); } else { const double normal_z = it_node->FastGetSolutionStepValue(NORMAL_Z); const TDataType normal_dof_value = dof_value * normal_z; const TDataType normal_dof_incr = dof_incr * normal_z; normal_lm_solution_norm += std::pow(normal_dof_value, 2); normal_lm_increase_norm += std::pow(normal_dof_incr, 2); if (it_node->Is(SLIP) || mOptions.Is(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) { tangent_lm_slip_solution_norm += std::pow(dof_value - normal_dof_value, 2); tangent_lm_slip_increase_norm += std::pow(dof_incr - normal_dof_incr, 2); ++lm_slip_dof_num; } else { tangent_lm_stick_solution_norm += std::pow(dof_value - normal_dof_value, 2); tangent_lm_stick_increase_norm += std::pow(dof_incr - normal_dof_incr, 2); ++lm_stick_dof_num; } } ++lm_dof_num; } else { // We will assume is displacement dof residual_dof_value = rb[dof_id]; disp_residual_solution_norm += residual_dof_value * residual_dof_value; ++disp_dof_num; } } } } if(normal_lm_increase_norm < Tolerance) normal_lm_increase_norm = 1.0; if(tangent_lm_stick_increase_norm < Tolerance) tangent_lm_stick_increase_norm = 1.0; if(tangent_lm_slip_increase_norm < Tolerance) tangent_lm_slip_increase_norm = 1.0; KRATOS_ERROR_IF(mOptions.Is(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ENSURE_CONTACT) && normal_lm_solution_norm < Tolerance) << "ERROR::CONTACT LOST::ARE YOU SURE YOU ARE SUPPOSED TO HAVE CONTACT?" << std::endl; mDispCurrentResidualNorm = disp_residual_solution_norm; const TDataType normal_lm_ratio = std::sqrt(normal_lm_increase_norm/normal_lm_solution_norm); const TDataType tangent_lm_slip_ratio = tangent_lm_slip_solution_norm > Tolerance ? std::sqrt(tangent_lm_slip_increase_norm/tangent_lm_slip_solution_norm) : 0.0; const TDataType tangent_lm_stick_ratio = tangent_lm_stick_solution_norm > Tolerance ? std::sqrt(tangent_lm_stick_increase_norm/tangent_lm_stick_solution_norm) : 0.0; const TDataType normal_lm_abs = std::sqrt(normal_lm_increase_norm)/static_cast<TDataType>(lm_dof_num); const TDataType tangent_lm_stick_abs = lm_stick_dof_num > 0 ? std::sqrt(tangent_lm_stick_increase_norm)/ static_cast<TDataType>(lm_stick_dof_num) : 0.0; const TDataType tangent_lm_slip_abs = lm_slip_dof_num > 0 ? std::sqrt(tangent_lm_slip_increase_norm)/ static_cast<TDataType>(lm_slip_dof_num) : 0.0; const TDataType normal_tangent_stick_ratio = tangent_lm_stick_abs/normal_lm_abs; const TDataType normal_tangent_slip_ratio = tangent_lm_slip_abs/normal_lm_abs; TDataType residual_disp_ratio; // We initialize the solution if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET)) { mDispInitialResidualNorm = (disp_residual_solution_norm < Tolerance) ? 1.0 : disp_residual_solution_norm; residual_disp_ratio = 1.0; mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET, true); } // We calculate the ratio of the displacements residual_disp_ratio = mDispCurrentResidualNorm/mDispInitialResidualNorm; // We calculate the absolute norms TDataType residual_disp_abs = mDispCurrentResidualNorm/disp_dof_num; // We print the results // TODO: Replace for the new log if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) { if (r_process_info.Has(TABLE_UTILITY)) { std::cout.precision(4); TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY]; auto& r_table = p_table->GetTable(); if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) { r_table << residual_disp_ratio << mDispRatioTolerance << residual_disp_abs << mDispAbsTolerance << normal_lm_ratio << mLMNormalRatioTolerance << normal_lm_abs << mLMNormalAbsTolerance << tangent_lm_stick_ratio << mLMTangentStickRatioTolerance << tangent_lm_stick_abs << mLMTangentSlipAbsTolerance << tangent_lm_slip_ratio << mLMTangentSlipRatioTolerance << tangent_lm_slip_abs << mLMTangentStickAbsTolerance; } else { r_table << residual_disp_ratio << mDispRatioTolerance << residual_disp_abs << mDispAbsTolerance << normal_lm_ratio << mLMNormalRatioTolerance << normal_lm_abs << mLMNormalAbsTolerance << tangent_lm_slip_ratio << mLMTangentSlipRatioTolerance << tangent_lm_slip_abs << mLMTangentSlipAbsTolerance; } } else { std::cout.precision(4); if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT)) { KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT("MIXED CONVERGENCE CHECK") << "\tSTEP: " << r_process_info[STEP] << "\tNL ITERATION: " << r_process_info[NL_ITERATION_NUMBER] << std::endl << std::scientific; KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT("\tDISPLACEMENT: RATIO = ") << residual_disp_ratio << BOLDFONT(" EXP.RATIO = ") << mDispRatioTolerance << BOLDFONT(" ABS = ") << residual_disp_abs << BOLDFONT(" EXP.ABS = ") << mDispAbsTolerance << std::endl; KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT("\tNORMAL LAGRANGE MUL: RATIO = ") << normal_lm_ratio << BOLDFONT(" EXP.RATIO = ") << mLMNormalRatioTolerance << BOLDFONT(" ABS = ") << normal_lm_abs << BOLDFONT(" EXP.ABS = ") << mLMNormalAbsTolerance << std::endl; KRATOS_INFO_IF("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria", mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) << BOLDFONT(" STICK LAGRANGE MUL:\tRATIO = ") << tangent_lm_stick_ratio << BOLDFONT(" EXP.RATIO = ") << mLMTangentStickRatioTolerance << BOLDFONT(" ABS = ") << tangent_lm_stick_abs << BOLDFONT(" EXP.ABS = ") << mLMTangentStickAbsTolerance << std::endl; KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT(" SLIP LAGRANGE MUL:\tRATIO = ") << tangent_lm_slip_ratio << BOLDFONT(" EXP.RATIO = ") << mLMTangentSlipRatioTolerance << BOLDFONT(" ABS = ") << tangent_lm_slip_abs << BOLDFONT(" EXP.ABS = ") << mLMTangentSlipAbsTolerance << std::endl; } else { KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << "MIXED CONVERGENCE CHECK" << "\tSTEP: " << r_process_info[STEP] << "\tNL ITERATION: " << r_process_info[NL_ITERATION_NUMBER] << std::endl << std::scientific; KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << "\tDISPLACEMENT: RATIO = " << residual_disp_ratio << " EXP.RATIO = " << mDispRatioTolerance << " ABS = " << residual_disp_abs << " EXP.ABS = " << mDispAbsTolerance << std::endl; KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << "\tNORMAL LAGRANGE MUL: RATIO = " << normal_lm_ratio << " EXP.RATIO = " << mLMNormalRatioTolerance << " ABS = " << normal_lm_abs << " EXP.ABS = " << mLMNormalAbsTolerance << std::endl; KRATOS_INFO_IF("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria", mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) << " STICK LAGRANGE MUL:\tRATIO = " << tangent_lm_stick_ratio << " EXP.RATIO = " << mLMTangentStickRatioTolerance << " ABS = " << tangent_lm_stick_abs << " EXP.ABS = " << mLMTangentStickAbsTolerance << std::endl; KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << " SLIP LAGRANGE MUL:\tRATIO = " << tangent_lm_slip_ratio << " EXP.RATIO = " << mLMTangentSlipRatioTolerance << " ABS = " << tangent_lm_slip_abs << " EXP.ABS = " << mLMTangentSlipAbsTolerance << std::endl; } } } // NOTE: Here we don't include the tangent counter part r_process_info[CONVERGENCE_RATIO] = (residual_disp_ratio > normal_lm_ratio) ? residual_disp_ratio : normal_lm_ratio; r_process_info[RESIDUAL_NORM] = (normal_lm_abs > mLMNormalAbsTolerance) ? normal_lm_abs : mLMNormalAbsTolerance; // We check if converged const bool disp_converged = (residual_disp_ratio <= mDispRatioTolerance || residual_disp_abs <= mDispAbsTolerance); const bool lm_converged = (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ENSURE_CONTACT) && normal_lm_solution_norm < Tolerance) ? true : (normal_lm_ratio <= mLMNormalRatioTolerance || normal_lm_abs <= mLMNormalAbsTolerance) && (tangent_lm_stick_ratio <= mLMTangentStickRatioTolerance || tangent_lm_stick_abs <= mLMTangentStickAbsTolerance || normal_tangent_stick_ratio <= mNormalTangentRatio) && (tangent_lm_slip_ratio <= mLMTangentSlipRatioTolerance || tangent_lm_slip_abs <= mLMTangentSlipAbsTolerance || normal_tangent_slip_ratio <= mNormalTangentRatio); if ( disp_converged && lm_converged ) { if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) { if (r_process_info.Has(TABLE_UTILITY)) { TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY]; auto& r_table = p_table->GetTable(); if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT)) r_table << BOLDFONT(FGRN(" Achieved")); else r_table << "Achieved"; } else { if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT)) KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT("\tConvergence") << " is " << BOLDFONT(FGRN("achieved")) << std::endl; else KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << "\tConvergence is achieved" << std::endl; } } return true; } else { if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) { if (r_process_info.Has(TABLE_UTILITY)) { TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY]; auto& r_table = p_table->GetTable(); if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT)) r_table << BOLDFONT(FRED(" Not achieved")); else r_table << "Not achieved"; } else { if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT)) KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT("\tConvergence") << " is " << BOLDFONT(FRED(" not achieved")) << std::endl; else KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << "\tConvergence is not achieved" << std::endl; } } return false; } } else // In this case all the displacements are imposed! return true; } /** * @brief This function initialize the convergence criteria * @param rModelPart Reference to the ModelPart containing the contact problem. (unused) */ void Initialize( ModelPart& rModelPart) override { BaseType::mConvergenceCriteriaIsInitialized = true; ProcessInfo& r_process_info = rModelPart.GetProcessInfo(); if (r_process_info.Has(TABLE_UTILITY) && mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::TABLE_IS_INITIALIZED)) { TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY]; auto& r_table = p_table->GetTable(); r_table.AddColumn("DP RATIO", 10); r_table.AddColumn("EXP. RAT", 10); r_table.AddColumn("ABS", 10); r_table.AddColumn("EXP. ABS", 10); r_table.AddColumn("N.LM RATIO", 10); r_table.AddColumn("EXP. RAT", 10); r_table.AddColumn("ABS", 10); r_table.AddColumn("EXP. ABS", 10); if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) { r_table.AddColumn("STI. RATIO", 10); r_table.AddColumn("EXP. RAT", 10); r_table.AddColumn("ABS", 10); r_table.AddColumn("EXP. ABS", 10); } r_table.AddColumn("SLIP RATIO", 10); r_table.AddColumn("EXP. RAT", 10); r_table.AddColumn("ABS", 10); r_table.AddColumn("EXP. ABS", 10); r_table.AddColumn("CONVERGENCE", 15); mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::TABLE_IS_INITIALIZED, true); } } /** * @brief This function initializes the solution step * @param rModelPart Reference to the ModelPart containing the contact problem. * @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver) * @param rA System matrix (unused) * @param rDx Vector of results (variations on nodal variables) * @param rb RHS vector (residual) */ void InitializeSolutionStep( ModelPart& rModelPart, DofsArrayType& rDofSet, const TSystemMatrixType& rA, const TSystemVectorType& rDx, const TSystemVectorType& rb ) override { // Initialize flags mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET, false); // Filling mActiveDofs when MPC exist ConstraintUtilities::ComputeActiveDofs(rModelPart, mActiveDofs, rDofSet); } /** * @brief This function finalizes the non-linear iteration * @param rModelPart Reference to the ModelPart containing the problem. * @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver) * @param rA System matrix (unused) * @param rDx Vector of results (variations on nodal variables) * @param rb RHS vector (residual + reactions) */ void FinalizeNonLinearIteration( ModelPart& rModelPart, DofsArrayType& rDofSet, const TSystemMatrixType& rA, const TSystemVectorType& rDx, const TSystemVectorType& rb ) override { // Calling base criteria BaseType::FinalizeNonLinearIteration(rModelPart, rDofSet, rA, rDx, rb); // The current process info ProcessInfo& r_process_info = rModelPart.GetProcessInfo(); r_process_info.SetValue(ACTIVE_SET_COMPUTED, false); } ///@} ///@name Operations ///@{ ///@} ///@name Acces ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Friends ///@{ protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ Flags mOptions; /// Local flags TDataType mDispRatioTolerance; /// The ratio threshold for the norm of the displacement residual TDataType mDispAbsTolerance; /// The absolute value threshold for the norm of the displacement residual TDataType mDispInitialResidualNorm; /// The reference norm of the displacement residual TDataType mDispCurrentResidualNorm; /// The current norm of the displacement residual TDataType mLMNormalRatioTolerance; /// The ratio threshold for the norm of the LM (normal) TDataType mLMNormalAbsTolerance; /// The absolute value threshold for the norm of the LM (normal) TDataType mLMTangentStickRatioTolerance; /// The ratio threshold for the norm of the LM (tangent-stick) TDataType mLMTangentStickAbsTolerance; /// The absolute value threshold for the norm of the LM (tangent-stick) TDataType mLMTangentSlipRatioTolerance; /// The ratio threshold for the norm of the LM (tangent-slip) TDataType mLMTangentSlipAbsTolerance; /// The absolute value threshold for the norm of the LM (tangent-slip) TDataType mNormalTangentRatio; /// The ratio to accept a non converged tangent component in case std::vector<bool> mActiveDofs; /// This vector contains the dofs that are active ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@} ///@name Serialization ///@{ ///@name Private Inquiry ///@{ ///@} ///@name Unaccessible methods ///@{ ///@} }; // Kratos DisplacementLagrangeMultiplierMixedFrictionalContactCriteria ///@name Local flags creation ///@{ /// Local Flags template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::ENSURE_CONTACT(Kratos::Flags::Create(0)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::NOT_ENSURE_CONTACT(Kratos::Flags::Create(0, false)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::PRINTING_OUTPUT(Kratos::Flags::Create(1)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::NOT_PRINTING_OUTPUT(Kratos::Flags::Create(1, false)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::TABLE_IS_INITIALIZED(Kratos::Flags::Create(2)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::NOT_TABLE_IS_INITIALIZED(Kratos::Flags::Create(2, false)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::PURE_SLIP(Kratos::Flags::Create(3)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::NOT_PURE_SLIP(Kratos::Flags::Create(3, false)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::INITIAL_RESIDUAL_IS_SET(Kratos::Flags::Create(4)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::NOT_INITIAL_RESIDUAL_IS_SET(Kratos::Flags::Create(4, false)); } #endif /* KRATOS_DISPLACEMENT_LAGRANGE_MULTIPLIER_MIXED_FRICTIONAL_CONTACT_CRITERIA_H */
conv_direct_hcl_int8_x86.c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /* * Copyright (c) 2021, OPEN AI LAB * Author: qtang@openailab.com */ #include "convolution_param.h" #include "graph/tensor.h" #include "graph/node.h" #include "graph/graph.h" #include "utility/sys_port.h" #include "utility/float.h" #include "utility/log.h" #include "device/cpu/cpu_node.h" #include "device/cpu/cpu_graph.h" #include "device/cpu/cpu_module.h" #include <math.h> #include <string.h> static void pad_int8(int8_t* input, int8_t* output, int in_h, int in_w, int out_h, int out_w, int top, int left, int8_t v) { int8_t* ptr = input; int8_t* outptr = output; int y = 0; // fill top for (; y < top; y++) { int x = 0; for (; x < out_w; x++) { outptr[x] = v; } outptr += out_w; } // fill center for (; y < (top + in_h); y++) { int x = 0; for (; x < left; x++) { outptr[x] = v; } if (in_w < 12) { for (; x < (left + in_w); x++) { outptr[x] = ptr[x - left]; } } else { memcpy(outptr + left, ptr, (size_t)in_w * sizeof(int8_t)); x += in_w; } for (; x < out_w; x++) { outptr[x] = v; } ptr += in_w; outptr += out_w; } // fill bottom for (; y < out_h; y++) { int x = 0; for (; x < out_w; x++) { outptr[x] = v; } outptr += out_w; } } static int conv3x3s1_int8_sse(struct tensor* input_tensor, struct tensor* weight_tensor, struct tensor* bias_tensor, struct tensor* output_tensor, struct conv_param* param, int num_thread) { int inch = input_tensor->dims[1]; int inh = input_tensor->dims[2]; int inw = input_tensor->dims[3]; int in_hw = inh * inw; int outch = output_tensor->dims[1]; int outh = output_tensor->dims[2]; int outw = output_tensor->dims[3]; int out_hw = outh * outw; int out_size = output_tensor->elem_num; int pad_w = param->pad_w0; int pad_h = param->pad_h0; int32_t* output_int32 = (int32_t*)sys_malloc(out_size * sizeof(int32_t)); memset(output_int32, 0, out_size * sizeof(int32_t)); float* output_fp32 = (float*)sys_malloc(out_size * sizeof(float)); int8_t* output_int8 = (int8_t*)output_tensor->data; int8_t* input_int8 = (int8_t*)input_tensor->data; int32_t* bias_int32 = NULL; if (bias_tensor) bias_int32 = (int32_t*)bias_tensor->data; /* get scale value of quantizaiton */ float input_scale = input_tensor->scale; float* kernel_scales = weight_tensor->scale_list; float output_scale = output_tensor->scale; const signed char* kernel = (const signed char*)weight_tensor->data; /* pading */ int inh_tmp = inh + pad_h + pad_h; int inw_tmp = inw + pad_w + pad_w; int8_t* input_tmp = NULL; if (inh_tmp == inh && inw_tmp == inw) input_tmp = input_int8; else { input_tmp = (int8_t*)sys_malloc((size_t)inh_tmp * inw_tmp * inch * sizeof(int8_t)); #pragma omp parallel for num_threads(num_thread) for (int g = 0; g < inch; g++) { int8_t* pad_in = input_int8 + g * inh * inw; int8_t* pad_out = input_tmp + g * inh_tmp * inw_tmp; pad_int8(pad_in, pad_out, inh, inw, inh_tmp, inw_tmp, pad_h, pad_w, 0); } } #pragma omp parallel for num_threads(num_thread) for (int p = 0; p < outch; p++) { int32_t* out0 = output_int32 + p * out_hw; int8_t* kernel0 = (int8_t*)kernel + p * inch * 9; for (int q = 0; q < inch; q++) { int* outptr0 = out0; int8_t* img0 = input_tmp + q * inw_tmp * inh_tmp; int8_t* r0 = img0; int8_t* r1 = img0 + inw_tmp; int8_t* r2 = img0 + inw_tmp * 2; for (int i = 0; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { int sum0 = 0; sum0 += (int)r0[0] * kernel0[0]; sum0 += (int)r0[1] * kernel0[1]; sum0 += (int)r0[2] * kernel0[2]; sum0 += (int)r1[0] * kernel0[3]; sum0 += (int)r1[1] * kernel0[4]; sum0 += (int)r1[2] * kernel0[5]; sum0 += (int)r2[0] * kernel0[6]; sum0 += (int)r2[1] * kernel0[7]; sum0 += (int)r2[2] * kernel0[8]; *outptr0 += sum0; r0++; r1++; r2++; outptr0++; } r0 += 2; r1 += 2; r2 += 2; } kernel0 += 9; } } /* process bias and dequant output from int32 to fp32 */ #pragma omp parallel for num_threads(num_thread) for (int i = 0; i < outch; i++) { for (int j = 0; j < outh * outw; j++) { int output_off = i * (outh * outw) + j; if (bias_tensor) output_fp32[output_off] = (float)(output_int32[output_off] + bias_int32[i]) * input_scale * kernel_scales[i]; else output_fp32[output_off] = (float)output_int32[output_off] * input_scale * kernel_scales[i]; } } /* process activation relu */ if (param->activation == 0) { #pragma omp parallel for num_threads(num_thread) for (int i = 0; i < outch; i++) { for (int j = 0; j < outh * outw; j++) { int output_off = i * (outh * outw) + j; if (output_fp32[output_off] < 0) output_fp32[output_off] = 0; } } } /* process activation relu6 */ if (param->activation > 0) { #pragma omp parallel for num_threads(num_thread) for (int i = 0; i < outch; i++) { for (int j = 0; j < outh * outw; j++) { int output_off = i * (outh * outw) + j; if (output_fp32[output_off] < 0) output_fp32[output_off] = 0; if (output_fp32[output_off] > 6) output_fp32[output_off] = 6; } } } /* quant from fp32 to int8 */ #pragma omp parallel for num_threads(num_thread) for (int i = 0; i < outch; i++) { for (int j = 0; j < outh * outw; j++) { int output_off = i * (outh * outw) + j; int32_t data_i32 = (int32_t)(round(output_fp32[output_off] / output_scale)); if (data_i32 > 127) data_i32 = 127; else if (data_i32 < -127) data_i32 = -127; output_int8[output_off] = (int8_t)data_i32; } } sys_free(output_int32); sys_free(output_fp32); if (!(inh_tmp == inh && inw_tmp == inw)) sys_free(input_tmp); return 0; } static int conv3x3s2_int8_sse(struct tensor* input_tensor, struct tensor* weight_tensor, struct tensor* bias_tensor, struct tensor* output_tensor, struct conv_param* param, int num_thread) { int inch = input_tensor->dims[1]; int inh = input_tensor->dims[2]; int inw = input_tensor->dims[3]; int in_hw = inh * inw; int outch = output_tensor->dims[1]; int outh = output_tensor->dims[2]; int outw = output_tensor->dims[3]; int out_hw = outh * outw; int out_size = output_tensor->elem_num; int pad_w = param->pad_w0; int pad_h = param->pad_h0; int32_t* output_int32 = (int32_t*)sys_malloc(out_size * sizeof(int32_t)); memset(output_int32, 0, out_size * sizeof(int32_t)); float* output_fp32 = (float*)sys_malloc(out_size * sizeof(float)); int8_t* output_int8 = (int8_t*)output_tensor->data; int8_t* input_int8 = (int8_t*)input_tensor->data; int32_t* bias_int32 = NULL; if (bias_tensor) bias_int32 = (int32_t*)bias_tensor->data; /* get scale value of quantizaiton */ float input_scale = input_tensor->scale; float* kernel_scales = weight_tensor->scale_list; float output_scale = output_tensor->scale; const signed char* kernel = (const signed char*)weight_tensor->data; /* pading */ int inh_tmp = inh + pad_h + pad_h; int inw_tmp = inw + pad_w + pad_w; int8_t* input_tmp = NULL; if (inh_tmp == inh && inw_tmp == inw) input_tmp = input_int8; else { input_tmp = (int8_t*)sys_malloc((size_t)inh_tmp * inw_tmp * inch * sizeof(int8_t)); #pragma omp parallel for num_threads(num_thread) for (int g = 0; g < inch; g++) { int8_t* pad_in = input_int8 + g * inh * inw; int8_t* pad_out = input_tmp + g * inh_tmp * inw_tmp; pad_int8(pad_in, pad_out, inh, inw, inh_tmp, inw_tmp, pad_h, pad_w, 0); } } int tailstep = inw_tmp - 2 * outw + inw_tmp; #pragma omp parallel for num_threads(num_thread) for (int p = 0; p < outch; p++) { int32_t* out0 = output_int32 + p * out_hw; int8_t* kernel0 = (int8_t*)kernel + p * inch * 9; for (int q = 0; q < inch; q++) { int* outptr0 = out0; int8_t* img0 = input_tmp + q * inw_tmp * inh_tmp; int8_t* r0 = img0; int8_t* r1 = img0 + inw_tmp; int8_t* r2 = img0 + inw_tmp * 2; for (int i = 0; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { int sum0 = 0; sum0 += (int)r0[0] * kernel0[0]; sum0 += (int)r0[1] * kernel0[1]; sum0 += (int)r0[2] * kernel0[2]; sum0 += (int)r1[0] * kernel0[3]; sum0 += (int)r1[1] * kernel0[4]; sum0 += (int)r1[2] * kernel0[5]; sum0 += (int)r2[0] * kernel0[6]; sum0 += (int)r2[1] * kernel0[7]; sum0 += (int)r2[2] * kernel0[8]; *outptr0 += sum0; r0 += 2; r1 += 2; r2 += 2; outptr0++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } kernel0 += 9; } } /* process bias and dequant output from int32 to fp32 */ #pragma omp parallel for num_threads(num_thread) for (int i = 0; i < outch; i++) { for (int j = 0; j < outh * outw; j++) { int output_off = i * (outh * outw) + j; if (bias_tensor) output_fp32[output_off] = (float)(output_int32[output_off] + bias_int32[i]) * input_scale * kernel_scales[i]; else output_fp32[output_off] = (float)output_int32[output_off] * input_scale * kernel_scales[i]; } } /* process activation relu */ if (param->activation == 0) { #pragma omp parallel for num_threads(num_thread) for (int i = 0; i < outch; i++) { for (int j = 0; j < outh * outw; j++) { int output_off = i * (outh * outw) + j; if (output_fp32[output_off] < 0) output_fp32[output_off] = 0; } } } /* process activation relu6 */ if (param->activation > 0) { #pragma omp parallel for num_threads(num_thread) for (int i = 0; i < outch; i++) { for (int j = 0; j < outh * outw; j++) { int output_off = i * (outh * outw) + j; if (output_fp32[output_off] < 0) output_fp32[output_off] = 0; if (output_fp32[output_off] > 6) output_fp32[output_off] = 6; } } } /* quant from fp32 to int8 */ #pragma omp parallel for num_threads(num_thread) for (int i = 0; i < outch; i++) { for (int j = 0; j < outh * outw; j++) { int output_off = i * (outh * outw) + j; int32_t data_i32 = (int32_t)(round(output_fp32[output_off] / output_scale)); if (data_i32 > 127) data_i32 = 127; else if (data_i32 < -127) data_i32 = -127; output_int8[output_off] = (int8_t)data_i32; } } sys_free(output_int32); sys_free(output_fp32); if (!(inh_tmp == inh && inw_tmp == inw)) sys_free(input_tmp); return 0; } static int run(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { struct node* ir_node = exec_node->ir_node; struct graph* ir_graph = ir_node->graph; struct tensor* input_tensor; struct tensor* weight_tensor; struct tensor* bias_tensor = NULL; struct tensor* output_tensor = NULL; int num_thread = exec_graph->num_thread; /* set the input data and shape again, in case of reshape or dynamic shape */ input_tensor = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[0]); weight_tensor = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[1]); if (ir_node->input_num > 2) bias_tensor = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[2]); output_tensor = get_ir_graph_tensor(ir_graph, ir_node->output_tensors[0]); struct conv_param* conv_param = (struct conv_param*)ir_node->op.param_mem; int ret = -1; switch (conv_param->stride_h) { case 1: ret = conv3x3s1_int8_sse(input_tensor, weight_tensor, bias_tensor, output_tensor, conv_param, num_thread); break; case 2: ret = conv3x3s2_int8_sse(input_tensor, weight_tensor, bias_tensor, output_tensor, conv_param, num_thread); break; default: TLOG_ERR("Direct Convolution Int8 not support the stride %d\n", conv_param->stride_h); } return ret; } static int init_node(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { return 0; } static int release_node(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { return 0; } static int score(struct node_ops* node_ops, struct exec_graph* exec_graph, struct node* exec_node) { struct conv_param* param = (struct conv_param*)exec_node->op.param_mem; struct node* ir_node = exec_node; struct graph* ir_graph = ir_node->graph; struct tensor* input_tensor; int group = param->group; int kernel_h = param->kernel_h; int kernel_w = param->kernel_w; int stride_h = param->stride_h; int stride_w = param->stride_w; int dilation_h = param->dilation_h; int dilation_w = param->dilation_w; int pad_h0 = param->pad_h0; int pad_w0 = param->pad_w0; int pad_h1 = param->pad_h1; int pad_w1 = param->pad_w1; input_tensor = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[0]); /* only support int8 */ if (input_tensor->data_type != TENGINE_DT_INT8) return 0; if (group == 1 && pad_h0 == pad_h1 && pad_w0 == pad_w1 && dilation_h == 1 && dilation_w == 1 && kernel_h == 3 && kernel_w == 3 && ((stride_h == 1 && stride_w == 1) || (stride_h == 2 && stride_w == 2))) return OPS_SCORE_BEST * 2; else return 0; } static struct node_ops hcl_node_ops = {.prerun = NULL, .run = run, .reshape = NULL, .postrun = NULL, .init_node = init_node, .release_node = release_node, .score = score}; int register_conv_direct_hcl_int8_x86_op() { return register_builtin_node_ops(OP_CONV, &hcl_node_ops); } int unregister_conv_direct_hcl_int8_x86_op() { unregister_builtin_node_ops(OP_CONV, &hcl_node_ops); return 0; }
taskloop_tied_threadid.c
// RUN: %libomp-compile-and-run // REQUIRES: abt #include "omp_testsuite.h" #include <string.h> #include <stdio.h> int test_taskloop_tied_threadid(int num_threads) { int vals[NUM_TASKS]; memset(vals, 0, sizeof(vals)); #pragma omp parallel num_threads(num_threads) { #pragma omp master { int i; #pragma omp taskloop grainsize(1) for (i = 0; i < NUM_TASKS; i++) { { ABT_thread abt_thread; ABT_EXIT_IF_FAIL(ABT_thread_self(&abt_thread)); // Context switching in OpenMP. #pragma omp taskyield int omp_thread_id2 = omp_get_thread_num(); ABT_thread abt_thread2; ABT_EXIT_IF_FAIL(ABT_thread_self(&abt_thread2)); ABT_bool abt_thread_equal; ABT_EXIT_IF_FAIL(ABT_thread_equal(abt_thread, abt_thread2, &abt_thread_equal)); if (abt_thread_equal == ABT_TRUE) { vals[i] += 1; } // Context switching in Argobots. ABT_EXIT_IF_FAIL(ABT_thread_yield()); int omp_thread_id3 = omp_get_thread_num(); if (omp_thread_id2 == omp_thread_id3) { // Argobots context switch does not change the thread-task mapping. vals[i] += 2; } } } } } int index; for (index = 0; index < NUM_TASKS; index++) { if (vals[index] != 3) { printf("vals[%d] == %d\n", index, vals[index]); return 0; } } return 1; } int main() { int i; int num_failed = 0; for (i = 0; i < REPETITIONS; i++) { if (!test_taskloop_tied_threadid(i + 1)) { num_failed++; } } return num_failed; }
bdf2_turbulent_scheme.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Jordi Cotela // #if !defined(KRATOS_BDF2_TURBULENT_SCHEME_H_INCLUDED ) #define KRATOS_BDF2_TURBULENT_SCHEME_H_INCLUDED // System includes #include <string> #include <iostream> // External includes // Project includes #include "solving_strategies/schemes/scheme.h" #include "includes/define.h" // #include "includes/serializer.h" #include "includes/dof.h" #include "processes/process.h" #include "containers/pointer_vector_set.h" #include "utilities/coordinate_transformation_utilities.h" // Application includes #include "fluid_dynamics_application_variables.h" namespace Kratos { ///@addtogroup FluidDynamicsApplication ///@{ ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /// A scheme for BDF2 time integration. /** */ template<class TSparseSpace,class TDenseSpace> class BDF2TurbulentScheme : public Scheme<TSparseSpace, TDenseSpace> { public: ///@name Type Definitions ///@{ /// Pointer definition of BDF2TurbulentScheme KRATOS_CLASS_POINTER_DEFINITION(BDF2TurbulentScheme); typedef Scheme<TSparseSpace,TDenseSpace> BaseType; typedef typename TSparseSpace::DataType TDataType; typedef typename TSparseSpace::MatrixType TSystemMatrixType; typedef typename TSparseSpace::VectorType TSystemVectorType; typedef typename TDenseSpace::MatrixType LocalSystemMatrixType; typedef typename TDenseSpace::VectorType LocalSystemVectorType; typedef Dof<TDataType> TDofType; typedef typename BaseType::DofsArrayType DofsArrayType; typedef CoordinateTransformationUtils<LocalSystemMatrixType, LocalSystemVectorType, double> RotationToolType; typedef typename RotationToolType::UniquePointer RotationToolPointerType; ///@} ///@name Life Cycle ///@{ /// Default constructor. BDF2TurbulentScheme() : Scheme<TSparseSpace, TDenseSpace>() , mrPeriodicIdVar(Kratos::Variable<int>::StaticObject()) {} /// Constructor to use the formulation combined with a turbulence model. /** * The turbulence model is assumed to be implemented as a Kratos::Process. * The model's Execute() method wil be called at the start of each * non-linear iteration. * @param pTurbulenceModel pointer to the turbulence model */ BDF2TurbulentScheme(Process::Pointer pTurbulenceModel) : Scheme<TSparseSpace, TDenseSpace>() , mpTurbulenceModel(pTurbulenceModel) , mrPeriodicIdVar(Kratos::Variable<int>::StaticObject()) {} /// Constructor for periodic boundary conditions. /** * @param rPeriodicVar the variable used to store periodic pair indices. */ BDF2TurbulentScheme(const Kratos::Variable<int>& rPeriodicVar) : Scheme<TSparseSpace, TDenseSpace>() , mrPeriodicIdVar(rPeriodicVar) {} /// Destructor. ~BDF2TurbulentScheme() override {} ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ /// Check input data for errors. /** * @param rModelPart The fluid's ModelPart * @return 0 if no errors were found */ int Check(ModelPart& rModelPart) override { KRATOS_TRY // Base scheme check int error_code = BaseType::Check(rModelPart); if (error_code != 0) { return error_code; } // Check buffer size KRATOS_ERROR_IF(rModelPart.GetBufferSize() < 3) << "Insufficient buffer size for BDF2, should be at least 3, got " << rModelPart.GetBufferSize() << std::endl; return 0; KRATOS_CATCH(""); } void Initialize(ModelPart& rModelPart) override { // Set up the rotation tool pointer const auto& r_proces_info = rModelPart.GetProcessInfo(); const unsigned int domain_size = r_proces_info[DOMAIN_SIZE]; auto p_aux = Kratos::make_unique<RotationToolType>(domain_size, domain_size + 1, SLIP); mpRotationTool.swap(p_aux); // Base initialize call BaseType::Initialize(rModelPart); } /// Set the time iteration coefficients void InitializeSolutionStep( ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) override { this->SetTimeCoefficients(rModelPart.GetProcessInfo()); // Base function initializes elements and conditions BaseType::InitializeSolutionStep(rModelPart,A,Dx,b); // Recalculate mesh velocity (to account for variable time step) const double tol = 1.0e-12; const double Dt = rModelPart.GetProcessInfo()[DELTA_TIME]; const double OldDt = rModelPart.GetProcessInfo().GetPreviousSolutionStepInfo(1)[DELTA_TIME]; if(std::abs(Dt - OldDt) > tol) { const int n_nodes = rModelPart.NumberOfNodes(); const Vector& BDFcoefs = rModelPart.GetProcessInfo()[BDF_COEFFICIENTS]; #pragma omp parallel for for(int i_node = 0; i_node < n_nodes; ++i_node) { auto it_node = rModelPart.NodesBegin() + i_node; auto& rMeshVel = it_node->FastGetSolutionStepValue(MESH_VELOCITY); const auto& rDisp0 = it_node->FastGetSolutionStepValue(DISPLACEMENT); const auto& rDisp1 = it_node->FastGetSolutionStepValue(DISPLACEMENT,1); const auto& rDisp2 = it_node->FastGetSolutionStepValue(DISPLACEMENT,2); rMeshVel = BDFcoefs[0] * rDisp0 + BDFcoefs[1] * rDisp1 + BDFcoefs[2] * rDisp2; } } } void InitializeNonLinIteration( ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) override { KRATOS_TRY if (mpTurbulenceModel != 0) mpTurbulenceModel->Execute(); KRATOS_CATCH("") } void FinalizeNonLinIteration( ModelPart &rModelPart, TSystemMatrixType &A, TSystemVectorType &Dx, TSystemVectorType &b) override { const ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); //if orthogonal subscales are computed if (CurrentProcessInfo[OSS_SWITCH] == 1.0) { this->LumpedProjection(rModelPart); //this->FullProjection(rModelPart); } } /// Start the iteration by providing a first approximation to the solution. void Predict( ModelPart& rModelPart, DofsArrayType& rDofSet, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) override { KRATOS_TRY const int n_nodes = rModelPart.NumberOfNodes(); const Vector& BDFcoefs = rModelPart.GetProcessInfo()[BDF_COEFFICIENTS]; #pragma omp parallel for for(int i_node = 0; i_node < n_nodes; ++i_node) { auto it_node = rModelPart.NodesBegin() + i_node; auto& rVel0 = it_node->FastGetSolutionStepValue(VELOCITY); const auto& rVel1 = it_node->FastGetSolutionStepValue(VELOCITY,1); const auto& rVel2 = it_node->FastGetSolutionStepValue(VELOCITY,2); auto& rAcceleration = it_node->FastGetSolutionStepValue(ACCELERATION); // Predict velocities if(!it_node->IsFixed(VELOCITY_X)) rVel0[0] = 2.00 * rVel1[0] - rVel2[0]; if(!it_node->IsFixed(VELOCITY_Y)) rVel0[1] = 2.00 * rVel1[1] - rVel2[1]; if(!it_node->IsFixed(VELOCITY_Z)) rVel0[2] = 2.00 * rVel1[2] - rVel2[2]; // Predict acceleration rAcceleration = BDFcoefs[0] * rVel0 + BDFcoefs[1] * rVel1 + BDFcoefs[2] * rVel2; } KRATOS_CATCH("") } /// Store the iteration results as solution step variables and update acceleration after a Newton-Raphson iteration. /** * @param rModelPart fluid ModelPart * @param rDofSet DofSet containing the Newton-Raphson system degrees of freedom. * @param A Newton-Raphson system matrix (unused) * @param Dx Newton-Raphson iteration solution * @param b Newton-Raphson right hand side (unused) */ void Update( ModelPart& rModelPart, DofsArrayType& rDofSet, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) override { KRATOS_TRY mpRotationTool->RotateVelocities(rModelPart); mpDofUpdater->UpdateDofs(rDofSet,Dx); mpRotationTool->RecoverVelocities(rModelPart); const Vector& BDFCoefs = rModelPart.GetProcessInfo()[BDF_COEFFICIENTS]; this->UpdateAcceleration(rModelPart,BDFCoefs); KRATOS_CATCH("") } void CalculateSystemContributions( Element& rCurrentElement, LocalSystemMatrixType& LHS_Contribution, LocalSystemVectorType& RHS_Contribution, Element::EquationIdVectorType& rEquationId, const ProcessInfo& rCurrentProcessInfo) override { KRATOS_TRY LocalSystemMatrixType Mass; LocalSystemMatrixType Damp; // Initialize element rCurrentElement.InitializeNonLinearIteration(rCurrentProcessInfo); // Get Equation Id rCurrentElement.EquationIdVector(rEquationId,rCurrentProcessInfo); // Get matrix contributions rCurrentElement.CalculateLocalSystem(LHS_Contribution,RHS_Contribution,rCurrentProcessInfo); rCurrentElement.CalculateMassMatrix(Mass,rCurrentProcessInfo); rCurrentElement.CalculateLocalVelocityContribution(Damp,RHS_Contribution,rCurrentProcessInfo); // Add the dynamic contributions to the local system using BDF2 coefficients this->CombineLHSContributions(LHS_Contribution,Mass,Damp,rCurrentProcessInfo); this->AddDynamicRHSContribution<Kratos::Element>(rCurrentElement,RHS_Contribution,Mass,rCurrentProcessInfo); // Apply slip condition mpRotationTool->Rotate(LHS_Contribution, RHS_Contribution, rCurrentElement.GetGeometry()); mpRotationTool->ApplySlipCondition(LHS_Contribution, RHS_Contribution, rCurrentElement.GetGeometry()); KRATOS_CATCH("") } void CalculateRHSContribution( Element& rCurrentElement, LocalSystemVectorType &RHS_Contribution, Element::EquationIdVectorType &rEquationId, const ProcessInfo &rCurrentProcessInfo) override { KRATOS_TRY LocalSystemMatrixType Mass; LocalSystemMatrixType Damp; // Initialize element rCurrentElement.InitializeNonLinearIteration(rCurrentProcessInfo); // Get Equation Id rCurrentElement.EquationIdVector(rEquationId,rCurrentProcessInfo); // Get matrix contributions rCurrentElement.CalculateRightHandSide(RHS_Contribution,rCurrentProcessInfo); rCurrentElement.CalculateMassMatrix(Mass,rCurrentProcessInfo); rCurrentElement.CalculateLocalVelocityContribution(Damp,RHS_Contribution,rCurrentProcessInfo); // Add the dynamic contributions to the local system using BDF2 coefficients this->AddDynamicRHSContribution<Kratos::Element>(rCurrentElement,RHS_Contribution,Mass,rCurrentProcessInfo); // Apply slip condition mpRotationTool->Rotate(RHS_Contribution, rCurrentElement.GetGeometry()); mpRotationTool->ApplySlipCondition(RHS_Contribution, rCurrentElement.GetGeometry()); KRATOS_CATCH("") } void CalculateSystemContributions( Condition& rCurrentCondition, LocalSystemMatrixType& LHS_Contribution, LocalSystemVectorType& RHS_Contribution, Element::EquationIdVectorType& rEquationId, const ProcessInfo& rCurrentProcessInfo) override { KRATOS_TRY LocalSystemMatrixType Mass; LocalSystemMatrixType Damp; // Initialize element rCurrentCondition.InitializeNonLinearIteration(rCurrentProcessInfo); // Get Equation Id rCurrentCondition.EquationIdVector(rEquationId,rCurrentProcessInfo); // Get matrix contributions rCurrentCondition.CalculateLocalSystem(LHS_Contribution,RHS_Contribution,rCurrentProcessInfo); rCurrentCondition.CalculateMassMatrix(Mass,rCurrentProcessInfo); rCurrentCondition.CalculateLocalVelocityContribution(Damp,RHS_Contribution,rCurrentProcessInfo); // Add the dynamic contributions to the local system using BDF2 coefficients this->CombineLHSContributions(LHS_Contribution,Mass,Damp,rCurrentProcessInfo); this->AddDynamicRHSContribution<Kratos::Condition>(rCurrentCondition,RHS_Contribution,Mass,rCurrentProcessInfo); // Apply slip condition mpRotationTool->Rotate(LHS_Contribution, RHS_Contribution, rCurrentCondition.GetGeometry()); mpRotationTool->ApplySlipCondition(LHS_Contribution, RHS_Contribution, rCurrentCondition.GetGeometry()); KRATOS_CATCH("") } void CalculateRHSContribution( Condition &rCurrentCondition, LocalSystemVectorType &RHS_Contribution, Element::EquationIdVectorType &rEquationId, const ProcessInfo &rCurrentProcessInfo) override { KRATOS_TRY LocalSystemMatrixType Mass; LocalSystemMatrixType Damp; // Initialize element rCurrentCondition.InitializeNonLinearIteration(rCurrentProcessInfo); // Get Equation Id rCurrentCondition.EquationIdVector(rEquationId,rCurrentProcessInfo); // Get matrix contributions rCurrentCondition.CalculateRightHandSide(RHS_Contribution,rCurrentProcessInfo); rCurrentCondition.CalculateMassMatrix(Mass,rCurrentProcessInfo); rCurrentCondition.CalculateLocalVelocityContribution(Damp,RHS_Contribution,rCurrentProcessInfo); // Add the dynamic contributions to the local system using BDF2 coefficients this->AddDynamicRHSContribution<Kratos::Condition>(rCurrentCondition,RHS_Contribution,Mass,rCurrentProcessInfo); // Apply slip condition mpRotationTool->Rotate(RHS_Contribution, rCurrentCondition.GetGeometry()); mpRotationTool->ApplySlipCondition(RHS_Contribution, rCurrentCondition.GetGeometry()); KRATOS_CATCH("") } /// Free memory allocated by this object. void Clear() override { this->mpDofUpdater->Clear(); } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. std::string Info() const override { std::stringstream buffer; buffer << "BDF2TurbulentScheme"; return buffer.str(); } /// Print information about this object. void PrintInfo(std::ostream& rOStream) const override { rOStream << Info(); } /// Print object's data. void PrintData(std::ostream& rOStream) const override {} ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ /// Calculate the coefficients for time iteration. /** * @param rCurrentProcessInfo ProcessInfo instance from the fluid ModelPart. Must contain DELTA_TIME and BDF_COEFFICIENTS variables. */ void SetTimeCoefficients(ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY; //calculate the BDF coefficients double Dt = rCurrentProcessInfo[DELTA_TIME]; double OldDt = rCurrentProcessInfo.GetPreviousTimeStepInfo(1)[DELTA_TIME]; double Rho = OldDt / Dt; double TimeCoeff = 1.0 / (Dt * Rho * Rho + Dt * Rho); Vector& BDFcoeffs = rCurrentProcessInfo[BDF_COEFFICIENTS]; BDFcoeffs.resize(3, false); BDFcoeffs[0] = TimeCoeff * (Rho * Rho + 2.0 * Rho); //coefficient for step n+1 (3/2Dt if Dt is constant) BDFcoeffs[1] = -TimeCoeff * (Rho * Rho + 2.0 * Rho + 1.0); //coefficient for step n (-4/2Dt if Dt is constant) BDFcoeffs[2] = TimeCoeff; //coefficient for step n-1 (1/2Dt if Dt is constant) KRATOS_CATCH(""); } /// Update Dof values after a Newton-Raphson iteration. /** * @param rDofSet Container for the Degrees of freedom in the system * @param Dx Solution of the linear system */ virtual void UpdateDofs( DofsArrayType& rDofSet, TSystemVectorType& Dx) { KRATOS_TRY const int n_dof = rDofSet.size(); #pragma omp parallel for for (int i_dof = 0; i_dof < n_dof; ++i_dof) { auto it_dof = rDofSet.begin() + i_dof; if (it_dof->IsFree()) { it_dof->GetSolutionStepValue() += TSparseSpace::GetValue(Dx, it_dof->EquationId()); } } KRATOS_CATCH("") } /// Update Dof values after a Newton-Raphson iteration /** * @param rModelPart fluid ModelPart * @param rBDFcoefs Time stepping coefficients for this iteration. */ void UpdateAcceleration( ModelPart& rModelPart, const Vector& rBDFcoefs) { KRATOS_TRY const double Coef0 = rBDFcoefs[0]; const double Coef1 = rBDFcoefs[1]; const double Coef2 = rBDFcoefs[2]; const int n_nodes = rModelPart.NumberOfNodes(); #pragma omp parallel for for (int i_node = 0; i_node < n_nodes; ++i_node) { auto it_node = rModelPart.NodesBegin() + i_node; const auto& rVel0 = it_node->FastGetSolutionStepValue(VELOCITY); const auto& rVel1 = it_node->FastGetSolutionStepValue(VELOCITY,1); const auto& rVel2 = it_node->FastGetSolutionStepValue(VELOCITY,2); auto& rAcceleration = it_node->FastGetSolutionStepValue(ACCELERATION); rAcceleration = Coef0 * rVel0 + Coef1 * rVel1 + Coef2 * rVel2; } KRATOS_CATCH("") } void CombineLHSContributions( LocalSystemMatrixType& rLHS, LocalSystemMatrixType& rMass, LocalSystemMatrixType& rDamp, const ProcessInfo& rCurrentProcessInfo) { const double Coef0 = rCurrentProcessInfo.GetValue(BDF_COEFFICIENTS)[0]; if (rMass.size1() != 0) noalias(rLHS) += Coef0 * rMass; if (rDamp.size1() != 0) noalias(rLHS) += rDamp; } template<class TObject> void AddDynamicRHSContribution( TObject& rObject, LocalSystemVectorType& rRHS, LocalSystemMatrixType& rMass, const ProcessInfo& rCurrentProcessInfo) { if (rMass.size1() != 0) { const Vector& rCoefs = rCurrentProcessInfo.GetValue(BDF_COEFFICIENTS); LocalSystemVectorType Acc; rObject.GetFirstDerivativesVector(Acc); Acc *= rCoefs[0]; for(unsigned int n = 1; n < 3; ++n) { LocalSystemVectorType rVel; rObject.GetFirstDerivativesVector(rVel,n); noalias(Acc) += rCoefs[n] * rVel; } noalias(rRHS) -= prod(rMass,Acc); } } void FullProjection(ModelPart& rModelPart) { const ProcessInfo& rCurrentProcessInfo = rModelPart.GetProcessInfo(); // Initialize containers const int n_nodes = rModelPart.NumberOfNodes(); const int n_elems = rModelPart.NumberOfElements(); const array_1d<double,3> zero_vect = ZeroVector(3); #pragma omp parallel for firstprivate(zero_vect) for (int i_node = 0; i_node < n_nodes; ++i_node) { auto ind = rModelPart.NodesBegin() + i_node; noalias(ind->FastGetSolutionStepValue(ADVPROJ)) = zero_vect; // "x" ind->FastGetSolutionStepValue(DIVPROJ) = 0.0; // "x" ind->FastGetSolutionStepValue(NODAL_AREA) = 0.0; // "Ml" } // Newton-Raphson parameters const double RelTol = 1e-4 * rModelPart.NumberOfNodes(); const double AbsTol = 1e-6 * rModelPart.NumberOfNodes(); const unsigned int MaxIter = 100; // iteration variables unsigned int iter = 0; array_1d<double,3> dMomProj = zero_vect; double dMassProj = 0.0; double RelMomErr = 1000.0 * RelTol; double RelMassErr = 1000.0 * RelTol; double AbsMomErr = 1000.0 * AbsTol; double AbsMassErr = 1000.0 * AbsTol; while( ( (AbsMomErr > AbsTol && RelMomErr > RelTol) || (AbsMassErr > AbsTol && RelMassErr > RelTol) ) && iter < MaxIter) { // Reinitialize RHS #pragma omp parallel for firstprivate(zero_vect) for (int i_node = 0; i_node < n_nodes; ++i_node) { auto ind = rModelPart.NodesBegin() + i_node; noalias(ind->GetValue(ADVPROJ)) = zero_vect; // "b" ind->GetValue(DIVPROJ) = 0.0; // "b" ind->FastGetSolutionStepValue(NODAL_AREA) = 0.0; // Reset because Calculate will overwrite it } // Reinitialize errors RelMomErr = 0.0; RelMassErr = 0.0; AbsMomErr = 0.0; AbsMassErr = 0.0; // Compute new values array_1d<double, 3 > output; #pragma omp parallel for private(output) for (int i_elem = 0; i_elem < n_elems; ++i_elem) { auto it_elem = rModelPart.ElementsBegin() + i_elem; it_elem->Calculate(SUBSCALE_VELOCITY, output, rCurrentProcessInfo); } rModelPart.GetCommunicator().AssembleCurrentData(NODAL_AREA); rModelPart.GetCommunicator().AssembleCurrentData(DIVPROJ); rModelPart.GetCommunicator().AssembleCurrentData(ADVPROJ); rModelPart.GetCommunicator().AssembleNonHistoricalData(DIVPROJ); rModelPart.GetCommunicator().AssembleNonHistoricalData(ADVPROJ); // Update iteration variables #pragma omp parallel for for (int i_node = 0; i_node < n_nodes; ++i_node) { auto ind = rModelPart.NodesBegin() + i_node; const double Area = ind->FastGetSolutionStepValue(NODAL_AREA); // Ml dx = b - Mc x dMomProj = ind->GetValue(ADVPROJ) / Area; dMassProj = ind->GetValue(DIVPROJ) / Area; RelMomErr += sqrt( dMomProj[0]*dMomProj[0] + dMomProj[1]*dMomProj[1] + dMomProj[2]*dMomProj[2]); RelMassErr += fabs(dMassProj); auto& rMomRHS = ind->FastGetSolutionStepValue(ADVPROJ); double& rMassRHS = ind->FastGetSolutionStepValue(DIVPROJ); rMomRHS += dMomProj; rMassRHS += dMassProj; AbsMomErr += sqrt( rMomRHS[0]*rMomRHS[0] + rMomRHS[1]*rMomRHS[1] + rMomRHS[2]*rMomRHS[2]); AbsMassErr += fabs(rMassRHS); } if(AbsMomErr > 1e-10) RelMomErr /= AbsMomErr; else // If residual is close to zero, force absolute convergence to avoid division by zero errors RelMomErr = 1000.0; if(AbsMassErr > 1e-10) RelMassErr /= AbsMassErr; else RelMassErr = 1000.0; iter++; } KRATOS_INFO("BDF2TurbulentScheme") << "Performed OSS Projection in " << iter << " iterations" << std::endl; } void LumpedProjection(ModelPart& rModelPart) { const int n_nodes = rModelPart.NumberOfNodes(); const int n_elems = rModelPart.NumberOfElements(); const ProcessInfo& rCurrentProcessInfo = rModelPart.GetProcessInfo(); const array_1d<double,3> zero_vect = ZeroVector(3); #pragma omp parallel for firstprivate(zero_vect) for (int i_node = 0; i_node < n_nodes; ++i_node) { auto itNode = rModelPart.NodesBegin() + i_node; noalias(itNode->FastGetSolutionStepValue(ADVPROJ)) = zero_vect; itNode->FastGetSolutionStepValue(DIVPROJ) = 0.0; itNode->FastGetSolutionStepValue(NODAL_AREA) = 0.0; } array_1d<double, 3 > Out; #pragma omp parallel for private(Out) for (int i_elem = 0; i_elem < n_elems; ++i_elem) { auto itElem = rModelPart.ElementsBegin() + i_elem; itElem->Calculate(ADVPROJ, Out, rCurrentProcessInfo); } rModelPart.GetCommunicator().AssembleCurrentData(NODAL_AREA); rModelPart.GetCommunicator().AssembleCurrentData(DIVPROJ); rModelPart.GetCommunicator().AssembleCurrentData(ADVPROJ); // Correction for periodic conditions if (mrPeriodicIdVar.Key() != 0) { this->PeriodicConditionProjectionCorrection(rModelPart); } const double zero_tol = 1.0e-12; #pragma omp parallel for firstprivate(zero_tol) for (int i_node = 0; i_node < n_nodes; ++i_node){ auto iNode = rModelPart.NodesBegin() + i_node; if (iNode->FastGetSolutionStepValue(NODAL_AREA) < zero_tol) { iNode->FastGetSolutionStepValue(NODAL_AREA) = 1.0; } const double Area = iNode->FastGetSolutionStepValue(NODAL_AREA); iNode->FastGetSolutionStepValue(ADVPROJ) /= Area; iNode->FastGetSolutionStepValue(DIVPROJ) /= Area; } KRATOS_INFO("BDF2TurbulentScheme") << "Computing OSS projections" << std::endl; } /** On periodic boundaries, the nodal area and the values to project need to take into account contributions from elements on * both sides of the boundary. This is done using the conditions and the non-historical nodal data containers as follows:\n * 1- The partition that owns the PeriodicCondition adds the values on both nodes to their non-historical containers.\n * 2- The non-historical containers are added across processes, communicating the right value from the condition owner to all partitions.\n * 3- The value on all periodic nodes is replaced by the one received in step 2. */ void PeriodicConditionProjectionCorrection(ModelPart& rModelPart) { const int num_nodes = rModelPart.NumberOfNodes(); const int num_conditions = rModelPart.NumberOfConditions(); #pragma omp parallel for for (int i = 0; i < num_nodes; i++) { auto it_node = rModelPart.NodesBegin() + i; it_node->SetValue(NODAL_AREA,0.0); it_node->SetValue(ADVPROJ,ZeroVector(3)); it_node->SetValue(DIVPROJ,0.0); } #pragma omp parallel for for (int i = 0; i < num_conditions; i++) { auto it_cond = rModelPart.ConditionsBegin() + i; if(it_cond->Is(PERIODIC)) { this->AssemblePeriodicContributionToProjections(it_cond->GetGeometry()); } } rModelPart.GetCommunicator().AssembleNonHistoricalData(NODAL_AREA); rModelPart.GetCommunicator().AssembleNonHistoricalData(ADVPROJ); rModelPart.GetCommunicator().AssembleNonHistoricalData(DIVPROJ); #pragma omp parallel for for (int i = 0; i < num_nodes; i++) { auto it_node = rModelPart.NodesBegin() + i; this->CorrectContributionsOnPeriodicNode(*it_node); } } void AssemblePeriodicContributionToProjections(Geometry< Node<3> >& rGeometry) { unsigned int nodes_in_cond = rGeometry.PointsNumber(); double nodal_area = 0.0; array_1d<double,3> momentum_projection = ZeroVector(3); double mass_projection = 0.0; for ( unsigned int i = 0; i < nodes_in_cond; i++ ) { auto& r_node = rGeometry[i]; nodal_area += r_node.FastGetSolutionStepValue(NODAL_AREA); noalias(momentum_projection) += r_node.FastGetSolutionStepValue(ADVPROJ); mass_projection += r_node.FastGetSolutionStepValue(DIVPROJ); } for ( unsigned int i = 0; i < nodes_in_cond; i++ ) { auto& r_node = rGeometry[i]; /* Note that this loop is expected to be threadsafe in normal conditions, * since each node should belong to a single periodic link. However, I am * setting the locks for openmp in case that we try more complicated things * in the future (like having different periodic conditions for different * coordinate directions). */ r_node.SetLock(); r_node.GetValue(NODAL_AREA) = nodal_area; noalias(r_node.GetValue(ADVPROJ)) = momentum_projection; r_node.GetValue(DIVPROJ) = mass_projection; r_node.UnSetLock(); } } void CorrectContributionsOnPeriodicNode(Node<3>& rNode) { //TODO: This needs to be done in another manner as soon as we start using non-historical NODAL_AREA if (rNode.GetValue(NODAL_AREA) != 0.0) // Only periodic nodes will have a non-historical NODAL_AREA set. { rNode.FastGetSolutionStepValue(NODAL_AREA) = rNode.GetValue(NODAL_AREA); noalias(rNode.FastGetSolutionStepValue(ADVPROJ)) = rNode.GetValue(ADVPROJ); rNode.FastGetSolutionStepValue(DIVPROJ) = rNode.GetValue(DIVPROJ); } } ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ /// Pointer to a turbulence model Process::Pointer mpTurbulenceModel = nullptr; RotationToolPointerType mpRotationTool = nullptr; typename TSparseSpace::DofUpdaterPointerType mpDofUpdater = TSparseSpace::CreateDofUpdater(); const Kratos::Variable<int>& mrPeriodicIdVar; // ///@} // ///@name Serialization // ///@{ // // friend class Serializer; // // virtual void save(Serializer& rSerializer) const // { // KRATOS_SERIALIZE_SAVE_BASE_CLASS(rSerializer, BaseType ); // rSerializer.save("mpTurbulenceModel",mpTurbulenceModel); // } // // virtual void load(Serializer& rSerializer) // { // KRATOS_SERIALIZE_LOAD_BASE_CLASS(rSerializer, BaseType ); // rSerializer.load("mpTurbulenceModel",mpTurbulenceModel); // } ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ /// Assignment operator. BDF2TurbulentScheme & operator=(BDF2TurbulentScheme const& rOther) {} /// Copy constructor. BDF2TurbulentScheme(BDF2TurbulentScheme const& rOther) {} ///@} }; // Class BDF2TurbulentScheme ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ /// input stream function template<class TSparseSpace,class TDenseSpace> inline std::istream& operator >>(std::istream& rIStream,BDF2TurbulentScheme<TSparseSpace,TDenseSpace>& rThis) { return rIStream; } /// output stream function template<class TSparseSpace,class TDenseSpace> inline std::ostream& operator <<(std::ostream& rOStream,const BDF2TurbulentScheme<TSparseSpace,TDenseSpace>& rThis) { rThis.PrintInfo(rOStream); rOStream << std::endl; rThis.PrintData(rOStream); return rOStream; } ///@} ///@} addtogroup block } // namespace Kratos. #endif // KRATOS_BDF2_TURBULENT_SCHEME_H_INCLUDED defined
laplace2d.c
/* * Copyright 2012 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 <math.h> #include <string.h> #include "timer.h" #include <stdio.h> #ifdef _OPENACCM #include <openacc.h> #endif #ifndef VERIFICATION #define VERIFICATION 0 #endif #ifndef NN #define NN 1024 #endif #ifdef _OPENARC_ #if NN == 1024 #pragma openarc #define NN 1024 #elif NN == 2048 #pragma openarc #define NN 2048 #elif NN == 3072 #pragma openarc #define NN 3072 #elif NN == 3072 #pragma openarc #define NN 3072 #elif NN == 4096 #pragma openarc #define NN 4096 #endif #endif #if VERIFICATION == 1 double A_CPU[NN][NN]; double Anew_CPU[NN][NN]; #endif int main(int argc, char** argv) { int n = NN; int m = n; int iter_max = 10; double tol = 1.0e-6; double error = 1.0; int i, j; int iter = 0; double runtime; double (*A)[NN] = (double (*)[NN])malloc(sizeof(double)*n*n); double (*Anew)[NN] = (double (*)[NN])malloc(sizeof(double)*n*n); memset(A, 0, n * m * sizeof(double)); memset(Anew, 0, n * m * sizeof(double)); #if VERIFICATION == 1 memset(A_CPU, 0, n * m * sizeof(double)); memset(Anew_CPU, 0, n * m * sizeof(double)); #endif for (j = 0; j < n; j++) { A[j][0] = 1.0; Anew[j][0] = 1.0; #if VERIFICATION == 1 A_CPU[j][0] = 1.0; Anew_CPU[j][0] = 1.0; #endif } printf("Jacobi relaxation Calculation: %d x %d mesh\n", n, m); StartTimer(); #pragma aspen enter modelregion #ifdef _OPENACCM acc_init(acc_device_default); #endif //aspen_param_whilecnt = 1000 for NN = NN = 4096 //aspen_param_whilecnt = 1000 for NN = NN = 8192 #pragma aspen declare param(aspen_param_whilecnt:10) #pragma aspen control loop(aspen_param_whilecnt) #pragma acc data copy(A[0:n][0:n]), create(Anew[0:n][0:n]) while ( error > tol && iter < iter_max ) { error = 0.0; //#pragma omp parallel for shared(m, n, Anew, A) #pragma acc parallel num_gangs(16) num_workers(32) reduction(max:error) private(j) { double lerror = 0.0; #pragma acc loop gang for( j = 1; j < n-1; j++) { #pragma acc loop worker reduction(max:lerror) for( i = 1; i < m-1; i++ ) { Anew[j][i] = 0.25 * ( A[j][i+1] + A[j][i-1] + A[j-1][i] + A[j+1][i]); lerror = fmax( lerror, fabs(Anew[j][i] - A[j][i])); } //[DEBUG] intentionally ignore to flatten nested map constructs. #pragma aspen control ignore error = fmax(error, lerror); } } //#pragma omp parallel for shared(m, n, Anew, A) #pragma acc kernels loop gang for( j = 1; j < n-1; j++) { #pragma acc loop worker for( i = 1; i < m-1; i++ ) { A[j][i] = Anew[j][i]; } } if(iter % 100 == 0) printf("%5d, %0.6f\n", iter, error); iter++; } #ifdef _OPENACCM acc_shutdown(acc_device_default); #endif #pragma aspen exit modelregion printf("iter: %d\n", iter); runtime = GetTimer(); printf("Accelerator Elapsed time %f s\n", runtime / 1000); #if VERIFICATION == 1 { StartTimer(); error = 1.0; iter = 0; while ( error > tol && iter < iter_max ) { error = 0.0; { #pragma omp parallel for private(j, i) for( j = 1; j < n-1; j++) { double lerror = 0.0; for( i = 1; i < m-1; i++ ) { Anew_CPU[j][i] = 0.25 * ( A_CPU[j][i+1] + A_CPU[j][i-1] + A_CPU[j-1][i] + A_CPU[j+1][i]); lerror = fmax( lerror, fabs(Anew_CPU[j][i] - A_CPU[j][i])); } #pragma omp critical error = fmax(error,lerror); } } #pragma omp parallel for private(j, i) for( j = 1; j < n-1; j++) { for( i = 1; i < m-1; i++ ) { A_CPU[j][i] = Anew_CPU[j][i]; } } if(iter % 100 == 0) printf("%5d, %0.6f\n", iter, error); iter++; } runtime = GetTimer(); printf("CPU Elapsed time %f s\n", runtime / 1000); { double cpu_sum = 0.0f; double gpu_sum = 0.0f; double rel_err = 0.0f; for (i = 1; i < m-1; i++) { cpu_sum += A_CPU[i][i]*A_CPU[i][i]; gpu_sum += A[i][i]*A[i][i]; } cpu_sum = sqrt(cpu_sum); gpu_sum = sqrt(gpu_sum); rel_err = (cpu_sum-gpu_sum)/cpu_sum; if(rel_err < 1e-6) { printf("Verification Successful err = %e\n", rel_err); } else { printf("Verification Fail err = %e\n", rel_err); } } } #endif }
a.33.2.c
/* { dg-do compile } */ #include <stdio.h> #include <stdlib.h> float read_next () { float *tmp; float return_val; #pragma omp single copyprivate(tmp) { tmp = (float *) malloc (sizeof (float)); } /* copies the pointer only */ #pragma omp master { scanf ("%f", tmp); } #pragma omp barrier return_val = *tmp; #pragma omp barrier #pragma omp single nowait { free (tmp); } return return_val; }
omp3-1-1.c
#include<stdio.h> #ifndef N #define N 5000 #endif #define M 1000000000 int a[N][N], b[N][N]; int main() { int i, j, sum; #pragma omp parallel sections { #pragma omp section for (i = 0; i < N; i++) for (j = 0; j < N; j++) a[i][j] = i + j; #pragma omp section for (i = 0; i < N; i++) for (j = 0; j < N; j++) b[i][j] = i - j; } sum = 0; for (i = 0; i < N; i++) for (j = 0; j < N; j++) sum += a[i][j]; printf("%d\n", sum); sum = 0; for (i = 0; i < N; i++) for (j = 0; j < N; j++) sum += b[i][j]; printf("%d\n", sum); return 0; }
GB_unaryop__identity_int16_bool.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__identity_int16_bool // op(A') function: GB_tran__identity_int16_bool // C type: int16_t // A type: bool // cast: int16_t cij = (int16_t) aij // unaryop: cij = aij #define GB_ATYPE \ bool #define GB_CTYPE \ int16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ bool aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, aij) \ int16_t z = (int16_t) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT16 || GxB_NO_BOOL) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_int16_bool ( int16_t *Cx, // Cx and Ax may be aliased bool *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__identity_int16_bool ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
vlisa_twosample.c
/* ** Implementation of LISA algorithm ** for statistical inference of fMRI images ** ** 2nd level inference, two-sample ttest, paired t-test ** ** G.Lohmann, MPI-KYB, 2018 */ #include <viaio/Vlib.h> #include <viaio/file.h> #include <viaio/mu.h> #include <viaio/option.h> #include <viaio/os.h> #include <viaio/VImage.h> #include <via/via.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_histogram.h> #include <gsl/gsl_histogram2d.h> #include <math.h> #include <stdio.h> #include <string.h> #ifdef _OPENMP #include <omp.h> #endif /*_OPENMP*/ #define ABS(x) ((x) > 0 ? (x) : -(x)) #define MIN(x,y) ((x) < (y) ? (x) : (y)) #define MAX(x,y) ((x) > (y) ? (x) : (y)) extern double ttest2(double *data1,double *data2,int n1,int n2); extern double xtest2(double *data1,double *data2,int n); extern double paired_ttest(double *data1,double *data2,int n); extern double welchtest(double *data1,double *data2,int n1,int n2); extern void VIsolatedVoxels(VImage src,float threshold); extern void VHistogram(gsl_histogram *histogram,VString filename); extern void VCheckImage(VImage src); extern void FDR(VImage src,VImage dest,gsl_histogram *nullhist,gsl_histogram *realhist,double); extern double ttest1(double *data1,int n); extern void ImageStats(VImage src,double *,double *,double *hmin,double *hmax); extern void VBilateralFilter(VImage src,VImage dest,int radius,double var1,double var2,int); extern double VImageVar(VImage src); extern void VGetHistRange(VImage src,double *hmin,double *hmax); extern void VZScale(VImage src,float mode,float stddev); extern float VGetMode(VImage src); extern void HistoUpdate(VImage,gsl_histogram *); /* generate permutation table */ int **genperm(long seed,int n1,int n2,int numperm,int testtype) { int i,j,n=n1+n2; int **table = (int **) VCalloc(numperm,sizeof(int *)); int *base = (int *) VCalloc(n,sizeof(int)); for (j=0; j<n; j++) base[j] = j; gsl_rng_env_setup(); const gsl_rng_type *T = gsl_rng_default; gsl_rng *rx = gsl_rng_alloc(T); gsl_rng_set(rx,(unsigned long int)seed); /* for each permutation: */ for (i = 0; i < numperm; i++) { /* unpaired test */ if (testtype == 0 || testtype == 2) { table[i] = (int *) VCalloc(n,sizeof(int)); gsl_ran_shuffle (rx,base,n,sizeof(int)); for (j=0; j<n; j++) { table[i][j] = base[j]; } } /* paired test */ if (testtype == 1) { table[i] = (int *) VCalloc(n1,sizeof(int)); for (j=0; j<n1; j++) { table[i][j] = 0; if (gsl_ran_bernoulli (rx,(double)0.5) == 1) table[i][j] = 1; } } } VFree(base); return table; } void TTest(VImage *src1,VImage *src2,int *permtable,VImage dest,int n1,int n2,int testtype) { int i,b,r,c,nslices,nrows,ncols; double u=0,v=0,z=0; int k1=0,k2=0,k=0; int n = n1+n2; int min1 = n1-2; int min2 = n2-2; gsl_set_error_handler_off(); nslices = VImageNBands(src1[0]); nrows = VImageNRows(src1[0]); ncols = VImageNColumns(src1[0]); VFillImage(dest,VAllBands,0); /* alloc */ double *data1 = (double *) VCalloc(n1,sizeof(double)); double *data2 = (double *) VCalloc(n2,sizeof(double)); double *data = (double *) VCalloc(n,sizeof(double)); /* for every voxel */ for (b=0; b<nslices; b++) { for (r=0; r<nrows; r++) { for (c=0; c<ncols; c++) { /* unpaired test */ if (testtype == 0 || testtype == 2) { k = 0; for (i=0; i<n1; i++) { data[k++] = VPixel(src1[i],b,r,c,VFloat); } for (i=0; i<n2; i++) { data[k++] = VPixel(src2[i],b,r,c,VFloat); } k1 = 0; for (i=0; i<n1; i++) { u = data[permtable[i]]; if (fabs(u) > 0) { data1[k1++] = u; } } if (k1 < min1) continue; k2 = 0; for (i=0; i<n2; i++) { u = data[permtable[i+n1]]; if (fabs(u) > 0) { data2[k2++] = u; } } if (k2 < min2) continue; } /* paired test */ if (testtype == 1) { k=0; for (i=0; i<n1; i++) { if (permtable[i] == 0) { /* no flip */ u = VPixel(src1[i],b,r,c,VFloat); v = VPixel(src2[i],b,r,c,VFloat); } else { /* flip */ u = VPixel(src2[i],b,r,c,VFloat); v = VPixel(src1[i],b,r,c,VFloat); } if (fabs(u) > 0 && fabs(v) > 0) { data1[k] = u; data2[k] = v; k++; } } if (k < min1) continue; } /* t-test */ z = 0; switch(testtype) { case 0 : z = ttest2(data1,data2,k1,k2); /* pooled variance */ break; case 1 : z = paired_ttest(data1,data2,k); /* paired */ break; case 2 : z = welchtest(data1,data2,k1,k2); /* unequal variance */ break; default: VError(" unknown testtype"); } VPixel(dest,b,r,c,VFloat) = z; } } } VFree(data); VFree(data1); VFree(data2); } VDictEntry TSTDict[] = { { "pooled", 0, 0,0,0,0 }, { "paired", 1, 0,0,0,0 }, { "welch", 2, 0,0,0,0 }, { NULL, 0,0,0,0,0 } }; int main (int argc, char *argv[]) { static VArgVector in_files1; static VArgVector in_files2; static VString out_filename=""; static VString mask_filename=""; static VFloat alpha = 0.05; static VShort testtype = 0; static VShort radius = 2; static VFloat rvar = 2.0; static VFloat svar = 2.0; static VShort numiter = 2; static VShort numperm = 5000; static VLong seed = 99402622; static VBoolean centering = FALSE; static VBoolean cleanup = TRUE; static VShort nproc = 0; static VOptionDescRec options[] = { {"in1", VStringRepn, 0, & in_files1, VRequiredOpt, NULL,"Input files 1" }, {"in2", VStringRepn, 0, & in_files2, VRequiredOpt, NULL,"Input files 2" }, {"out", VStringRepn, 1, & out_filename, VRequiredOpt, NULL,"Output file" }, {"alpha",VFloatRepn,1,(VPointer) &alpha,VOptionalOpt,NULL,"FDR significance level"}, {"perm",VShortRepn,1,(VPointer) &numperm,VOptionalOpt,NULL,"Number of permutations"}, {"mask", VStringRepn, 1, (VPointer) &mask_filename, VRequiredOpt, NULL, "Mask"}, {"test",VShortRepn,1,(VPointer) &testtype,VOptionalOpt,TSTDict,"type of test"}, {"seed",VLongRepn,1,(VPointer) &seed,VOptionalOpt,NULL,"Seed for random number generation"}, {"radius",VShortRepn,1,(VPointer) &radius,VOptionalOpt,NULL,"Bilateral parameter (radius in voxels)"}, {"rvar",VFloatRepn,1,(VPointer) &rvar,VOptionalOpt,NULL,"Bilateral parameter (radiometric)"}, {"svar",VFloatRepn,1,(VPointer) &svar,VOptionalOpt,NULL,"Bilateral parameter (spatial)"}, {"filteriterations",VShortRepn,1,(VPointer) &numiter,VOptionalOpt,NULL,"Bilateral parameter (number of iterations)"}, {"cleanup",VBooleanRepn,1,(VPointer) &cleanup,VOptionalOpt,NULL,"Whether to apply cleanup"}, {"j",VShortRepn,1,(VPointer) &nproc,VOptionalOpt,NULL,"Number of processors to use, '0' to use all"}, }; FILE *fp=NULL; VString in_filename,str1,str2; VAttrList list1=NULL,list2=NULL,out_list=NULL,geolist=NULL; int i,nimages1=0,nimages2=0,npix=0; char *prg_name=GetLipsiaName("vlisa_twosample"); fprintf (stderr, "%s\n", prg_name); /* parse command line */ if (! VParseCommand (VNumber (options), options, & argc, argv)) { VReportUsage (argv[0], VNumber (options), options, NULL); exit (EXIT_FAILURE); } if (argc > 1) { VReportBadArgs (argc, argv); exit (EXIT_FAILURE); } /* omp-stuff */ #ifdef _OPENMP int num_procs=omp_get_num_procs(); if (nproc > 0 && nproc < num_procs) num_procs = nproc; fprintf(stderr," using %d cores\n",(int)num_procs); omp_set_num_threads(num_procs); #endif /* _OPENMP */ /* read mask */ VImage mask = VReadImageFile(mask_filename); if (mask==NULL) VError("Error reading mask file %s",mask_filename); /* number of inputs */ nimages1 = in_files1.number; nimages2 = in_files2.number; fprintf(stderr," nimages= %d %d\n",nimages1,nimages2); /* images 1 */ VImage *src1 = (VImage *) VCalloc(nimages1,sizeof(VImage)); for (i = 0; i < nimages1; i++) { in_filename = ((VString *) in_files1.vector)[i]; list1 = VReadAttrList(in_filename,0L,TRUE,FALSE); VMaskMinval(list1,mask,0.0); src1[i] = VReadImage(list1); if (src1[i] == NULL) VError(" no input image found"); if (VPixelRepn(src1[i]) != VFloatRepn) VError(" input pixel repn must be float"); if (i == 0) npix = VImageNPixels(src1[i]); else if (npix != VImageNPixels(src1[i])) VError(" inconsistent image dimensions"); /* use geometry info from 1st file */ if (geolist == NULL) geolist = VGetGeoInfo(list1); } /* images 2 */ VImage *src2 = (VImage *) VCalloc(nimages2,sizeof(VImage)); for (i = 0; i < nimages2; i++) { in_filename = ((VString *) in_files2.vector)[i]; list2 = VReadAttrList(in_filename,0L,TRUE,FALSE); VMaskMinval(list2,mask,0.0); src2[i] = VReadImage(list2); if (src2[i] == NULL) VError(" no input image found"); if (VPixelRepn(src2[i]) != VFloatRepn) VError(" input pixel repn must be float"); if (i == 0) npix = VImageNPixels(src2[i]); else if (npix != VImageNPixels(src2[i])) VError(" inconsistent image dimensions"); } if (testtype == 1) { /* print filenames to terminal */ for (i = 0; i < nimages1; i++) { str1 = ((VString *) in_files1.vector)[i]; str2 = ((VString *) in_files2.vector)[i]; fprintf(stderr," %3d: %s %s\n",i,str1,str2); } } else { fprintf(stderr," Group 1:\n"); for (i = 0; i < nimages1; i++) { str1 = ((VString *) in_files1.vector)[i]; fprintf(stderr," %3d: %s\n",i,str1); } fprintf(stderr,"\n Group 2:\n"); for (i = 0; i < nimages2; i++) { str2 = ((VString *) in_files2.vector)[i]; fprintf(stderr," %3d: %s\n",i,str2); } } /* random permutations */ size_t n = nimages1+nimages2; int nperm=0; int **permtable = genperm((long)seed,(int)nimages1,(int)nimages2,(int)numperm,(int)testtype); int *nopermtable = (int *) VCalloc(n,sizeof(int)); for (i=0; i<n; i++) nopermtable[i]=i; if (testtype == 1) for (i=0; i<n; i++) nopermtable[i]=0; /* estimate null variance based on first 30 permutations */ double hmin=0,hmax=0; float stddev=1.0; if (numperm > 0) { int tstperm = 30; if (tstperm > numperm) tstperm = numperm; double varsum=0,nx=0; #pragma omp parallel for shared(src1,permtable) schedule(dynamic) for (nperm = 0; nperm < tstperm; nperm++) { VImage zmap = VCreateImageLike(src1[0]); TTest(src1,src2,permtable[nperm],zmap,nimages1,nimages2,(int)testtype); #pragma omp critical { varsum += VImageVar(zmap); nx++; } VDestroyImage(zmap); } double meanvar = varsum/nx; stddev = sqrt(meanvar); } /* no permutation */ VImage dst1 = VCreateImageLike (src1[0]); VImage zmap1 = VCreateImageLike(src1[0]); VFillImage(zmap1,VAllBands,0); TTest(src1,src2,nopermtable,zmap1,nimages1,nimages2,(int)testtype); if (numperm == 0) { double z = VImageVar(zmap1); stddev = (float)(sqrt(z)); /* update stddev */ } float mode=0; if (centering) mode = VGetMode(zmap1); if (numperm > 0) VZScale(zmap1,mode,stddev); VBilateralFilter(zmap1,dst1,(int)radius,(double)rvar,(double)svar,(int)numiter); /* ini histograms */ VGetHistRange(dst1,&hmin,&hmax); size_t nbins = 20000; gsl_histogram *hist0 = gsl_histogram_alloc (nbins); gsl_histogram_set_ranges_uniform (hist0,hmin,hmax); gsl_histogram *histz = gsl_histogram_alloc (nbins); gsl_histogram_set_ranges_uniform (histz,hmin,hmax); HistoUpdate(dst1,histz); #pragma omp parallel for shared(src1,src2,permtable) schedule(dynamic) for (nperm = 0; nperm < numperm; nperm++) { if (nperm%20 == 0) fprintf(stderr," perm %4d of %d\r",nperm,(int)numperm); VImage zmap = VCreateImageLike(src1[0]); VImage dst = VCreateImageLike (zmap); TTest(src1,src2,permtable[nperm],zmap,nimages1,nimages2,(int)testtype); float mode=0; if (centering) mode = VGetMode(zmap); VZScale(zmap,mode,stddev); VBilateralFilter(zmap,dst,(int)radius,(double)rvar,(double)svar,(int)numiter); #pragma omp critical { HistoUpdate(dst,hist0); } VDestroyImage(dst); VDestroyImage(zmap); } /* apply fdr */ VImage fdrimage = VCopyImage (dst1,NULL,VAllBands); if (numperm > 0) { FDR(dst1,fdrimage,hist0,histz,(double)alpha); if (cleanup && alpha < 1.0) { VIsolatedVoxels(fdrimage,(float)(1.0-alpha)); } } /* write output to disk */ out_list = VCreateAttrList (); VHistory(VNumber(options),options,prg_name,&list1,&out_list); VSetGeoInfo(geolist,out_list); VAppendAttr (out_list,"image",NULL,VImageRepn,fdrimage); fp = VOpenOutputFile (out_filename, TRUE); if (! VWriteFile (fp, out_list)) exit (1); fclose(fp); fprintf (stderr, "\n"); fprintf (stderr, "%s: done.\n", argv[0]); exit(0); }
opencl_office2007_fmt_plug.c
/* MS Office 2007 cracker patch for JtR. Hacked together during March of 2012 by * Dhiru Kholia <dhiru.kholia at gmail.com> * * OpenCL support by magnum. * * This software is Copyright (c) 2012, Dhiru Kholia <dhiru.kholia at gmail.com> * and Copyright (c) 2012, magnum and it is hereby released to the general public * under the following terms: * Redistribution and use in source and binary forms, with or without * modification, are permitted. */ #ifdef HAVE_OPENCL #if FMT_EXTERNS_H extern struct fmt_main fmt_opencl_office2007; #elif FMT_REGISTERS_H john_register_one(&fmt_opencl_office2007); #else #include "sha.h" #include "aes.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <errno.h> #include "arch.h" #include "misc.h" #include "common.h" #include "formats.h" #include "params.h" #include "options.h" #include "unicode.h" #include "common-opencl.h" #include "office_common.h" #include "config.h" #define PLAINTEXT_LENGTH 51 #define UNICODE_LENGTH 104 /* In octets, including 0x80 */ #define FORMAT_LABEL "office2007-opencl" #define FORMAT_NAME "MS Office 2007" #define OCL_ALGORITHM_NAME "SHA1 OpenCL" #define CPU_ALGORITHM_NAME " AES" #define ALGORITHM_NAME OCL_ALGORITHM_NAME CPU_ALGORITHM_NAME #define BENCHMARK_COMMENT " (50,000 iterations)" #define BENCHMARK_LENGTH -1 #define BINARY_SIZE 16 #define BINARY_ALIGN 4 #define SALT_LENGTH 16 #define SALT_SIZE sizeof(*cur_salt) #define SALT_ALIGN 1 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 static struct fmt_tests tests[] = { {"$office$*2007*20*128*16*8b2c9e8c878844fc842012273be4bea8*aa862168b80d8c45c852696a8bb499eb*a413507fabe2d87606595f987f679ff4b5b4c2cd", "Password"}, /* 2007-Default_myhovercraftisfullofeels_.docx */ {"$office$*2007*20*128*16*91f095a1fd02595359fe3938fa9236fd*e22668eb1347957987175079e980990f*659f50b9062d36999bf3d0911068c93268ae1d86", "myhovercraftisfullofeels"}, /* 2007-Default_myhovercraftisfullofeels_.dotx */ {"$office$*2007*20*128*16*56ea65016fbb4eac14a6770b2dbe7e99*8cf82ce1b62f01fd3b2c7666a2313302*21443fe938177e648c482da72212a8848c2e9c80", "myhovercraftisfullofeels"}, /* 2007-Default_myhovercraftisfullofeels_.xlsb */ {"$office$*2007*20*128*16*fbd4cc5dab9b8e341778ddcde9eca740*3a040a9cef3d3675009b22f99718e39c*48053b27e95fa53b3597d48ca4ad41eec382e0c8", "myhovercraftisfullofeels"}, /* 2007-Default_myhovercraftisfullofeels_.xlsm */ {"$office$*2007*20*128*16*fbd4cc5dab9b8e341778ddcde9eca740*92bb2ef34ca662ca8a26c8e2105b05c0*0261ba08cd36a324aa1a70b3908a24e7b5a89dd6", "myhovercraftisfullofeels"}, /* 2007-Default_myhovercraftisfullofeels_.xlsx */ {"$office$*2007*20*128*16*fbd4cc5dab9b8e341778ddcde9eca740*46bef371486919d4bffe7280110f913d*b51af42e6696baa097a7109cebc3d0ff7cc8b1d8", "myhovercraftisfullofeels"}, /* 2007-Default_myhovercraftisfullofeels_.xltx */ {"$office$*2007*20*128*16*fbd4cc5dab9b8e341778ddcde9eca740*1addb6823689aca9ce400be8f9e55fc9*e06bf10aaf3a4049ffa49dd91cf9e7bbf88a1b3b", "myhovercraftisfullofeels"}, {NULL} }; static ms_office_custom_salt *cur_salt; static ARCH_WORD_32 (*crypt_key)[4]; static char *saved_key; /* Password encoded in UCS-2 */ static int *saved_len; /* UCS-2 password length, in octets */ static char *saved_salt; static unsigned char *key; /* Output key from kernel */ static int new_keys; static cl_mem cl_saved_key, cl_saved_len, cl_salt, cl_pwhash, cl_key; static cl_mem pinned_saved_key, pinned_saved_len, pinned_salt, pinned_key; static cl_kernel GenerateSHA1pwhash, Generate2007key; static struct fmt_main *self; #define HASH_LOOPS 500 /* Lower figure gives less X hogging */ #define ITERATIONS 50000 #define STEP 0 #define SEED 128 static const char * warn[] = { "xfer: ", ", xfer: ", ", init: ", ", loop: ", ", final: ", ", xfer: " }; static int split_events[] = { 3, -1, -1 }; //This file contains auto-tuning routine(s). Has to be included after formats definitions. #include "opencl-autotune.h" #include "memdbg.h" /* ------- Helper functions ------- */ static size_t get_task_max_work_group_size() { size_t s; s = autotune_get_task_max_work_group_size(FALSE, 0, GenerateSHA1pwhash); s = MIN(s, autotune_get_task_max_work_group_size(FALSE, 0, crypt_kernel)); s = MIN(s, autotune_get_task_max_work_group_size(FALSE, 0, Generate2007key)); return s; } static void create_clobj(size_t gws, struct fmt_main *self) { int i; int bench_len = strlen(tests[0].plaintext) * 2; gws *= ocl_v_width; pinned_saved_key = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR, UNICODE_LENGTH * gws, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating page-locked memory"); cl_saved_key = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, UNICODE_LENGTH * gws, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating device memory"); saved_key = (char*)clEnqueueMapBuffer(queue[gpu_id], pinned_saved_key, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, UNICODE_LENGTH * gws, 0, NULL, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error mapping page-locked memory saved_key"); memset(saved_key, 0, UNICODE_LENGTH * gws); pinned_saved_len = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR, sizeof(cl_int) * gws, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating page-locked memory"); cl_saved_len = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, sizeof(cl_int) * gws, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating device memory"); saved_len = (int*)clEnqueueMapBuffer(queue[gpu_id], pinned_saved_len, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, sizeof(cl_int) * gws, 0, NULL, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error mapping page-locked memory saved_len"); for (i = 0; i < gws; i++) saved_len[i] = bench_len; pinned_salt = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR, SALT_LENGTH, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating page-locked memory"); cl_salt = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, SALT_LENGTH, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating device memory"); saved_salt = (char*) clEnqueueMapBuffer(queue[gpu_id], pinned_salt, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, SALT_LENGTH, 0, NULL, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error mapping page-locked memory saved_salt"); memset(saved_salt, 0, SALT_LENGTH); cl_pwhash = clCreateBuffer(context[gpu_id], CL_MEM_READ_WRITE, sizeof(cl_uint) * 6 * gws, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating device state buffer"); pinned_key = clCreateBuffer(context[gpu_id], CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR, 16 * gws, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating page-locked memory"); cl_key = clCreateBuffer(context[gpu_id], CL_MEM_READ_WRITE, 16 * gws, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating device memory"); key = (unsigned char*) clEnqueueMapBuffer(queue[gpu_id], pinned_key, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, 16 * gws, 0, NULL, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error mapping page-locked memory key"); memset(key, 0, 16 * gws); HANDLE_CLERROR(clSetKernelArg(GenerateSHA1pwhash, 0, sizeof(cl_mem), (void*)&cl_saved_key), "Error setting argument 0"); HANDLE_CLERROR(clSetKernelArg(GenerateSHA1pwhash, 1, sizeof(cl_mem), (void*)&cl_saved_len), "Error setting argument 1"); HANDLE_CLERROR(clSetKernelArg(GenerateSHA1pwhash, 2, sizeof(cl_mem), (void*)&cl_salt), "Error setting argument 2"); HANDLE_CLERROR(clSetKernelArg(GenerateSHA1pwhash, 3, sizeof(cl_mem), (void*)&cl_pwhash), "Error setting argument 3"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 0, sizeof(cl_mem), (void*)&cl_pwhash), "Error setting argument 0"); HANDLE_CLERROR(clSetKernelArg(Generate2007key, 0, sizeof(cl_mem), (void*)&cl_pwhash), "Error setting argument 0"); HANDLE_CLERROR(clSetKernelArg(Generate2007key, 1, sizeof(cl_mem), (void*)&cl_key), "Error setting argument 1"); crypt_key = mem_calloc(gws, sizeof(*crypt_key)); } static void release_clobj(void) { if (crypt_key) { HANDLE_CLERROR(clEnqueueUnmapMemObject(queue[gpu_id], pinned_key, key, 0, NULL, NULL), "Error Unmapping key"); HANDLE_CLERROR(clEnqueueUnmapMemObject(queue[gpu_id], pinned_saved_key, saved_key, 0, NULL, NULL), "Error Unmapping saved_key"); HANDLE_CLERROR(clEnqueueUnmapMemObject(queue[gpu_id], pinned_saved_len, saved_len, 0, NULL, NULL), "Error Unmapping saved_len"); HANDLE_CLERROR(clEnqueueUnmapMemObject(queue[gpu_id], pinned_salt, saved_salt, 0, NULL, NULL), "Error Unmapping saved_salt"); HANDLE_CLERROR(clFinish(queue[gpu_id]), "Error releasing memory mappings"); HANDLE_CLERROR(clReleaseMemObject(pinned_key), "Release GPU buffer"); HANDLE_CLERROR(clReleaseMemObject(pinned_saved_key), "Release GPU buffer"); HANDLE_CLERROR(clReleaseMemObject(pinned_saved_len), "Release GPU buffer"); HANDLE_CLERROR(clReleaseMemObject(pinned_salt), "Release GPU buffer"); HANDLE_CLERROR(clReleaseMemObject(cl_key), "Release GPU buffer"); HANDLE_CLERROR(clReleaseMemObject(cl_saved_key), "Release GPU buffer"); HANDLE_CLERROR(clReleaseMemObject(cl_saved_len), "Release GPU buffer"); HANDLE_CLERROR(clReleaseMemObject(cl_salt), "Release GPU buffer"); HANDLE_CLERROR(clReleaseMemObject(cl_pwhash), "Release GPU buffer"); MEM_FREE(crypt_key); } } static void done(void) { if (autotuned) { release_clobj(); HANDLE_CLERROR(clReleaseKernel(crypt_kernel), "Release kernel"); HANDLE_CLERROR(clReleaseKernel(GenerateSHA1pwhash), "Release kernel"); HANDLE_CLERROR(clReleaseKernel(Generate2007key), "Release kernel"); HANDLE_CLERROR(clReleaseProgram(program[gpu_id]), "Release Program"); autotuned--; } } static void clear_keys(void) { memset(saved_key, 0, UNICODE_LENGTH * global_work_size * ocl_v_width); memset(saved_len, 0, sizeof(*saved_len) * global_work_size * ocl_v_width); } static void set_key(char *key, int index) { UTF16 *utfkey = (UTF16*)&saved_key[index * UNICODE_LENGTH]; /* convert key to UTF-16LE */ saved_len[index] = enc_to_utf16(utfkey, PLAINTEXT_LENGTH, (UTF8*)key, strlen(key)); if (saved_len[index] < 0) saved_len[index] = strlen16(utfkey); /* Prepare for GPU */ utfkey[saved_len[index]] = 0x80; saved_len[index] <<= 1; new_keys = 1; //dump_stuff_msg("key buffer", &saved_key[index*UNICODE_LENGTH], UNICODE_LENGTH); } static void set_salt(void *salt) { cur_salt = (ms_office_custom_salt *)salt; memcpy(saved_salt, cur_salt->osalt, SALT_LENGTH); HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], cl_salt, CL_FALSE, 0, SALT_LENGTH, saved_salt, 0, NULL, NULL), "failed in clEnqueueWriteBuffer saved_salt"); } static void init(struct fmt_main *_self) { static char valgo[32] = ""; self = _self; opencl_prepare_dev(gpu_id); if ((ocl_v_width = opencl_get_vector_width(gpu_id, sizeof(cl_int))) > 1) { /* Run vectorized kernel */ snprintf(valgo, sizeof(valgo), OCL_ALGORITHM_NAME " %ux" CPU_ALGORITHM_NAME, ocl_v_width); self->params.algorithm_name = valgo; } if (options.target_enc == UTF_8) self->params.plaintext_length = MIN(125, 3 * PLAINTEXT_LENGTH); } static void reset(struct db_main *db) { if (!autotuned) { char build_opts[64]; snprintf(build_opts, sizeof(build_opts), "-DHASH_LOOPS=%u -DUNICODE_LENGTH=%u -DV_WIDTH=%u", HASH_LOOPS, UNICODE_LENGTH, ocl_v_width); opencl_init("$JOHN/kernels/office2007_kernel.cl", gpu_id, build_opts); // create kernel to execute GenerateSHA1pwhash = clCreateKernel(program[gpu_id], "GenerateSHA1pwhash", &ret_code); HANDLE_CLERROR(ret_code, "Error creating kernel. Double-check kernel name?"); crypt_kernel = clCreateKernel(program[gpu_id], "HashLoop", &ret_code); HANDLE_CLERROR(ret_code, "Error creating kernel. Double-check kernel name?"); Generate2007key = clCreateKernel(program[gpu_id], "Generate2007key", &ret_code); HANDLE_CLERROR(ret_code, "Error creating kernel. Double-check kernel name?"); // Initialize openCL tuning (library) for this format. opencl_init_auto_setup(SEED, HASH_LOOPS, split_events, warn, 3, self, create_clobj, release_clobj, ocl_v_width * UNICODE_LENGTH, 0, db); // Auto tune execution from shared/included code. autotune_run(self, ITERATIONS + 4, 0, (cpu(device_info[gpu_id]) ? 1000000000 : 10000000000ULL)); } } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index; size_t gws, scalar_gws; size_t *lws = local_work_size ? &local_work_size : NULL; gws = GET_MULTIPLE_OR_BIGGER_VW(count, local_work_size); scalar_gws = gws * ocl_v_width; if (ocl_autotune_running || new_keys) { BENCH_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], cl_saved_key, CL_FALSE, 0, UNICODE_LENGTH * scalar_gws, saved_key, 0, NULL, multi_profilingEvent[0]), "failed in clEnqueueWriteBuffer saved_key"); BENCH_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], cl_saved_len, CL_FALSE, 0, sizeof(int) * scalar_gws, saved_len, 0, NULL, multi_profilingEvent[1]), "failed in clEnqueueWriteBuffer saved_len"); new_keys = 0; } BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], GenerateSHA1pwhash, 1, NULL, &scalar_gws, lws, 0, NULL, multi_profilingEvent[2]), "failed in clEnqueueNDRangeKernel"); for (index = 0; index < (ocl_autotune_running ? 1 : 50000 / HASH_LOOPS); index++) { BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], crypt_kernel, 1, NULL, &gws, lws, 0, NULL, multi_profilingEvent[3]), "failed in clEnqueueNDRangeKernel"); BENCH_CLERROR(clFinish(queue[gpu_id]), "Error running loop kernel"); opencl_process_event(); } BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], Generate2007key, 1, NULL, &gws, lws, 0, NULL, multi_profilingEvent[4]), "failed in clEnqueueNDRangeKernel"); // read back aes key BENCH_CLERROR(clEnqueueReadBuffer(queue[gpu_id], cl_key, CL_TRUE, 0, 16 * scalar_gws, key, 0, NULL, multi_profilingEvent[5]), "failed in reading key back"); if (!ocl_autotune_running) { #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index++) ms_office_common_PasswordVerifier(cur_salt, &key[index*16], crypt_key[index]); } return count; } static int cmp_all(void *binary, int count) { int index; for (index = 0; index < count; index++) { if ( ((ARCH_WORD_32*)binary)[0] == crypt_key[index][0] ) return 1; } return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_key[index], BINARY_SIZE); } static int cmp_exact(char *source, int index) { return 1; } static int get_hash_0(int index) { return crypt_key[index][0] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_key[index][0] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_key[index][0] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_key[index][0] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_key[index][0] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_key[index][0] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_key[index][0] & PH_MASK_6; } static char *get_key(int index) { UTF16 buf[PLAINTEXT_LENGTH + 1]; memcpy(buf, &saved_key[index * UNICODE_LENGTH], saved_len[index]); buf[saved_len[index] >> 1] = 0; return (char*)utf16_to_enc(buf); } struct fmt_main fmt_opencl_office2007 = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_UNICODE | FMT_UTF8 | FMT_OMP, { NULL }, { FORMAT_TAG_OFFICE_2007 }, tests }, { init, done, reset, fmt_default_prepare, ms_office_common_valid_2007, fmt_default_split, ms_office_common_binary, ms_office_common_get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, NULL, set_salt, set_key, get_key, clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */ #endif /* HAVE_OPENCL */
convolution_3x3.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. // Copyright (C) 2019 BUG1989. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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. static void conv3x3s1_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); for (int q=0; q<inch; q++) { float* outptr = out; float* outptr2 = outptr + outw; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch*9 + q*9; const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w*2; const float* r3 = img0 + w*3; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; int i = 0; for (; i+1 < outh; i+=2) { int remain = outw; for (; remain>0; remain--) { float sum = 0; float sum2 = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; sum2 += r1[0] * k0[0]; sum2 += r1[1] * k0[1]; sum2 += r1[2] * k0[2]; sum2 += r2[0] * k1[0]; sum2 += r2[1] * k1[1]; sum2 += r2[2] * k1[2]; sum2 += r3[0] * k2[0]; sum2 += r3[1] * k2[1]; sum2 += r3[2] * k2[2]; *outptr += sum; *outptr2 += sum2; r0++; r1++; r2++; r3++; outptr++; outptr2++; } r0 += 2 + w; r1 += 2 + w; r2 += 2 + w; r3 += 2 + w; outptr += outw; outptr2 += outw; } for (; i < outh; i++) { int remain = outw; for (; remain>0; remain--) { float sum = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr += sum; r0++; r1++; r2++; outptr++; } r0 += 2; r1 += 2; r2 += 2; } } } } static void conv3x3s1_winograd23_transform_kernel_sse(const Mat& kernel, Mat& kernel_tm, int inch, int outch) { kernel_tm.create(4*4, inch, outch); // G const float ktm[4][3] = { { 1.0f, 0.0f, 0.0f}, { 1.0f/2, 1.0f/2, 1.0f/2}, { 1.0f/2, -1.0f/2, 1.0f/2}, { 0.0f, 0.0f, 1.0f} }; #pragma omp parallel for for (int p = 0; p<outch; p++) { for (int q = 0; q<inch; q++) { const float* kernel0 = (const float*)kernel + p*inch * 9 + q * 9; float* kernel_tm0 = kernel_tm.channel(p).row(q); // transform kernel const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; // h float tmp[4][3]; for (int i=0; i<4; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // U for (int j=0; j<4; j++) { float* tmpp = &tmp[j][0]; for (int i=0; i<4; i++) { kernel_tm0[j*4 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } } static void conv3x3s1_winograd23_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 2n+2, winograd F(2,3) Mat bottom_blob_bordered = bottom_blob; outw = (outw + 1) / 2 * 2; outh = (outh + 1) / 2 * 2; w = outw + 2; h = outh + 2; Option opt_b = opt; opt_b.blob_allocator = opt.workspace_allocator; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f, opt_b); const float* bias = _bias; // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 2 * 4; int h_tm = outh / 2 * 4; int nColBlocks = h_tm/4; // may be the block num in Feathercnn int nRowBlocks = w_tm/4; const int tiles = nColBlocks * nRowBlocks; bottom_blob_tm.create(4*4, tiles, inch, 4u, opt.workspace_allocator); // BT // const float itm[4][4] = { // {1.0f, 0.0f, -1.0f, 0.0f}, // {0.0f, 1.0f, 1.00f, 0.0f}, // {0.0f, -1.0f, 1.00f, 0.0f}, // {0.0f, -1.0f, 0.00f, 1.0f} // }; #pragma omp parallel for num_threads(opt.num_threads) for (int q=0; q<inch; q++) { const float* img = bottom_blob_bordered.channel(q); float* out_tm0 = bottom_blob_tm.channel(q); for (int j = 0; j < nColBlocks; j++) { const float* r0 = img + w * j * 2; const float* r1 = r0 + w; const float* r2 = r1 + w; const float* r3 = r2 + w; for (int i = 0; i < nRowBlocks; i++) { #if __AVX__ __m128 _d0, _d1, _d2, _d3; __m128 _w0, _w1, _w2, _w3; // load _d0 = _mm_loadu_ps(r0); _d1 = _mm_loadu_ps(r1); _d2 = _mm_loadu_ps(r2); _d3 = _mm_loadu_ps(r3); // w = B_t * d _w0 = _mm_sub_ps(_d0, _d2); _w1 = _mm_add_ps(_d1, _d2); _w2 = _mm_sub_ps(_d2, _d1); _w3 = _mm_sub_ps(_d3, _d1); // transpose d to d_t _MM_TRANSPOSE4_PS(_w0, _w1, _w2, _w3); // d = B_t * d_t _d0 = _mm_sub_ps(_w0, _w2); _d1 = _mm_add_ps(_w1, _w2); _d2 = _mm_sub_ps(_w2, _w1); _d3 = _mm_sub_ps(_w3, _w1); // save to out_tm _mm_storeu_ps(out_tm0, _d0); _mm_storeu_ps(out_tm0+4, _d1); _mm_storeu_ps(out_tm0+8, _d2); _mm_storeu_ps(out_tm0+12, _d3); #else float d0[4],d1[4],d2[4],d3[4]; float w0[4],w1[4],w2[4],w3[4]; float t0[4],t1[4],t2[4],t3[4]; // load for (int n = 0; n < 4; n++) { d0[n] = r0[n]; d1[n] = r1[n]; d2[n] = r2[n]; d3[n] = r3[n]; } // w = B_t * d for (int n = 0; n < 4; n++) { w0[n] = d0[n] - d2[n]; w1[n] = d1[n] + d2[n]; w2[n] = d2[n] - d1[n]; w3[n] = d3[n] - d1[n]; } // transpose d to d_t { t0[0]=w0[0]; t1[0]=w0[1]; t2[0]=w0[2]; t3[0]=w0[3]; t0[1]=w1[0]; t1[1]=w1[1]; t2[1]=w1[2]; t3[1]=w1[3]; t0[2]=w2[0]; t1[2]=w2[1]; t2[2]=w2[2]; t3[2]=w2[3]; t0[3]=w3[0]; t1[3]=w3[1]; t2[3]=w3[2]; t3[3]=w3[3]; } // d = B_t * d_t for (int n = 0; n < 4; n++) { d0[n] = t0[n] - t2[n]; d1[n] = t1[n] + t2[n]; d2[n] = t2[n] - t1[n]; d3[n] = t3[n] - t1[n]; } // save to out_tm for (int n = 0; n < 4; n++) { out_tm0[n ] = d0[n]; out_tm0[n+ 4] = d1[n]; out_tm0[n+ 8] = d2[n]; out_tm0[n+12] = d3[n]; } #endif r0 += 2; r1 += 2; r2 += 2; r3 += 2; out_tm0 += 16; } } } } bottom_blob_bordered = Mat(); // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 2 * 4; int h_tm = outh / 2 * 4; int nColBlocks = h_tm/4; // may be the block num in Feathercnn int nRowBlocks = w_tm/4; const int tiles = nColBlocks * nRowBlocks; top_blob_tm.create(16, tiles, outch, 4u, opt.workspace_allocator); int nn_outch = outch >> 2; int remain_outch_start = nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp=0; pp<nn_outch; pp++) { int p = pp * 4; Mat out0_tm = top_blob_tm.channel(p); Mat out1_tm = top_blob_tm.channel(p+1); Mat out2_tm = top_blob_tm.channel(p+2); Mat out3_tm = top_blob_tm.channel(p+3); const Mat kernel0_tm = kernel_tm.channel(p); const Mat kernel1_tm = kernel_tm.channel(p+1); const Mat kernel2_tm = kernel_tm.channel(p+2); const Mat kernel3_tm = kernel_tm.channel(p+3); for (int i=0; i<tiles; i++) { float* output0_tm = out0_tm.row(i); float* output1_tm = out1_tm.row(i); float* output2_tm = out2_tm.row(i); float* output3_tm = out3_tm.row(i); #if __AVX__ float zero_val = 0.f; __m256 _sum0 = _mm256_broadcast_ss(&zero_val); __m256 _sum0n = _mm256_broadcast_ss(&zero_val); __m256 _sum1 = _mm256_broadcast_ss(&zero_val); __m256 _sum1n = _mm256_broadcast_ss(&zero_val); __m256 _sum2 = _mm256_broadcast_ss(&zero_val); __m256 _sum2n = _mm256_broadcast_ss(&zero_val); __m256 _sum3 = _mm256_broadcast_ss(&zero_val); __m256 _sum3n = _mm256_broadcast_ss(&zero_val); int q = 0; for (; q+3<inch; q+=4) { const float* r0 = bottom_blob_tm.channel(q).row(i); const float* r1 = bottom_blob_tm.channel(q+1).row(i); const float* r2 = bottom_blob_tm.channel(q+2).row(i); const float* r3 = bottom_blob_tm.channel(q+3).row(i); const float* k0 = kernel0_tm.row(q); const float* k1 = kernel1_tm.row(q); const float* k2 = kernel2_tm.row(q); const float* k3 = kernel3_tm.row(q); __m256 _r0 = _mm256_loadu_ps(r0); __m256 _r0n = _mm256_loadu_ps(r0+8); // k0 __m256 _k0 = _mm256_loadu_ps(k0); __m256 _k0n = _mm256_loadu_ps(k0+8); __m256 _k1 = _mm256_loadu_ps(k1); __m256 _k1n = _mm256_loadu_ps(k1+8); __m256 _k2 = _mm256_loadu_ps(k2); __m256 _k2n = _mm256_loadu_ps(k2+8); __m256 _k3 = _mm256_loadu_ps(k3); __m256 _k3n = _mm256_loadu_ps(k3+8); _sum0 = _mm256_fmadd_ps(_r0, _k0, _sum0); _sum0n = _mm256_fmadd_ps(_r0n, _k0n, _sum0n); _sum1 = _mm256_fmadd_ps(_r0, _k1, _sum1); _sum1n = _mm256_fmadd_ps(_r0n, _k1n, _sum1n); _sum2 = _mm256_fmadd_ps(_r0, _k2, _sum2); _sum2n = _mm256_fmadd_ps(_r0n, _k2n, _sum2n); _sum3 = _mm256_fmadd_ps(_r0, _k3, _sum3); _sum3n = _mm256_fmadd_ps(_r0n, _k3n, _sum3n); // k1 _r0 = _mm256_loadu_ps(r1); _r0n = _mm256_loadu_ps(r1+8); _k0 = _mm256_loadu_ps(k0+16); _k0n = _mm256_loadu_ps(k0+24); _k1 = _mm256_loadu_ps(k1+16); _k1n = _mm256_loadu_ps(k1+24); _k2 = _mm256_loadu_ps(k2+16); _k2n = _mm256_loadu_ps(k2+24); _k3 = _mm256_loadu_ps(k3+16); _k3n = _mm256_loadu_ps(k3+24); _sum0 = _mm256_fmadd_ps(_r0, _k0, _sum0); _sum0n = _mm256_fmadd_ps(_r0n, _k0n, _sum0n); _sum1 = _mm256_fmadd_ps(_r0, _k1, _sum1); _sum1n = _mm256_fmadd_ps(_r0n, _k1n, _sum1n); _sum2 = _mm256_fmadd_ps(_r0, _k2, _sum2); _sum2n = _mm256_fmadd_ps(_r0n, _k2n, _sum2n); _sum3 = _mm256_fmadd_ps(_r0, _k3, _sum3); _sum3n = _mm256_fmadd_ps(_r0n, _k3n, _sum3n); // k2 _r0 = _mm256_loadu_ps(r2); _r0n = _mm256_loadu_ps(r2+8); _k0 = _mm256_loadu_ps(k0+32); _k0n = _mm256_loadu_ps(k0+40); _k1 = _mm256_loadu_ps(k1+32); _k1n = _mm256_loadu_ps(k1+40); _k2 = _mm256_loadu_ps(k2+32); _k2n = _mm256_loadu_ps(k2+40); _k3 = _mm256_loadu_ps(k3+32); _k3n = _mm256_loadu_ps(k3+40); _sum0 = _mm256_fmadd_ps(_r0, _k0, _sum0); _sum0n = _mm256_fmadd_ps(_r0n, _k0n, _sum0n); _sum1 = _mm256_fmadd_ps(_r0, _k1, _sum1); _sum1n = _mm256_fmadd_ps(_r0n, _k1n, _sum1n); _sum2 = _mm256_fmadd_ps(_r0, _k2, _sum2); _sum2n = _mm256_fmadd_ps(_r0n, _k2n, _sum2n); _sum3 = _mm256_fmadd_ps(_r0, _k3, _sum3); _sum3n = _mm256_fmadd_ps(_r0n, _k3n, _sum3n); // k3 _r0 = _mm256_loadu_ps(r3); _r0n = _mm256_loadu_ps(r3+8); _k0 = _mm256_loadu_ps(k0+48); _k0n = _mm256_loadu_ps(k0+56); _k1 = _mm256_loadu_ps(k1+48); _k1n = _mm256_loadu_ps(k1+56); _k2 = _mm256_loadu_ps(k2+48); _k2n = _mm256_loadu_ps(k2+56); _k3 = _mm256_loadu_ps(k3+48); _k3n = _mm256_loadu_ps(k3+56); _sum0 = _mm256_fmadd_ps(_r0, _k0, _sum0); _sum0n = _mm256_fmadd_ps(_r0n, _k0n, _sum0n); _sum1 = _mm256_fmadd_ps(_r0, _k1, _sum1); _sum1n = _mm256_fmadd_ps(_r0n, _k1n, _sum1n); _sum2 = _mm256_fmadd_ps(_r0, _k2, _sum2); _sum2n = _mm256_fmadd_ps(_r0n, _k2n, _sum2n); _sum3 = _mm256_fmadd_ps(_r0, _k3, _sum3); _sum3n = _mm256_fmadd_ps(_r0n, _k3n, _sum3n); } for (; q<inch; q++) { const float* r0 = bottom_blob_tm.channel(q).row(i); const float* k0 = kernel0_tm.row(q); const float* k1 = kernel1_tm.row(q); const float* k2 = kernel2_tm.row(q); const float* k3 = kernel3_tm.row(q); __m256 _r0 = _mm256_loadu_ps(r0); __m256 _r0n = _mm256_loadu_ps(r0+8); __m256 _k0 = _mm256_loadu_ps(k0); __m256 _k0n = _mm256_loadu_ps(k0+8); __m256 _k1 = _mm256_loadu_ps(k1); __m256 _k1n = _mm256_loadu_ps(k1+8); __m256 _k2 = _mm256_loadu_ps(k2); __m256 _k2n = _mm256_loadu_ps(k2+8); __m256 _k3 = _mm256_loadu_ps(k3); __m256 _k3n = _mm256_loadu_ps(k3+8); _sum0 = _mm256_fmadd_ps(_r0, _k0, _sum0); _sum0n = _mm256_fmadd_ps(_r0n, _k0n, _sum0n); _sum1 = _mm256_fmadd_ps(_r0, _k1, _sum1); _sum1n = _mm256_fmadd_ps(_r0n, _k1n, _sum1n); _sum2 = _mm256_fmadd_ps(_r0, _k2, _sum2); _sum2n = _mm256_fmadd_ps(_r0n, _k2n, _sum2n); _sum3 = _mm256_fmadd_ps(_r0, _k3, _sum3); _sum3n = _mm256_fmadd_ps(_r0n, _k3n, _sum3n); } _mm256_storeu_ps(output0_tm, _sum0); _mm256_storeu_ps(output0_tm+8, _sum0n); _mm256_storeu_ps(output1_tm, _sum1); _mm256_storeu_ps(output1_tm+8, _sum1n); _mm256_storeu_ps(output2_tm, _sum2); _mm256_storeu_ps(output2_tm+8, _sum2n); _mm256_storeu_ps(output3_tm, _sum3); _mm256_storeu_ps(output3_tm+8, _sum3n); #else float sum0[16] = {0.0f}; float sum1[16] = {0.0f}; float sum2[16] = {0.0f}; float sum3[16] = {0.0f}; int q = 0; for (; q+3<inch; q+=4) { const float* r0 = bottom_blob_tm.channel(q).row(i); const float* r1 = bottom_blob_tm.channel(q+1).row(i); const float* r2 = bottom_blob_tm.channel(q+2).row(i); const float* r3 = bottom_blob_tm.channel(q+3).row(i); const float* k0 = kernel0_tm.row(q); const float* k1 = kernel1_tm.row(q); const float* k2 = kernel2_tm.row(q); const float* k3 = kernel3_tm.row(q); for (int n=0; n<16; n++) { sum0[n] += r0[n] * k0[n]; k0 += 16; sum0[n] += r1[n] * k0[n]; k0 += 16; sum0[n] += r2[n] * k0[n]; k0 += 16; sum0[n] += r3[n] * k0[n]; k0 -= 16 * 3; sum1[n] += r0[n] * k1[n]; k1 += 16; sum1[n] += r1[n] * k1[n]; k1 += 16; sum1[n] += r2[n] * k1[n]; k1 += 16; sum1[n] += r3[n] * k1[n]; k1 -= 16 * 3; sum2[n] += r0[n] * k2[n]; k2 += 16; sum2[n] += r1[n] * k2[n]; k2 += 16; sum2[n] += r2[n] * k2[n]; k2 += 16; sum2[n] += r3[n] * k2[n]; k2 -= 16 * 3; sum3[n] += r0[n] * k3[n]; k3 += 16; sum3[n] += r1[n] * k3[n]; k3 += 16; sum3[n] += r2[n] * k3[n]; k3 += 16; sum3[n] += r3[n] * k3[n]; k3 -= 16 * 3; } } for (; q<inch; q++) { const float* r0 = bottom_blob_tm.channel(q).row(i); const float* k0 = kernel0_tm.row(q); const float* k1 = kernel1_tm.row(q); const float* k2 = kernel2_tm.row(q); const float* k3 = kernel3_tm.row(q); for (int n=0; n<16; n++) { sum0[n] += r0[n] * k0[n]; sum1[n] += r0[n] * k1[n]; sum2[n] += r0[n] * k2[n]; sum3[n] += r0[n] * k3[n]; } } for (int n=0; n<16; n++) { output0_tm[n] = sum0[n]; output1_tm[n] = sum1[n]; output2_tm[n] = sum2[n]; output3_tm[n] = sum3[n]; } #endif } } #pragma omp parallel for num_threads(opt.num_threads) for (int p=remain_outch_start; p<outch; p++) { Mat out0_tm = top_blob_tm.channel(p); const Mat kernel0_tm = kernel_tm.channel(p); for (int i=0; i<tiles; i++) { float* output0_tm = out0_tm.row(i); float sum0[16] = {0.0f}; int q = 0; for (; q+3<inch; q+=4) { const float* r0 = bottom_blob_tm.channel(q).row(i); const float* r1 = bottom_blob_tm.channel(q+1).row(i); const float* r2 = bottom_blob_tm.channel(q+2).row(i); const float* r3 = bottom_blob_tm.channel(q+3).row(i); const float* k0 = kernel0_tm.row(q); const float* k1 = kernel0_tm.row(q+1); const float* k2 = kernel0_tm.row(q+2); const float* k3 = kernel0_tm.row(q+3); for (int n=0; n<16; n++) { sum0[n] += r0[n] * k0[n]; sum0[n] += r1[n] * k1[n]; sum0[n] += r2[n] * k2[n]; sum0[n] += r3[n] * k3[n]; } } for (; q<inch; q++) { const float* r0 = bottom_blob_tm.channel(q).row(i); const float* k0 = kernel0_tm.row(q); for (int n=0; n<16; n++) { sum0[n] += r0[n] * k0[n]; } } for (int n=0; n<16; n++) { output0_tm[n] = sum0[n]; } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; top_blob_bordered.create(outw, outh, outch, 4u, opt.workspace_allocator); { // AT // const float itm[2][4] = { // {1.0f, 1.0f, 1.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 1.0f} // }; int w_tm = outw / 2 * 4; int h_tm = outh / 2 * 4; int nColBlocks = h_tm/4; // may be the block num in Feathercnn int nRowBlocks = w_tm/4; #pragma omp parallel for num_threads(opt.num_threads) for (int p=0; p<outch; p++) { Mat out_tm = top_blob_tm.channel(p); Mat out = top_blob_bordered.channel(p); const float bias0 = bias ? bias[p] : 0.f; for (int j=0; j<nColBlocks; j++) { float* outRow0 = out.row(j*2); float* outRow1 = out.row(j*2+1); for(int i=0; i<nRowBlocks; i++) { float* out_tile = out_tm.row(j*nRowBlocks + i); float s0[4],s1[4],s2[4],s3[4]; float w0[4],w1[4]; float d0[2],d1[2],d2[2],d3[2]; float o0[2],o1[2]; // load for (int n = 0; n < 4; n++) { s0[n] = out_tile[n]; s1[n] = out_tile[n+ 4]; s2[n] = out_tile[n+ 8]; s3[n] = out_tile[n+12]; } // w = A_T * W for (int n = 0; n < 4; n++) { w0[n] = s0[n] + s1[n] + s2[n]; w1[n] = s1[n] - s2[n] + s3[n]; } // transpose w to w_t { d0[0] = w0[0]; d0[1] = w1[0]; d1[0] = w0[1]; d1[1] = w1[1]; d2[0] = w0[2]; d2[1] = w1[2]; d3[0] = w0[3]; d3[1] = w1[3]; } // Y = A_T * w_t for (int n = 0; n < 2; n++) { o0[n] = d0[n] + d1[n] + d2[n] + bias0; o1[n] = d1[n] - d2[n] + d3[n] + bias0; } // save to top blob tm outRow0[0] = o0[0]; outRow0[1] = o0[1]; outRow1[0] = o1[0]; outRow1[1] = o1[1]; outRow0 += 2; outRow1 += 2; } } } } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt); } static void conv3x3s1_winograd43_transform_kernel_sse(const Mat& kernel, std::vector<Mat> &kernel_tm2, int inch, int outch) { Mat kernel_tm(6*6, inch, outch); // G const float ktm[6][3] = { { 1.0f/4, 0.0f, 0.0f}, { -1.0f/6, -1.0f/6, -1.0f/6}, { -1.0f/6, 1.0f/6, -1.0f/6}, { 1.0f/24, 1.0f/12, 1.0f/6}, { 1.0f/24, -1.0f/12, 1.0f/6}, { 0.0f, 0.0f, 1.0f} }; #pragma omp parallel for for (int p = 0; p<outch; p++) { for (int q = 0; q<inch; q++) { const float* kernel0 = (const float*)kernel + p*inch * 9 + q * 9; float* kernel_tm0 = kernel_tm.channel(p).row(q); // transform kernel const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; // h float tmp[6][3]; for (int i=0; i<6; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // U for (int j=0; j<6; j++) { float* tmpp = &tmp[j][0]; for (int i=0; i<6; i++) { kernel_tm0[j*6 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } for (int r=0; r<9; r++) { Mat kernel_tm_test(4*8, inch, outch/8 + (outch%8)/4 + outch%4); int p = 0; for (; p+7<outch; p+=8) { const float* kernel0 = (const float*)kernel_tm.channel(p); const float* kernel1 = (const float*)kernel_tm.channel(p+1); const float* kernel2 = (const float*)kernel_tm.channel(p+2); const float* kernel3 = (const float*)kernel_tm.channel(p+3); const float* kernel4 = (const float*)kernel_tm.channel(p+4); const float* kernel5 = (const float*)kernel_tm.channel(p+5); const float* kernel6 = (const float*)kernel_tm.channel(p+6); const float* kernel7 = (const float*)kernel_tm.channel(p+7); float* ktmp = kernel_tm_test.channel(p/8); for (int q=0; q<inch; q++) { ktmp[0] = kernel0[r*4+0]; ktmp[1] = kernel0[r*4+1]; ktmp[2] = kernel0[r*4+2]; ktmp[3] = kernel0[r*4+3]; ktmp[4] = kernel1[r*4+0]; ktmp[5] = kernel1[r*4+1]; ktmp[6] = kernel1[r*4+2]; ktmp[7] = kernel1[r*4+3]; ktmp[8] = kernel2[r*4+0]; ktmp[9] = kernel2[r*4+1]; ktmp[10] = kernel2[r*4+2]; ktmp[11] = kernel2[r*4+3]; ktmp[12] = kernel3[r*4+0]; ktmp[13] = kernel3[r*4+1]; ktmp[14] = kernel3[r*4+2]; ktmp[15] = kernel3[r*4+3]; ktmp[16] = kernel4[r*4+0]; ktmp[17] = kernel4[r*4+1]; ktmp[18] = kernel4[r*4+2]; ktmp[19] = kernel4[r*4+3]; ktmp[20] = kernel5[r*4+0]; ktmp[21] = kernel5[r*4+1]; ktmp[22] = kernel5[r*4+2]; ktmp[23] = kernel5[r*4+3]; ktmp[24] = kernel6[r*4+0]; ktmp[25] = kernel6[r*4+1]; ktmp[26] = kernel6[r*4+2]; ktmp[27] = kernel6[r*4+3]; ktmp[28] = kernel7[r*4+0]; ktmp[29] = kernel7[r*4+1]; ktmp[30] = kernel7[r*4+2]; ktmp[31] = kernel7[r*4+3]; ktmp += 32; kernel0 += 36; kernel1 += 36; kernel2 += 36; kernel3 += 36; kernel4 += 36; kernel5 += 36; kernel6 += 36; kernel7 += 36; } } for (; p+3<outch; p+=4) { const float* kernel0 = (const float*)kernel_tm.channel(p); const float* kernel1 = (const float*)kernel_tm.channel(p+1); const float* kernel2 = (const float*)kernel_tm.channel(p+2); const float* kernel3 = (const float*)kernel_tm.channel(p+3); float* ktmp = kernel_tm_test.channel(p/8 + (p%8)/4); for (int q=0; q<inch; q++) { ktmp[0] = kernel0[r*4+0]; ktmp[1] = kernel0[r*4+1]; ktmp[2] = kernel0[r*4+2]; ktmp[3] = kernel0[r*4+3]; ktmp[4] = kernel1[r*4+0]; ktmp[5] = kernel1[r*4+1]; ktmp[6] = kernel1[r*4+2]; ktmp[7] = kernel1[r*4+3]; ktmp[8] = kernel2[r*4+0]; ktmp[9] = kernel2[r*4+1]; ktmp[10] = kernel2[r*4+2]; ktmp[11] = kernel2[r*4+3]; ktmp[12] = kernel3[r*4+0]; ktmp[13] = kernel3[r*4+1]; ktmp[14] = kernel3[r*4+2]; ktmp[15] = kernel3[r*4+3]; ktmp += 16; kernel0 += 36; kernel1 += 36; kernel2 += 36; kernel3 += 36; } } for (; p<outch; p++) { const float* kernel0 = (const float*)kernel_tm.channel(p); float* ktmp = kernel_tm_test.channel(p/8 + (p%8)/4 + p%4); for (int q=0; q<inch; q++) { ktmp[0] = kernel0[r*4+0]; ktmp[1] = kernel0[r*4+1]; ktmp[2] = kernel0[r*4+2]; ktmp[3] = kernel0[r*4+3]; ktmp += 4; kernel0 += 36; } } kernel_tm2.push_back(kernel_tm_test); } } static void conv3x3s1_winograd43_sse(const Mat& bottom_blob, Mat& top_blob, const std::vector<Mat> &kernel_tm_test, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; size_t elemsize = bottom_blob.elemsize; const float* bias = _bias; // pad to 4n+2, winograd F(4,3) Mat bottom_blob_bordered = bottom_blob; outw = (outw + 3) / 4 * 4; outh = (outh + 3) / 4 * 4; w = outw + 2; h = outh + 2; Option opt_b = opt; opt_b.blob_allocator = opt.workspace_allocator; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f, opt_b); // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; int nColBlocks = h_tm/6; // may be the block num in Feathercnn int nRowBlocks = w_tm/6; const int tiles = nColBlocks * nRowBlocks; bottom_blob_tm.create(4, inch, tiles*9, elemsize, opt.workspace_allocator); // BT // const float itm[4][4] = { // {4.0f, 0.0f, -5.0f, 0.0f, 1.0f, 0.0f}, // {0.0f,-4.0f, -4.0f, 1.0f, 1.0f, 0.0f}, // {0.0f, 4.0f, -4.0f,-1.0f, 1.0f, 0.0f}, // {0.0f,-2.0f, -1.0f, 2.0f, 1.0f, 0.0f}, // {0.0f, 2.0f, -1.0f,-2.0f, 1.0f, 0.0f}, // {0.0f, 4.0f, 0.0f,-5.0f, 0.0f, 1.0f} // }; // 0 = 4 * r00 - 5 * r02 + r04 // 1 = -4 * (r01 + r02) + r03 + r04 // 2 = 4 * (r01 - r02) - r03 + r04 // 3 = -2 * r01 - r02 + 2 * r03 + r04 // 4 = 2 * r01 - r02 - 2 * r03 + r04 // 5 = 4 * r01 - 5 * r03 + r05 // 0 = 4 * r00 - 5 * r02 + r04 // 1 = -4 * (r01 + r02) + r03 + r04 // 2 = 4 * (r01 - r02) - r03 + r04 // 3 = -2 * r01 - r02 + 2 * r03 + r04 // 4 = 2 * r01 - r02 - 2 * r03 + r04 // 5 = 4 * r01 - 5 * r03 + r05 #if __AVX__ __m256 _1_n = _mm256_set1_ps(-1); __m256 _2_p = _mm256_set1_ps(2); __m256 _2_n = _mm256_set1_ps(-2); __m256 _4_p = _mm256_set1_ps(4); __m256 _4_n = _mm256_set1_ps(-4); __m256 _5_n = _mm256_set1_ps(-5); #endif #pragma omp parallel for num_threads(opt.num_threads) for (int q=0; q<inch; q++) { const float* img = bottom_blob_bordered.channel(q); for (int j = 0; j < nColBlocks; j++) { const float* r0 = img + w * j * 4; const float* r1 = r0 + w; const float* r2 = r1 + w; const float* r3 = r2 + w; const float* r4 = r3 + w; const float* r5 = r4 + w; for (int i = 0; i < nRowBlocks; i++) { float* out_tm0 = bottom_blob_tm.channel(tiles*0+j*nRowBlocks+i).row(q); float* out_tm1 = bottom_blob_tm.channel(tiles*1+j*nRowBlocks+i).row(q); float* out_tm2 = bottom_blob_tm.channel(tiles*2+j*nRowBlocks+i).row(q); float* out_tm3 = bottom_blob_tm.channel(tiles*3+j*nRowBlocks+i).row(q); float* out_tm4 = bottom_blob_tm.channel(tiles*4+j*nRowBlocks+i).row(q); float* out_tm5 = bottom_blob_tm.channel(tiles*5+j*nRowBlocks+i).row(q); float* out_tm6 = bottom_blob_tm.channel(tiles*6+j*nRowBlocks+i).row(q); float* out_tm7 = bottom_blob_tm.channel(tiles*7+j*nRowBlocks+i).row(q); float* out_tm8 = bottom_blob_tm.channel(tiles*8+j*nRowBlocks+i).row(q); #if __AVX__ __m256 _d0, _d1, _d2, _d3, _d4, _d5; __m256 _w0, _w1, _w2, _w3, _w4, _w5; __m256 _t0, _t1, _t2, _t3, _t4, _t5; __m256 _n0, _n1, _n2, _n3, _n4, _n5; // load _d0 = _mm256_loadu_ps(r0); _d1 = _mm256_loadu_ps(r1); _d2 = _mm256_loadu_ps(r2); _d3 = _mm256_loadu_ps(r3); _d4 = _mm256_loadu_ps(r4); _d5 = _mm256_loadu_ps(r5); // w = B_t * d _w0 = _mm256_mul_ps(_d0, _4_p); _w0 = _mm256_fmadd_ps(_d2, _5_n, _w0); _w0 = _mm256_add_ps(_w0, _d4); _w1 = _mm256_mul_ps(_d1, _4_n); _w1 = _mm256_fmadd_ps(_d2, _4_n, _w1); _w1 = _mm256_add_ps(_w1, _d3); _w1 = _mm256_add_ps(_w1, _d4); _w2 = _mm256_mul_ps(_d1, _4_p); _w2 = _mm256_fmadd_ps(_d2, _4_n, _w2); _w2 = _mm256_fmadd_ps(_d3, _1_n, _w2); _w2 = _mm256_add_ps(_w2, _d4); _w3 = _mm256_mul_ps(_d1, _2_n); _w3 = _mm256_fmadd_ps(_d2, _1_n, _w3); _w3 = _mm256_fmadd_ps(_d3, _2_p, _w3); _w3 = _mm256_add_ps(_w3, _d4); _w4 = _mm256_mul_ps(_d1, _2_p); _w4 = _mm256_fmadd_ps(_d2, _1_n, _w4); _w4 = _mm256_fmadd_ps(_d3, _2_n, _w4); _w4 = _mm256_add_ps(_w4, _d4); _w5 = _mm256_mul_ps(_d1, _4_p); _w5 = _mm256_fmadd_ps(_d3, _5_n, _w5); _w5 = _mm256_add_ps(_w5, _d5); // transpose d to d_t #ifdef _WIN32 { _t0.m256_f32[0]=_w0.m256_f32[0]; _t1.m256_f32[0]=_w0.m256_f32[1]; _t2.m256_f32[0]=_w0.m256_f32[2]; _t3.m256_f32[0]=_w0.m256_f32[3]; _t4.m256_f32[0]=_w0.m256_f32[4]; _t5.m256_f32[0]=_w0.m256_f32[5]; _t0.m256_f32[1]=_w1.m256_f32[0]; _t1.m256_f32[1]=_w1.m256_f32[1]; _t2.m256_f32[1]=_w1.m256_f32[2]; _t3.m256_f32[1]=_w1.m256_f32[3]; _t4.m256_f32[1]=_w1.m256_f32[4]; _t5.m256_f32[1]=_w1.m256_f32[5]; _t0.m256_f32[2]=_w2.m256_f32[0]; _t1.m256_f32[2]=_w2.m256_f32[1]; _t2.m256_f32[2]=_w2.m256_f32[2]; _t3.m256_f32[2]=_w2.m256_f32[3]; _t4.m256_f32[2]=_w2.m256_f32[4]; _t5.m256_f32[2]=_w2.m256_f32[5]; _t0.m256_f32[3]=_w3.m256_f32[0]; _t1.m256_f32[3]=_w3.m256_f32[1]; _t2.m256_f32[3]=_w3.m256_f32[2]; _t3.m256_f32[3]=_w3.m256_f32[3]; _t4.m256_f32[3]=_w3.m256_f32[4]; _t5.m256_f32[3]=_w3.m256_f32[5]; _t0.m256_f32[4]=_w4.m256_f32[0]; _t1.m256_f32[4]=_w4.m256_f32[1]; _t2.m256_f32[4]=_w4.m256_f32[2]; _t3.m256_f32[4]=_w4.m256_f32[3]; _t4.m256_f32[4]=_w4.m256_f32[4]; _t5.m256_f32[4]=_w4.m256_f32[5]; _t0.m256_f32[5]=_w5.m256_f32[0]; _t1.m256_f32[5]=_w5.m256_f32[1]; _t2.m256_f32[5]=_w5.m256_f32[2]; _t3.m256_f32[5]=_w5.m256_f32[3]; _t4.m256_f32[5]=_w5.m256_f32[4]; _t5.m256_f32[5]=_w5.m256_f32[5]; } #else { _t0[0]=_w0[0]; _t1[0]=_w0[1]; _t2[0]=_w0[2]; _t3[0]=_w0[3]; _t4[0]=_w0[4]; _t5[0]=_w0[5]; _t0[1]=_w1[0]; _t1[1]=_w1[1]; _t2[1]=_w1[2]; _t3[1]=_w1[3]; _t4[1]=_w1[4]; _t5[1]=_w1[5]; _t0[2]=_w2[0]; _t1[2]=_w2[1]; _t2[2]=_w2[2]; _t3[2]=_w2[3]; _t4[2]=_w2[4]; _t5[2]=_w2[5]; _t0[3]=_w3[0]; _t1[3]=_w3[1]; _t2[3]=_w3[2]; _t3[3]=_w3[3]; _t4[3]=_w3[4]; _t5[3]=_w3[5]; _t0[4]=_w4[0]; _t1[4]=_w4[1]; _t2[4]=_w4[2]; _t3[4]=_w4[3]; _t4[4]=_w4[4]; _t5[4]=_w4[5]; _t0[5]=_w5[0]; _t1[5]=_w5[1]; _t2[5]=_w5[2]; _t3[5]=_w5[3]; _t4[5]=_w5[4]; _t5[5]=_w5[5]; } #endif // d = B_t * d_t _n0 = _mm256_mul_ps(_t0, _4_p); _n0 = _mm256_fmadd_ps(_t2, _5_n, _n0); _n0 = _mm256_add_ps(_n0, _t4); _n1 = _mm256_mul_ps(_t1, _4_n); _n1 = _mm256_fmadd_ps(_t2, _4_n, _n1); _n1 = _mm256_add_ps(_n1, _t3); _n1 = _mm256_add_ps(_n1, _t4); _n2 = _mm256_mul_ps(_t1, _4_p); _n2 = _mm256_fmadd_ps(_t2, _4_n, _n2); _n2 = _mm256_fmadd_ps(_t3, _1_n, _n2); _n2 = _mm256_add_ps(_n2, _t4); _n3 = _mm256_mul_ps(_t1, _2_n); _n3 = _mm256_fmadd_ps(_t2, _1_n, _n3); _n3 = _mm256_fmadd_ps(_t3, _2_p, _n3); _n3 = _mm256_add_ps(_n3, _t4); _n4 = _mm256_mul_ps(_t1, _2_p); _n4 = _mm256_fmadd_ps(_t2, _1_n, _n4); _n4 = _mm256_fmadd_ps(_t3, _2_n, _n4); _n4 = _mm256_add_ps(_n4, _t4); _n5 = _mm256_mul_ps(_t1, _4_p); _n5 = _mm256_fmadd_ps(_t3, _5_n, _n5); _n5 = _mm256_add_ps(_n5, _t5); // save to out_tm float output_n0[8] = {0.f};_mm256_storeu_ps(output_n0, _n0); float output_n1[8] = {0.f};_mm256_storeu_ps(output_n1, _n1); float output_n2[8] = {0.f};_mm256_storeu_ps(output_n2, _n2); float output_n3[8] = {0.f};_mm256_storeu_ps(output_n3, _n3); float output_n4[8] = {0.f};_mm256_storeu_ps(output_n4, _n4); float output_n5[8] = {0.f};_mm256_storeu_ps(output_n5, _n5); out_tm0[0]=output_n0[0];out_tm0[1]=output_n0[1];out_tm0[2]=output_n0[2];out_tm0[3]=output_n0[3]; out_tm1[0]=output_n0[4];out_tm1[1]=output_n0[5];out_tm1[2]=output_n1[0];out_tm1[3]=output_n1[1]; out_tm2[0]=output_n1[2];out_tm2[1]=output_n1[3];out_tm2[2]=output_n1[4];out_tm2[3]=output_n1[5]; out_tm3[0]=output_n2[0];out_tm3[1]=output_n2[1];out_tm3[2]=output_n2[2];out_tm3[3]=output_n2[3]; out_tm4[0]=output_n2[4];out_tm4[1]=output_n2[5];out_tm4[2]=output_n3[0];out_tm4[3]=output_n3[1]; out_tm5[0]=output_n3[2];out_tm5[1]=output_n3[3];out_tm5[2]=output_n3[4];out_tm5[3]=output_n3[5]; out_tm6[0]=output_n4[0];out_tm6[1]=output_n4[1];out_tm6[2]=output_n4[2];out_tm6[3]=output_n4[3]; out_tm7[0]=output_n4[4];out_tm7[1]=output_n4[5];out_tm7[2]=output_n5[0];out_tm7[3]=output_n5[1]; out_tm8[0]=output_n5[2];out_tm8[1]=output_n5[3];out_tm8[2]=output_n5[4];out_tm8[3]=output_n5[5]; #else float d0[6],d1[6],d2[6],d3[6],d4[6],d5[6]; float w0[6],w1[6],w2[6],w3[6],w4[6],w5[6]; float t0[6],t1[6],t2[6],t3[6],t4[6],t5[6]; // load for (int n = 0; n < 6; n++) { d0[n] = r0[n]; d1[n] = r1[n]; d2[n] = r2[n]; d3[n] = r3[n]; d4[n] = r4[n]; d5[n] = r5[n]; } // w = B_t * d for (int n = 0; n < 6; n++) { w0[n] = 4*d0[n] - 5*d2[n] + d4[n]; w1[n] = -4*d1[n] - 4*d2[n] + d3[n] + d4[n]; w2[n] = 4*d1[n] - 4*d2[n] - d3[n] + d4[n]; w3[n] = -2*d1[n] - d2[n] + 2*d3[n] + d4[n]; w4[n] = 2*d1[n] - d2[n] - 2*d3[n] + d4[n]; w5[n] = 4*d1[n] - 5*d3[n] + d5[n]; } // transpose d to d_t { t0[0]=w0[0]; t1[0]=w0[1]; t2[0]=w0[2]; t3[0]=w0[3]; t4[0]=w0[4]; t5[0]=w0[5]; t0[1]=w1[0]; t1[1]=w1[1]; t2[1]=w1[2]; t3[1]=w1[3]; t4[1]=w1[4]; t5[1]=w1[5]; t0[2]=w2[0]; t1[2]=w2[1]; t2[2]=w2[2]; t3[2]=w2[3]; t4[2]=w2[4]; t5[2]=w2[5]; t0[3]=w3[0]; t1[3]=w3[1]; t2[3]=w3[2]; t3[3]=w3[3]; t4[3]=w3[4]; t5[3]=w3[5]; t0[4]=w4[0]; t1[4]=w4[1]; t2[4]=w4[2]; t3[4]=w4[3]; t4[4]=w4[4]; t5[4]=w4[5]; t0[5]=w5[0]; t1[5]=w5[1]; t2[5]=w5[2]; t3[5]=w5[3]; t4[5]=w5[4]; t5[5]=w5[5]; } // d = B_t * d_t for (int n = 0; n < 6; n++) { d0[n] = 4*t0[n] - 5*t2[n] + t4[n]; d1[n] = - 4*t1[n] - 4*t2[n] + t3[n] + t4[n]; d2[n] = 4*t1[n] - 4*t2[n] - t3[n] + t4[n]; d3[n] = - 2*t1[n] - t2[n] + 2*t3[n] + t4[n]; d4[n] = 2*t1[n] - t2[n] - 2*t3[n] + t4[n]; d5[n] = 4*t1[n] - 5*t3[n] + t5[n]; } // save to out_tm { out_tm0[0]=d0[0];out_tm0[1]=d0[1];out_tm0[2]=d0[2];out_tm0[3]=d0[3]; out_tm1[0]=d0[4];out_tm1[1]=d0[5];out_tm1[2]=d1[0];out_tm1[3]=d1[1]; out_tm2[0]=d1[2];out_tm2[1]=d1[3];out_tm2[2]=d1[4];out_tm2[3]=d1[5]; out_tm3[0]=d2[0];out_tm3[1]=d2[1];out_tm3[2]=d2[2];out_tm3[3]=d2[3]; out_tm4[0]=d2[4];out_tm4[1]=d2[5];out_tm4[2]=d3[0];out_tm4[3]=d3[1]; out_tm5[0]=d3[2];out_tm5[1]=d3[3];out_tm5[2]=d3[4];out_tm5[3]=d3[5]; out_tm6[0]=d4[0];out_tm6[1]=d4[1];out_tm6[2]=d4[2];out_tm6[3]=d4[3]; out_tm7[0]=d4[4];out_tm7[1]=d4[5];out_tm7[2]=d5[0];out_tm7[3]=d5[1]; out_tm8[0]=d5[2];out_tm8[1]=d5[3];out_tm8[2]=d5[4];out_tm8[3]=d5[5]; } #endif // __AVX__ r0 += 4; r1 += 4; r2 += 4; r3 += 4; r4 += 4; r5 += 4; } } } } bottom_blob_bordered = Mat(); // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; int nColBlocks = h_tm/6; // may be the block num in Feathercnn int nRowBlocks = w_tm/6; const int tiles = nColBlocks * nRowBlocks; top_blob_tm.create(36, tiles, outch, elemsize, opt.workspace_allocator); #pragma omp parallel for num_threads(opt.num_threads) for (int r=0; r<9; r++) { int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 3; remain_outch_start = nn_outch << 3; for (int pp=0; pp<nn_outch; pp++) { int p = pp * 8; float* output0_tm = top_blob_tm.channel(p); float* output1_tm = top_blob_tm.channel(p+1); float* output2_tm = top_blob_tm.channel(p+2); float* output3_tm = top_blob_tm.channel(p+3); float* output4_tm = top_blob_tm.channel(p+4); float* output5_tm = top_blob_tm.channel(p+5); float* output6_tm = top_blob_tm.channel(p+6); float* output7_tm = top_blob_tm.channel(p+7); output0_tm = output0_tm + r*4; output1_tm = output1_tm + r*4; output2_tm = output2_tm + r*4; output3_tm = output3_tm + r*4; output4_tm = output4_tm + r*4; output5_tm = output5_tm + r*4; output6_tm = output6_tm + r*4; output7_tm = output7_tm + r*4; for (int i=0; i<tiles; i++) { const float* kptr = kernel_tm_test[r].channel(p/8); const float* r0 = bottom_blob_tm.channel(tiles*r+i); #if __AVX__ || __SSE__ #if __AVX__ float zero_val = 0.f; __m128 _sum0 = _mm_broadcast_ss(&zero_val); __m128 _sum1 = _mm_broadcast_ss(&zero_val); __m128 _sum2 = _mm_broadcast_ss(&zero_val); __m128 _sum3 = _mm_broadcast_ss(&zero_val); __m128 _sum4 = _mm_broadcast_ss(&zero_val); __m128 _sum5 = _mm_broadcast_ss(&zero_val); __m128 _sum6 = _mm_broadcast_ss(&zero_val); __m128 _sum7 = _mm_broadcast_ss(&zero_val); #else __m128 _sum0 = _mm_set1_ps(0.f); __m128 _sum1 = _mm_set1_ps(0.f); __m128 _sum2 = _mm_set1_ps(0.f); __m128 _sum3 = _mm_set1_ps(0.f); __m128 _sum4 = _mm_set1_ps(0.f); __m128 _sum5 = _mm_set1_ps(0.f); __m128 _sum6 = _mm_set1_ps(0.f); __m128 _sum7 = _mm_set1_ps(0.f); #endif int q=0; for (; q+3<inch; q=q+4) { __m128 _r0 = _mm_loadu_ps(r0); __m128 _r1 = _mm_loadu_ps(r0+4); __m128 _r2 = _mm_loadu_ps(r0+8); __m128 _r3 = _mm_loadu_ps(r0+12); __m128 _k0 = _mm_loadu_ps(kptr); __m128 _k1 = _mm_loadu_ps(kptr+4); __m128 _k2 = _mm_loadu_ps(kptr+8); __m128 _k3 = _mm_loadu_ps(kptr+12); __m128 _k4 = _mm_loadu_ps(kptr+16); __m128 _k5 = _mm_loadu_ps(kptr+20); __m128 _k6 = _mm_loadu_ps(kptr+24); __m128 _k7 = _mm_loadu_ps(kptr+28); #if __AVX__ _sum0 = _mm_fmadd_ps(_r0, _k0, _sum0); _sum1 = _mm_fmadd_ps(_r0, _k1, _sum1); _sum2 = _mm_fmadd_ps(_r0, _k2, _sum2); _sum3 = _mm_fmadd_ps(_r0, _k3, _sum3); _sum4 = _mm_fmadd_ps(_r0, _k4, _sum4); _sum5 = _mm_fmadd_ps(_r0, _k5, _sum5); _sum6 = _mm_fmadd_ps(_r0, _k6, _sum6); _sum7 = _mm_fmadd_ps(_r0, _k7, _sum7); #else _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r0, _k0)); _sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r0, _k1)); _sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r0, _k2)); _sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r0, _k3)); _sum4 = _mm_add_ps(_sum4, _mm_mul_ps(_r0, _k4)); _sum5 = _mm_add_ps(_sum5, _mm_mul_ps(_r0, _k5)); _sum6 = _mm_add_ps(_sum6, _mm_mul_ps(_r0, _k6)); _sum7 = _mm_add_ps(_sum7, _mm_mul_ps(_r0, _k7)); #endif kptr += 32; _k0 = _mm_loadu_ps(kptr); _k1 = _mm_loadu_ps(kptr+4); _k2 = _mm_loadu_ps(kptr+8); _k3 = _mm_loadu_ps(kptr+12); _k4 = _mm_loadu_ps(kptr+16); _k5 = _mm_loadu_ps(kptr+20); _k6 = _mm_loadu_ps(kptr+24); _k7 = _mm_loadu_ps(kptr+28); #if __AVX__ _sum0 = _mm_fmadd_ps(_r1, _k0, _sum0); _sum1 = _mm_fmadd_ps(_r1, _k1, _sum1); _sum2 = _mm_fmadd_ps(_r1, _k2, _sum2); _sum3 = _mm_fmadd_ps(_r1, _k3, _sum3); _sum4 = _mm_fmadd_ps(_r1, _k4, _sum4); _sum5 = _mm_fmadd_ps(_r1, _k5, _sum5); _sum6 = _mm_fmadd_ps(_r1, _k6, _sum6); _sum7 = _mm_fmadd_ps(_r1, _k7, _sum7); #else _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r1, _k0)); _sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r1, _k1)); _sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r1, _k2)); _sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r1, _k3)); _sum4 = _mm_add_ps(_sum4, _mm_mul_ps(_r1, _k4)); _sum5 = _mm_add_ps(_sum5, _mm_mul_ps(_r1, _k5)); _sum6 = _mm_add_ps(_sum6, _mm_mul_ps(_r1, _k6)); _sum7 = _mm_add_ps(_sum7, _mm_mul_ps(_r1, _k7)); #endif kptr += 32; _k0 = _mm_loadu_ps(kptr); _k1 = _mm_loadu_ps(kptr+4); _k2 = _mm_loadu_ps(kptr+8); _k3 = _mm_loadu_ps(kptr+12); _k4 = _mm_loadu_ps(kptr+16); _k5 = _mm_loadu_ps(kptr+20); _k6 = _mm_loadu_ps(kptr+24); _k7 = _mm_loadu_ps(kptr+28); #if __AVX__ _sum0 = _mm_fmadd_ps(_r2, _k0, _sum0); _sum1 = _mm_fmadd_ps(_r2, _k1, _sum1); _sum2 = _mm_fmadd_ps(_r2, _k2, _sum2); _sum3 = _mm_fmadd_ps(_r2, _k3, _sum3); _sum4 = _mm_fmadd_ps(_r2, _k4, _sum4); _sum5 = _mm_fmadd_ps(_r2, _k5, _sum5); _sum6 = _mm_fmadd_ps(_r2, _k6, _sum6); _sum7 = _mm_fmadd_ps(_r2, _k7, _sum7); #else _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r2, _k0)); _sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r2, _k1)); _sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r2, _k2)); _sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r2, _k3)); _sum4 = _mm_add_ps(_sum4, _mm_mul_ps(_r2, _k4)); _sum5 = _mm_add_ps(_sum5, _mm_mul_ps(_r2, _k5)); _sum6 = _mm_add_ps(_sum6, _mm_mul_ps(_r2, _k6)); _sum7 = _mm_add_ps(_sum7, _mm_mul_ps(_r2, _k7)); #endif kptr += 32; _k0 = _mm_loadu_ps(kptr); _k1 = _mm_loadu_ps(kptr+4); _k2 = _mm_loadu_ps(kptr+8); _k3 = _mm_loadu_ps(kptr+12); _k4 = _mm_loadu_ps(kptr+16); _k5 = _mm_loadu_ps(kptr+20); _k6 = _mm_loadu_ps(kptr+24); _k7 = _mm_loadu_ps(kptr+28); #if __AVX__ _sum0 = _mm_fmadd_ps(_r3, _k0, _sum0); _sum1 = _mm_fmadd_ps(_r3, _k1, _sum1); _sum2 = _mm_fmadd_ps(_r3, _k2, _sum2); _sum3 = _mm_fmadd_ps(_r3, _k3, _sum3); _sum4 = _mm_fmadd_ps(_r3, _k4, _sum4); _sum5 = _mm_fmadd_ps(_r3, _k5, _sum5); _sum6 = _mm_fmadd_ps(_r3, _k6, _sum6); _sum7 = _mm_fmadd_ps(_r3, _k7, _sum7); #else _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r3, _k0)); _sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r3, _k1)); _sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r3, _k2)); _sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r3, _k3)); _sum4 = _mm_add_ps(_sum4, _mm_mul_ps(_r3, _k4)); _sum5 = _mm_add_ps(_sum5, _mm_mul_ps(_r3, _k5)); _sum6 = _mm_add_ps(_sum6, _mm_mul_ps(_r3, _k6)); _sum7 = _mm_add_ps(_sum7, _mm_mul_ps(_r3, _k7)); #endif kptr += 32; r0 += 16; } for (; q<inch; q++) { __m128 _r0 = _mm_loadu_ps(r0); __m128 _k0 = _mm_loadu_ps(kptr); __m128 _k1 = _mm_loadu_ps(kptr+4); __m128 _k2 = _mm_loadu_ps(kptr+8); __m128 _k3 = _mm_loadu_ps(kptr+12); __m128 _k4 = _mm_loadu_ps(kptr+16); __m128 _k5 = _mm_loadu_ps(kptr+20); __m128 _k6 = _mm_loadu_ps(kptr+24); __m128 _k7 = _mm_loadu_ps(kptr+28); #if __AVX__ _sum0 = _mm_fmadd_ps(_r0, _k0, _sum0); _sum1 = _mm_fmadd_ps(_r0, _k1, _sum1); _sum2 = _mm_fmadd_ps(_r0, _k2, _sum2); _sum3 = _mm_fmadd_ps(_r0, _k3, _sum3); _sum4 = _mm_fmadd_ps(_r0, _k4, _sum4); _sum5 = _mm_fmadd_ps(_r0, _k5, _sum5); _sum6 = _mm_fmadd_ps(_r0, _k6, _sum6); _sum7 = _mm_fmadd_ps(_r0, _k7, _sum7); #else _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r0, _k0)); _sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r0, _k1)); _sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r0, _k2)); _sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r0, _k3)); _sum4 = _mm_add_ps(_sum4, _mm_mul_ps(_r0, _k4)); _sum5 = _mm_add_ps(_sum5, _mm_mul_ps(_r0, _k5)); _sum6 = _mm_add_ps(_sum6, _mm_mul_ps(_r0, _k6)); _sum7 = _mm_add_ps(_sum7, _mm_mul_ps(_r0, _k7)); #endif kptr += 32; r0 += 4; } _mm_storeu_ps(output0_tm, _sum0); _mm_storeu_ps(output1_tm, _sum1); _mm_storeu_ps(output2_tm, _sum2); _mm_storeu_ps(output3_tm, _sum3); _mm_storeu_ps(output4_tm, _sum4); _mm_storeu_ps(output5_tm, _sum5); _mm_storeu_ps(output6_tm, _sum6); _mm_storeu_ps(output7_tm, _sum7); #else float sum0[4] = {0}; float sum1[4] = {0}; float sum2[4] = {0}; float sum3[4] = {0}; float sum4[4] = {0}; float sum5[4] = {0}; float sum6[4] = {0}; float sum7[4] = {0}; for (int q=0; q<inch; q++) { for (int n=0; n<4; n++) { sum0[n] += r0[n] * kptr[n]; sum1[n] += r0[n] * kptr[n+4]; sum2[n] += r0[n] * kptr[n+8]; sum3[n] += r0[n] * kptr[n+12]; sum4[n] += r0[n] * kptr[n+16]; sum5[n] += r0[n] * kptr[n+20]; sum6[n] += r0[n] * kptr[n+24]; sum7[n] += r0[n] * kptr[n+28]; } kptr += 32; r0 += 4; } for (int n=0; n<4; n++) { output0_tm[n] = sum0[n]; output1_tm[n] = sum1[n]; output2_tm[n] = sum2[n]; output3_tm[n] = sum3[n]; output4_tm[n] = sum4[n]; output5_tm[n] = sum5[n]; output6_tm[n] = sum6[n]; output7_tm[n] = sum7[n]; } #endif // __AVX__ output0_tm += 36; output1_tm += 36; output2_tm += 36; output3_tm += 36; output4_tm += 36; output5_tm += 36; output6_tm += 36; output7_tm += 36; } } nn_outch = (outch - remain_outch_start) >> 2; for (int pp=0; pp<nn_outch; pp++) { int p = remain_outch_start + pp * 4; float* output0_tm = top_blob_tm.channel(p); float* output1_tm = top_blob_tm.channel(p+1); float* output2_tm = top_blob_tm.channel(p+2); float* output3_tm = top_blob_tm.channel(p+3); output0_tm = output0_tm + r*4; output1_tm = output1_tm + r*4; output2_tm = output2_tm + r*4; output3_tm = output3_tm + r*4; for (int i=0; i<tiles; i++) { const float* kptr = kernel_tm_test[r].channel(p/8 + (p%8)/4); const float* r0 = bottom_blob_tm.channel(tiles*r+i); #if __AVX__ || __SSE__ #if __AVX__ float zero_val = 0.f; __m128 _sum0 = _mm_broadcast_ss(&zero_val); __m128 _sum1 = _mm_broadcast_ss(&zero_val); __m128 _sum2 = _mm_broadcast_ss(&zero_val); __m128 _sum3 = _mm_broadcast_ss(&zero_val); #else __m128 _sum0 = _mm_set1_ps(0.f); __m128 _sum1 = _mm_set1_ps(0.f); __m128 _sum2 = _mm_set1_ps(0.f); __m128 _sum3 = _mm_set1_ps(0.f); #endif for (int q=0; q<inch; q++) { __m128 _r0 = _mm_loadu_ps(r0); __m128 _k0 = _mm_loadu_ps(kptr); __m128 _k1 = _mm_loadu_ps(kptr+4); __m128 _k2 = _mm_loadu_ps(kptr+8); __m128 _k3 = _mm_loadu_ps(kptr+12); #if __AVX__ _sum0 = _mm_fmadd_ps(_r0, _k0, _sum0); _sum1 = _mm_fmadd_ps(_r0, _k1, _sum1); _sum2 = _mm_fmadd_ps(_r0, _k2, _sum2); _sum3 = _mm_fmadd_ps(_r0, _k3, _sum3); #else _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r0, _k0)); _sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r0, _k1)); _sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r0, _k2)); _sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r0, _k3)); #endif kptr += 16; r0 += 4; } _mm_storeu_ps(output0_tm, _sum0); _mm_storeu_ps(output1_tm, _sum1); _mm_storeu_ps(output2_tm, _sum2); _mm_storeu_ps(output3_tm, _sum3); #else float sum0[4] = {0}; float sum1[4] = {0}; float sum2[4] = {0}; float sum3[4] = {0}; for (int q=0; q<inch; q++) { for (int n=0; n<4; n++) { sum0[n] += r0[n] * kptr[n]; sum1[n] += r0[n] * kptr[n+4]; sum2[n] += r0[n] * kptr[n+8]; sum3[n] += r0[n] * kptr[n+12]; } kptr += 16; r0 += 4; } for (int n=0; n<4; n++) { output0_tm[n] = sum0[n]; output1_tm[n] = sum1[n]; output2_tm[n] = sum2[n]; output3_tm[n] = sum3[n]; } #endif // __AVX__ output0_tm += 36; output1_tm += 36; output2_tm += 36; output3_tm += 36; } } remain_outch_start += nn_outch << 2; for (int p=remain_outch_start; p<outch; p++) { float* output0_tm = top_blob_tm.channel(p); output0_tm = output0_tm + r*4; for (int i=0; i<tiles; i++) { const float* kptr = kernel_tm_test[r].channel(p/8 + (p%8)/4 + p%4); const float* r0 = bottom_blob_tm.channel(tiles*r+i); #if __AVX__ || __SSE__ #if __AVX__ float zero_val = 0.f; __m128 _sum0 = _mm_broadcast_ss(&zero_val); #else __m128 _sum0 = _mm_set1_ps(0.f); #endif for (int q=0; q<inch; q++) { __m128 _r0 = _mm_loadu_ps(r0); __m128 _k0 = _mm_loadu_ps(kptr); #if __AVX__ _sum0 = _mm_fmadd_ps(_r0, _k0, _sum0); #else _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r0, _k0)); #endif kptr += 16; r0 += 4; } _mm_storeu_ps(output0_tm, _sum0); #else float sum0[4] = {0}; for (int q=0; q<inch; q++) { for (int n=0; n<4; n++) { sum0[n] += (int)r0[n] * kptr[n]; } kptr += 4; r0 += 4; } for (int n=0; n<4; n++) { output0_tm[n] = sum0[n]; } #endif // __AVX__ || __SSE__ output0_tm += 36; } } // for (int p=0; p<outch; p++) // { // Mat out0_tm = top_blob_tm.channel(p); // const Mat kernel0_tm = kernel_tm.channel(p); // for (int i=0; i<tiles; i++) // { // float* output0_tm = out0_tm.row<int>(i); // int sum0[36] = {0}; // for (int q=0; q<inch; q++) // { // const float* r0 = bottom_blob_tm.channel(q).row<float>(i); // const float* k0 = kernel0_tm.row<float>(q); // for (int n=0; n<36; n++) // { // sum0[n] += (int)r0[n] * k0[n]; // } // } // for (int n=0; n<36; n++) // { // output0_tm[n] = sum0[n]; // } // } // } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; top_blob_bordered.create(outw, outh, outch, elemsize, opt.workspace_allocator); { // AT // const float itm[4][6] = { // {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 1.0f} // }; // 0 = r00 + r01 + r02 + r03 + r04 // 1 = r01 - r02 + 2 * (r03 - r04) // 2 = r01 + r02 + 4 * (r03 + r04) // 3 = r01 - r02 + 8 * (r03 - r04) + r05 int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; int nColBlocks = h_tm/6; // may be the block num in Feathercnn int nRowBlocks = w_tm/6; #pragma omp parallel for num_threads(opt.num_threads) for (int p=0; p<outch; p++) { float* out_tile = top_blob_tm.channel(p); float* outRow0 = top_blob_bordered.channel(p); float* outRow1 = outRow0 + outw; float* outRow2 = outRow0 + outw * 2; float* outRow3 = outRow0 + outw * 3; const float bias0 = bias ? bias[p] : 0.f; for (int j=0; j<nColBlocks; j++) { for(int i=0; i<nRowBlocks; i++) { // TODO AVX2 float s0[6],s1[6],s2[6],s3[6],s4[6],s5[6]; float w0[6],w1[6],w2[6],w3[6]; float d0[4],d1[4],d2[4],d3[4],d4[4],d5[4]; float o0[4],o1[4],o2[4],o3[4]; // load for (int n = 0; n < 6; n++) { s0[n] = out_tile[n]; s1[n] = out_tile[n+ 6]; s2[n] = out_tile[n+12]; s3[n] = out_tile[n+18]; s4[n] = out_tile[n+24]; s5[n] = out_tile[n+30]; } // w = A_T * W for (int n = 0; n < 6; n++) { w0[n] = s0[n] + s1[n] + s2[n] + s3[n] + s4[n]; w1[n] = s1[n] - s2[n] + 2*s3[n] - 2*s4[n]; w2[n] = s1[n] + s2[n] + 4*s3[n] + 4*s4[n]; w3[n] = s1[n] - s2[n] + 8*s3[n] - 8*s4[n] + s5[n]; } // transpose w to w_t { d0[0] = w0[0]; d0[1] = w1[0]; d0[2] = w2[0]; d0[3] = w3[0]; d1[0] = w0[1]; d1[1] = w1[1]; d1[2] = w2[1]; d1[3] = w3[1]; d2[0] = w0[2]; d2[1] = w1[2]; d2[2] = w2[2]; d2[3] = w3[2]; d3[0] = w0[3]; d3[1] = w1[3]; d3[2] = w2[3]; d3[3] = w3[3]; d4[0] = w0[4]; d4[1] = w1[4]; d4[2] = w2[4]; d4[3] = w3[4]; d5[0] = w0[5]; d5[1] = w1[5]; d5[2] = w2[5]; d5[3] = w3[5]; } // Y = A_T * w_t for (int n = 0; n < 4; n++) { o0[n] = d0[n] + d1[n] + d2[n] + d3[n] + d4[n]; o1[n] = d1[n] - d2[n] + 2*d3[n] - 2*d4[n]; o2[n] = d1[n] + d2[n] + 4*d3[n] + 4*d4[n]; o3[n] = d1[n] - d2[n] + 8*d3[n] - 8*d4[n] + d5[n]; } // save to top blob tm for (int n = 0; n < 4; n++) { outRow0[n] = o0[n] + bias0; outRow1[n] = o1[n] + bias0; outRow2[n] = o2[n] + bias0; outRow3[n] = o3[n] + bias0; } out_tile += 36; outRow0 += 4; outRow1 += 4; outRow2 += 4; outRow3 += 4; } outRow0 += outw * 3; outRow1 += outw * 3; outRow2 += outw * 3; outRow3 += outw * 3; } } } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt); } static void conv3x3s2_sse(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2 * outw + w; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); for (int q = 0; q < inch; q++) { float *outptr = out; const float *img = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch*9 + q*9; const float *r0 = img; const float *r1 = img + w; const float *r2 = img + w * 2; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; for (int i = 0; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { float sum = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr += sum; r0 += 2; r1 += 2; r2 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } } } }
depthwise_conv2d.h
// Copyright 2018 Xiaomi, Inc. All rights reserved. // // 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 MACE_KERNELS_DEPTHWISE_CONV2D_H_ #define MACE_KERNELS_DEPTHWISE_CONV2D_H_ #if defined(MACE_ENABLE_NEON) && defined(__aarch64__) #include <arm_neon.h> #endif #include <algorithm> #include <memory> #include <vector> #include "mace/core/future.h" #include "mace/kernels/conv_pool_2d_util.h" #include "mace/kernels/activation.h" #include "mace/kernels/arm/depthwise_conv2d_neon.h" #include "mace/public/mace.h" #ifdef MACE_ENABLE_OPENCL #include "mace/core/runtime/opencl/cl2_header.h" #endif // MACE_ENABLE_OPENCL namespace mace { namespace kernels { struct DepthwiseConv2dFunctorBase { DepthwiseConv2dFunctorBase(const int *strides, const Padding padding_type, const std::vector<int> &paddings, const int *dilations, const ActivationType activation, const float relux_max_limit) : strides_(strides), padding_type_(padding_type), paddings_(paddings), dilations_(dilations), activation_(activation), relux_max_limit_(relux_max_limit) {} const int *strides_; // [stride_h, stride_w] const Padding padding_type_; std::vector<int> paddings_; const int *dilations_; // [dilation_h, dilation_w] const ActivationType activation_; const float relux_max_limit_; }; template<DeviceType D, typename T> struct DepthwiseConv2dFunctor; template<> struct DepthwiseConv2dFunctor<DeviceType::CPU, float> : public DepthwiseConv2dFunctorBase { DepthwiseConv2dFunctor(const int *strides, const Padding padding_type, const std::vector<int> &paddings, const int *dilations, const ActivationType activation, const float relux_max_limit) : DepthwiseConv2dFunctorBase(strides, padding_type, paddings, dilations, activation, relux_max_limit) {} void DepthwiseConv2dGeneral(const float *input, const float *filter, const index_t *in_shape, const index_t *out_shape, const index_t *filter_shape, const int *stride_hw, const int *dilation_hw, const int *pad_hw, float *output) { const index_t multiplier = filter_shape[0] / filter_shape[1]; #pragma omp parallel for collapse(2) for (index_t b = 0; b < in_shape[0]; ++b) { for (index_t m = 0; m < filter_shape[0]; ++m) { for (index_t h = 0; h < out_shape[2]; ++h) { for (index_t w = 0; w < out_shape[3]; ++w) { const index_t out_channels = filter_shape[0]; const index_t in_channels = filter_shape[1]; const index_t filter_height = filter_shape[2]; const index_t filter_width = filter_shape[3]; const index_t in_height = in_shape[2]; const index_t in_width = in_shape[3]; const index_t out_height = out_shape[2]; const index_t out_width = out_shape[3]; index_t out_offset = ((b * out_channels + m) * out_height + h) * out_width + w; index_t c = m / multiplier; index_t o = m % multiplier; float sum = 0; for (index_t kh = 0; kh < filter_height; ++kh) { for (index_t kw = 0; kw < filter_width; ++kw) { index_t ih = h * stride_hw[0] + kh * dilation_hw[0] - pad_hw[0]; index_t iw = w * stride_hw[1] + kw * dilation_hw[1] - pad_hw[1]; if (ih >= 0 && ih < in_height && iw >= 0 && iw < in_width) { index_t in_offset = ((b * in_channels + c) * in_height + ih) * in_width + iw; index_t filter_offset = (((o * in_channels) + c) * filter_height + kh) * filter_width + kw; sum += input[in_offset] * filter[filter_offset]; } } } output[out_offset] = sum; } } } } } MaceStatus operator()(const Tensor *input, const Tensor *filter, const Tensor *bias, Tensor *output, StatsFuture *future) { MACE_UNUSED(future); MACE_CHECK_NOTNULL(input); MACE_CHECK_NOTNULL(filter); MACE_CHECK_NOTNULL(output); std::vector<index_t> output_shape(4); std::vector<int> paddings(2); std::vector<index_t> filter_shape {filter->dim(0) * filter->dim(1), filter->dim(1), filter->dim(2), filter->dim(3)}; if (paddings_.empty()) { CalcNCHWPaddingAndOutputSize(input->shape().data(), filter_shape.data(), dilations_, strides_, padding_type_, output_shape.data(), paddings.data()); } else { paddings = paddings_; CalcNCHWOutputSize(input->shape().data(), filter_shape.data(), paddings_.data(), dilations_, strides_, RoundType::FLOOR, output_shape.data()); } MACE_RETURN_IF_ERROR(output->Resize(output_shape)); output->Clear(); index_t batch = output->dim(0); index_t channels = output->dim(1); index_t height = output->dim(2); index_t width = output->dim(3); index_t input_batch = input->dim(0); index_t input_channels = input->dim(1); index_t input_height = input->dim(2); index_t input_width = input->dim(3); index_t filter_h = filter_shape[2]; index_t filter_w = filter_shape[3]; MACE_CHECK(filter_shape[0] == channels, filter_shape[0], " != ", channels); MACE_CHECK(filter_shape[1] == input_channels, filter_shape[1], " != ", input_channels); index_t stride_h = strides_[0]; index_t stride_w = strides_[1]; index_t dilation_h = dilations_[0]; index_t dilation_w = dilations_[1]; MACE_CHECK(batch == input_batch, "Input/Output batch size mismatch"); int pad_top = paddings[0] >> 1; int pad_bottom = paddings[0] - pad_top; int pad_left = paddings[1] >> 1; int pad_right = paddings[1] - pad_left; index_t valid_h_start = pad_top == 0 ? 0 : (pad_top - 1) / stride_h + 1; index_t valid_h_stop = pad_bottom == 0 ? height : height - ((pad_bottom - 1) / stride_h + 1); index_t valid_w_start = pad_left == 0 ? 0 : (pad_left - 1) / stride_w + 1; index_t valid_w_stop = pad_right == 0 ? width : width - ((pad_right - 1) / stride_w + 1); std::function<void(const float *input, float *output)> conv_func; Tensor::MappingGuard input_guard(input); Tensor::MappingGuard filter_guard(filter); Tensor::MappingGuard bias_guard(bias); Tensor::MappingGuard output_guard(output); auto input_data = input->data<float>(); auto filter_data = filter->data<float>(); auto bias_data = bias == nullptr ? nullptr : bias->data<float>(); auto output_data = output->mutable_data<float>(); const int pad_hw[2] = {pad_top, pad_left}; const index_t input_shape[4] = {batch, input_channels, input_height, input_width}; if (filter_h == 3 && filter_w == 3 && stride_h == 1 && stride_w == 1 && dilation_h == 1 && dilation_w == 1) { conv_func = [=](const float *input, float *output) { DepthwiseConv2dNeonK3x3S1(input, filter_data, input_shape, output_shape.data(), pad_hw, valid_h_start, valid_h_stop, valid_w_start, valid_w_stop, output); }; } else if (filter_h == 3 && filter_w == 3 && stride_h == 2 && stride_w == 2 && dilation_h == 1 && dilation_w == 1) { conv_func = [=](const float *input, float *output) { DepthwiseConv2dNeonK3x3S2(input, filter_data, input_shape, output_shape.data(), pad_hw, valid_h_start, valid_h_stop, valid_w_start, valid_w_stop, output); }; } else { conv_func = [=](const float *input, float *output) { DepthwiseConv2dGeneral(input, filter_data, input_shape, output_shape.data(), filter_shape.data(), strides_, dilations_, pad_hw, output); }; } conv_func(input_data, output_data); if (bias_data != nullptr) { #pragma omp parallel for collapse(2) for (index_t b = 0; b < batch; ++b) { for (index_t c = 0; c < channels; ++c) { for (index_t i = 0; i < height * width; ++i) { output_data[(b * channels + c) * height * width + i] += bias_data[c]; } } } } DoActivation(output_data, output_data, output->size(), activation_, relux_max_limit_); return MACE_SUCCESS; } }; #ifdef MACE_ENABLE_OPENCL template<typename T> struct DepthwiseConv2dFunctor<DeviceType::GPU, T> : DepthwiseConv2dFunctorBase { DepthwiseConv2dFunctor(const int *strides, const Padding padding_type, const std::vector<int> &paddings, const int *dilations, const ActivationType activation, const float relux_max_limit) : DepthwiseConv2dFunctorBase(strides, padding_type, paddings, dilations, activation, relux_max_limit) {} MaceStatus operator()(const Tensor *input, const Tensor *filter, const Tensor *bias, Tensor *output, StatsFuture *future); cl::Kernel kernel_; uint32_t kwg_size_; std::unique_ptr<BufferBase> kernel_error_; std::vector<index_t> input_shape_; }; #endif // MACE_ENABLE_OPENCL } // namespace kernels } // namespace mace #endif // MACE_KERNELS_DEPTHWISE_CONV2D_H_
directives.c
#include <stdio.h> #include <omp.h> int main() { size_t id, amount = omp_get_num_threads(); printf("Defined number of threads: %li\n", amount); size_t start = omp_get_wtime(); #pragma omp parallel num_threads(4) { amount = omp_get_num_threads(); id = omp_get_thread_num(); printf("Current number: %li out of %li\n", id, amount); } size_t end = omp_get_wtime(); printf("Time elapsed: %zu\n", end - start); return 0; }
declare_variant_mixed_codegen.c
// RUN: %clang_cc1 -verify -fopenmp -x c -triple x86_64-unknown-linux -emit-llvm %s -o - | FileCheck %s --check-prefix HOST // RUN: %clang_cc1 -fopenmp -x c -triple x86_64-unknown-linux -emit-pch -o %t -fopenmp-version=50 %s // RUN: %clang_cc1 -fopenmp -x c -triple x86_64-unknown-linux -include-pch %t -verify %s -emit-llvm -o - -fopenmp-version=50 | FileCheck %s --check-prefix HOST // RUN: %clang_cc1 -verify -fopenmp -x c -triple powerpc64le-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm-bc %s -o %t-ppc-host.bc -fopenmp-version=50 // RUN: %clang_cc1 -verify -fopenmp -x c -triple nvptx64-unknown-unknown -aux-triple powerpc64le-unknown-unknown -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - -fopenmp-version=50 | FileCheck %s --check-prefix GPU // RUN: %clang_cc1 -verify -fopenmp -x c -triple nvptx64-unknown-unknown -aux-triple powerpc64le-unknown-unknown -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -emit-pch -o %t -fopenmp-version=50 // RUN: %clang_cc1 -verify -fopenmp -x c -triple nvptx64-unknown-unknown -aux-triple powerpc64le-unknown-unknown -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -include-pch %t -o - -fopenmp-version=50 | FileCheck %s --check-prefix GPU // expected-no-diagnostics #ifndef HEADER #define HEADER int dev(double i) { return 0; } int hst(double i) { return 1; } #pragma omp declare variant(hst) match(device = {kind(host)}) #pragma omp declare variant(dev) match(device = {kind(gpu)}) int base(); // HOST-LABEL: define void @foo() // HOST: call i32 @hst(double -1.000000e+00) // HOST: call i32 @hst(double -2.000000e+00) // HOST: call void [[OFFL:@.+_foo_l28]]() void foo() { base(-1); hst(-2); #pragma omp target { base(-3); dev(-4); } } // HOST: define {{.*}}void [[OFFL]]() // HOST: call i32 @hst(double -3.000000e+00) // HOST: call i32 @dev(double -4.000000e+00) // GPU: define {{.*}}void @__omp_offloading_{{.+}}_foo_l28() // GPU: call i32 @dev(double -3.000000e+00) // GPU: call i32 @dev(double -4.000000e+00) // GPU-NOT: @base // GPU: define {{.*}}i32 @dev(double // GPU: ret i32 0 #endif // HEADER
3d25pt.c
/* * Order-2, 3D 25 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) #ifndef min #define min(x,y) ((x) < (y)? (x) : (y)) #endif /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); double ***roc2 = (double ***) malloc(sizeof(double**)); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); roc2 = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); roc2[i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); roc2[i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 8; tile_size[1] = 8; tile_size[2] = 8; tile_size[3] = 32; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); roc2[i][j][k] = 2.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif const double coef0 = -0.28472; const double coef1 = 0.16000; const double coef2 = -0.02000; const double coef3 = 0.00254; const double coef4 = -0.00018; for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt; t++) { for (i = 4; i < Nz-4; i++) { for (j = 4; j < Ny-4; j++) { for (k = 4; k < Nx-4; k++) { A[(t+1)%2][i][j][k] = 2.0*A[t%2][i][j][k] - A[(t+1)%2][i][j][k] + roc2[i][j][k]*( coef0* A[t%2][i ][j ][k ] + coef1*(A[t%2][i-1][j ][k ] + A[t%2][i+1][j ][k ] + A[t%2][i ][j-1][k ] + A[t%2][i ][j+1][k ] + A[t%2][i ][j ][k-1] + A[t%2][i ][j ][k+1]) + coef2*(A[t%2][i-2][j ][k ] + A[t%2][i+2][j ][k ] + A[t%2][i ][j-2][k ] + A[t%2][i ][j+2][k ] + A[t%2][i ][j ][k-2] + A[t%2][i ][j ][k+2]) + coef3*(A[t%2][i-3][j ][k ] + A[t%2][i+3][j ][k ] + A[t%2][i ][j-3][k ] + A[t%2][i ][j+3][k ] + A[t%2][i ][j ][k-3] + A[t%2][i ][j ][k+3]) + coef4*(A[t%2][i-4][j ][k ] + A[t%2][i+4][j ][k ] + A[t%2][i ][j-4][k ] + A[t%2][i ][j+4][k ] + A[t%2][i ][j ][k-4] + A[t%2][i ][j ][k+4]) ); } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = MIN(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); free(roc2[i][j]); } free(A[0][i]); free(A[1][i]); free(roc2[i]); } free(A[0]); free(A[1]); free(roc2); return 0; }
declare-target-5.c
#pragma omp declare target void foo (void); /* { dg-error "'#pragma omp declare target' without corresponding '#pragma omp end declare target'" } */
GB_binop__bget_int8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__bget_int8) // A.*B function (eWiseMult): GB (_AemultB_08__bget_int8) // A.*B function (eWiseMult): GB (_AemultB_02__bget_int8) // A.*B function (eWiseMult): GB (_AemultB_04__bget_int8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bget_int8) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__bget_int8) // C+=b function (dense accum): GB (_Cdense_accumb__bget_int8) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bget_int8) // C=scalar+B GB (_bind1st__bget_int8) // C=scalar+B' GB (_bind1st_tran__bget_int8) // C=A+scalar GB (_bind2nd__bget_int8) // C=A'+scalar GB (_bind2nd_tran__bget_int8) // C type: int8_t // A type: int8_t // A pattern? 0 // B type: int8_t // B pattern? 0 // BinaryOp: cij = GB_BITGET (aij, bij, int8_t, 8) #define GB_ATYPE \ int8_t #define GB_BTYPE \ int8_t #define GB_CTYPE \ int8_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int8_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int8_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_BITGET (x, y, int8_t, 8) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 1 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BGET || GxB_NO_INT8 || GxB_NO_BGET_INT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__bget_int8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__bget_int8) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__bget_int8) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int8_t int8_t bwork = (*((int8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t *restrict Cx = (int8_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t *restrict Cx = (int8_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__bget_int8) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; int8_t alpha_scalar ; int8_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int8_t *) alpha_scalar_in)) ; beta_scalar = (*((int8_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__bget_int8) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__bget_int8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__bget_int8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__bget_int8) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__bget_int8) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t *Cx = (int8_t *) Cx_output ; int8_t x = (*((int8_t *) x_input)) ; int8_t *Bx = (int8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int8_t bij = GBX (Bx, p, false) ; Cx [p] = GB_BITGET (x, bij, int8_t, 8) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bget_int8) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int8_t *Cx = (int8_t *) Cx_output ; int8_t *Ax = (int8_t *) Ax_input ; int8_t y = (*((int8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int8_t aij = GBX (Ax, p, false) ; Cx [p] = GB_BITGET (aij, y, int8_t, 8) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_BITGET (x, aij, int8_t, 8) ; \ } GrB_Info GB (_bind1st_tran__bget_int8) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t x = (*((const int8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_BITGET (aij, y, int8_t, 8) ; \ } GrB_Info GB (_bind2nd_tran__bget_int8) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t y = (*((const int8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unaryop__ainv_uint32_int64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__ainv_uint32_int64 // op(A') function: GB_tran__ainv_uint32_int64 // C type: uint32_t // A type: int64_t // cast: uint32_t cij = (uint32_t) aij // unaryop: cij = -aij #define GB_ATYPE \ int64_t #define GB_CTYPE \ uint32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = -x ; // casting #define GB_CASTING(z, x) \ uint32_t z = (uint32_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_AINV || GxB_NO_UINT32 || GxB_NO_INT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__ainv_uint32_int64 ( uint32_t *restrict Cx, const int64_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__ainv_uint32_int64 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
fusedmmh.h
#ifndef DGL_ARRAY_CPU_FUSEDMMH_H_ #define DGL_ARRAY_CPU_FUSEDMMH_H_ #include <dgl/array.h> #include <dgl/bcast.h> #include <math.h> #include <iostream> #include <omp.h> #include "../selector.h" #include "sddmm.h" //#include "./FusedMM/kernels/include/kernels.h" #include "./FusedMM/fusedMM.h" //#include "fusedMM.h" #define SM_TABLE_SIZE 2048 #define SM_BOUND 5.0 #define SM_RESOLUTION SM_TABLE_SIZE/(2.0 * SM_BOUND) using namespace std; VALUETYPE *SM_TABLE; void uinit_SM_TABLE() { VALUETYPE x; SM_TABLE = (VALUETYPE*)malloc(SM_TABLE_SIZE*sizeof(VALUETYPE)); assert(SM_TABLE); for(INDEXTYPE i = 0; i < SM_TABLE_SIZE; i++) { x = 2.0 * SM_BOUND * i / SM_TABLE_SIZE - SM_BOUND; SM_TABLE[i] = 1.0 / (1 + exp(-x)); } } inline VALUETYPE uscale_SM(VALUETYPE val) { VALUETYPE sval; /* hopefully compiler will figure out and replace it max min instruction */ sval = (val > SM_BOUND) ? SM_BOUND : val; sval = (val < -SM_BOUND) ? -SM_BOUND : val; return(sval); } VALUETYPE ufast_SM(VALUETYPE v) { if (v > SM_BOUND) return 1.0; else if (v < -SM_BOUND) return 0.0; return SM_TABLE[(INDEXTYPE)((v + SM_BOUND) * SM_RESOLUTION)]; } int SOP_UDEF_FUNC(VALUETYPE val, VALUETYPE &out) { out = 1.0 - ufast_SM(val); return FUSEDMM_SUCCESS_RETURN; } VALUETYPE scale(VALUETYPE v){ if(v > SM_BOUND) return SM_BOUND; else if(v < -SM_BOUND) return -SM_BOUND; return v; } namespace dgl { namespace aten { namespace cpu { template <typename DType> DType scale(DType v){ if(v > SM_BOUND) return SM_BOUND; else if(v < -SM_BOUND) return -SM_BOUND; return v; } template <typename DType> DType fast_SM(DType v, DType *sm_table){ if(v > SM_BOUND) return 1.0; else if(v < -SM_BOUND) return 0.0; return sm_table[(int)((v + SM_BOUND) * SM_RESOLUTION)]; } template <typename IdType, typename DType> void init_SM_TABLE(DType *sm_table){ DType x; for(IdType i = 0; i < SM_TABLE_SIZE; i++){ x = 2.0 * SM_BOUND * i / SM_TABLE_SIZE - SM_BOUND; sm_table[i] = 1.0 / (1 + exp(-x)); } } template <typename IdType, typename DType> void FUSEDMMCsrTdist(const IdType *indptr, const IdType *indices, const IdType *edges, const DType *X, const DType *Y, DType *O, const IdType N, const int64_t dim) { #pragma omp parallel for for (IdType rid = 0; rid < N; ++rid) { const IdType row_start = indptr[rid], row_end = indptr[rid + 1]; const IdType iindex = rid * dim; DType T[dim]; for (IdType j = row_start; j < row_end; ++j){ const IdType cid = indices[j]; const IdType jindex = cid * dim; DType attrc = 0; for (int64_t k = 0; k < dim; ++k) { T[k] = X[iindex + k] - Y[jindex + k]; attrc += T[k] * T[k]; } DType d1 = -2.0 / (1.0 + attrc); for (int64_t k = 0; k < dim; ++k) { T[k] = scale<DType>(T[k] * d1); O[iindex+k] = O[iindex+k] + T[k]; } } } } template <typename IdType, typename DType> void FUSEDMMCsrSigmoid(const IdType *indptr, const IdType *indices, const IdType *edges, const DType *X, const DType *Y, DType *O, const IdType N, const int64_t dim) { DType *sm_table; sm_table = static_cast<DType *> (::operator new (sizeof(DType[SM_TABLE_SIZE]))); init_SM_TABLE<IdType, DType>(sm_table); cout << "Calling FUSEDMMCsrSigmoid..." << indptr[0] << ":" << indices[0] << ":" << edges[0] << ":" << X[0] << endl; #pragma omp parallel for for (IdType rid = 0; rid < N; ++rid){ const IdType row_start = indptr[rid], row_end = indptr[rid + 1]; const IdType iindex = rid * dim; for (IdType j = row_start; j < row_end; ++j){ const IdType cid = indices[j]; const IdType jindex = cid * dim; DType attrc = 0; for (int64_t k = 0; k < dim; ++k) { attrc += X[iindex + k] * X[jindex + k]; } DType d1 = 0.5;//fast_SM<DType>(attrc, sm_table); for (int64_t k = 0; k < dim; ++k) { O[iindex+k] = O[iindex+k] + (1.0 - d1) * X[jindex + k]; } } } cout << "End of Calling FUSEDMMCsrSigmoid..." << endl; } template <typename IdType, typename DType> void FUSEDMMCsrGCN(const IdType *indptr, const IdType *indices, const IdType *edges, const DType *X, const DType *Y, DType *O, const IdType N, const int64_t dim) { cout << "Calling FUSEDMMCsrGCN..." << indptr[0] << ":" << indices[0] << ":" << edges[0] << ":" << X[0] << endl; #pragma omp parallel for for (IdType rid = 0; rid < N; ++rid){ const IdType row_start = indptr[rid], row_end = indptr[rid + 1]; const IdType iindex = rid * dim; for (IdType j = row_start; j < row_end; ++j){ const IdType cid = indices[j]; const IdType jindex = cid * dim; for (int64_t k = 0; k < dim; ++k) { O[iindex+k] = O[iindex+k] + X[jindex + k]; } } } cout << "End of Calling FUSEDMMCsrGCN..." << endl; } template <typename IdType, typename DType> void FUSEDMMCsr(const BcastOff& bcast, const CSRMatrix& csr, NDArray lhs, NDArray rhs, NDArray out, int ftype = 1) { const IdType* indptr = csr.indptr.Ptr<IdType>(); const IdType* indices = csr.indices.Ptr<IdType>(); const IdType* edges = csr.data.Ptr<IdType>(); const DType* X = lhs.Ptr<DType>(); const DType* Y = rhs.Ptr<DType>(); const int32_t dim = bcast.out_len; std::cout << "From FusedMMCsr function...(dim):" << dim << ", num_rows:" << csr.num_rows << endl; DType* O = out.Ptr<DType>(); FUSEDMMCsrGCN<IdType, DType>(indptr, indices, edges, X, Y, O, csr.num_rows, dim); std::cout << "Returning from FusedMMCsr function..." << endl; /* if(ftype == 1){ uinit_SM_TABLE(); int32_t imsg; imsg = VOP_COPY_RHS | ROP_DOT | SOP_UDEF | VSC_MUL | AOP_ADD; fusedMM_csr(imsg, csr.num_rows, csr.num_rows, dim, 1.0, 0.0, csr.num_rows, csr.num_rows, NULL, (const long int*)indices, (const long int*)indptr, (const long int*)indptr+1, (const float*)X, dim, (const float*)Y, dim, 1.0, (float*)O, dim); }else{ int32_t imsg; imsg = VOP_SUBR | ROP_UDEF | SOP_UDEF | VSC_MUL | AOP_ADD; fusedMM_csr(imsg, csr.num_rows, csr.num_rows, dim, 1.0, 0.0, csr.num_rows, csr.num_rows, NULL, (const long int*)indices, (const long int*)indptr, (const long int*)indptr+1, (const float*)X, dim, (const float*)Y, dim, 1.0, (float*)O, dim); } */ } } } } #endif
fc_compute.h
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. 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. */ #pragma once #include "paddle/fluid/operators/jit/kernels.h" #include "paddle/fluid/operators/math/blas.h" namespace paddle { namespace operators { namespace math { template <typename DeviceContext, typename T> inline void FCCompute(const BlasT<DeviceContext, T>& blas, const int M, const int N, const int K, const T* X, const T* W, T* Y, const T* B = NULL, bool relu = false) { blas.MatMul(M, N, K, X, W, Y); if (B == NULL) { return; } if (relu) { auto compute = jit::KernelFuncs<jit::kVAddRelu, jit::XYZNTuples<T>, platform::CPUPlace>::Cache() .At(N); for (int i = 0; i < M; i++) { T* dst = Y + i * N; compute(B, dst, dst, N); } } else { auto compute = jit::KernelFuncs<jit::kVAdd, jit::XYZNTuples<T>, platform::CPUPlace>::Cache() .At(N); #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (int i = 0; i < M; i++) { T* dst = Y + i * N; compute(B, dst, dst, N); } } } } // namespace math } // namespace operators } // namespace paddle
ex04.c
/* Copyright (c) 2019 CSC Training */ /* Copyright (c) 2021 ENCCS */ #include <stdio.h> #include <math.h> #define NX 102400 int main(void) { double vecA[NX],vecB[NX],vecC[NX]; double r=0.2; /* Initialization of vectors */ for (int i = 0; i < NX; i++) { vecA[i] = pow(r, i); vecB[i] = 1.0; } /* dot product of two vectors */ #pragma omp target teams distribute map(from:vecC[0:NX]) map(to:vecA[0:NX],vecB[0:NX]) for (int i = 0; i < NX; i++) { vecC[i] = vecA[i] * vecB[i]; } double sum = 0.0; /* calculate the sum */ #pragma omp target map(tofrom:sum) for (int i = 0; i < NX; i++) { sum += vecC[i]; } printf("The sum is: %8.6f \n", sum); return 0; }
tree-vectorizer.h
/* Vectorizer Copyright (C) 2003-2015 Free Software Foundation, Inc. Contributed by Dorit Naishlos <dorit@il.ibm.com> This file is part of GCC. GCC 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. GCC 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 GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #ifndef GCC_TREE_VECTORIZER_H #define GCC_TREE_VECTORIZER_H #include "tree-data-ref.h" #include "target.h" #include "hash-table.h" /* Used for naming of new temporaries. */ enum vect_var_kind { vect_simple_var, vect_pointer_var, vect_scalar_var }; /* Defines type of operation. */ enum operation_type { unary_op = 1, binary_op, ternary_op }; /* Define type of available alignment support. */ enum dr_alignment_support { dr_unaligned_unsupported, dr_unaligned_supported, dr_explicit_realign, dr_explicit_realign_optimized, dr_aligned }; /* Define type of def-use cross-iteration cycle. */ enum vect_def_type { vect_uninitialized_def = 0, vect_constant_def = 1, vect_external_def, vect_internal_def, vect_induction_def, vect_reduction_def, vect_double_reduction_def, vect_nested_cycle, vect_unknown_def_type }; #define VECTORIZABLE_CYCLE_DEF(D) (((D) == vect_reduction_def) \ || ((D) == vect_double_reduction_def) \ || ((D) == vect_nested_cycle)) /* Structure to encapsulate information about a group of like instructions to be presented to the target cost model. */ typedef struct _stmt_info_for_cost { int count; enum vect_cost_for_stmt kind; gimple stmt; int misalign; } stmt_info_for_cost; typedef vec<stmt_info_for_cost> stmt_vector_for_cost; static inline void add_stmt_info_to_vec (stmt_vector_for_cost *stmt_cost_vec, int count, enum vect_cost_for_stmt kind, gimple stmt, int misalign) { stmt_info_for_cost si; si.count = count; si.kind = kind; si.stmt = stmt; si.misalign = misalign; stmt_cost_vec->safe_push (si); } /************************************************************************ SLP ************************************************************************/ typedef struct _slp_tree *slp_tree; /* A computation tree of an SLP instance. Each node corresponds to a group of stmts to be packed in a SIMD stmt. */ struct _slp_tree { /* Nodes that contain def-stmts of this node statements operands. */ vec<slp_tree> children; /* A group of scalar stmts to be vectorized together. */ vec<gimple> stmts; /* Load permutation relative to the stores, NULL if there is no permutation. */ vec<unsigned> load_permutation; /* Vectorized stmt/s. */ vec<gimple> vec_stmts; /* Number of vector stmts that are created to replace the group of scalar stmts. It is calculated during the transformation phase as the number of scalar elements in one scalar iteration (GROUP_SIZE) multiplied by VF divided by vector size. */ unsigned int vec_stmts_size; }; /* SLP instance is a sequence of stmts in a loop that can be packed into SIMD stmts. */ typedef struct _slp_instance { /* The root of SLP tree. */ slp_tree root; /* Size of groups of scalar stmts that will be replaced by SIMD stmt/s. */ unsigned int group_size; /* The unrolling factor required to vectorized this SLP instance. */ unsigned int unrolling_factor; /* Vectorization costs associated with SLP instance. */ stmt_vector_for_cost body_cost_vec; /* The group of nodes that contain loads of this SLP instance. */ vec<slp_tree> loads; /* The first scalar load of the instance. The created vector loads will be inserted before this statement. */ gimple first_load; } *slp_instance; /* Access Functions. */ #define SLP_INSTANCE_TREE(S) (S)->root #define SLP_INSTANCE_GROUP_SIZE(S) (S)->group_size #define SLP_INSTANCE_UNROLLING_FACTOR(S) (S)->unrolling_factor #define SLP_INSTANCE_BODY_COST_VEC(S) (S)->body_cost_vec #define SLP_INSTANCE_LOADS(S) (S)->loads #define SLP_INSTANCE_FIRST_LOAD_STMT(S) (S)->first_load #define SLP_TREE_CHILDREN(S) (S)->children #define SLP_TREE_SCALAR_STMTS(S) (S)->stmts #define SLP_TREE_VEC_STMTS(S) (S)->vec_stmts #define SLP_TREE_NUMBER_OF_VEC_STMTS(S) (S)->vec_stmts_size #define SLP_TREE_LOAD_PERMUTATION(S) (S)->load_permutation /* This structure is used in creation of an SLP tree. Each instance corresponds to the same operand in a group of scalar stmts in an SLP node. */ typedef struct _slp_oprnd_info { /* Def-stmts for the operands. */ vec<gimple> def_stmts; /* Information about the first statement, its vector def-type, type, the operand itself in case it's constant, and an indication if it's a pattern stmt. */ enum vect_def_type first_dt; tree first_op_type; bool first_pattern; } *slp_oprnd_info; /* This struct is used to store the information of a data reference, including the data ref itself, the access offset (calculated by summing its offset and init) and the segment length for aliasing checks. This is used to merge alias checks. */ struct dr_with_seg_len { dr_with_seg_len (data_reference_p d, tree len) : dr (d), offset (size_binop (PLUS_EXPR, DR_OFFSET (d), DR_INIT (d))), seg_len (len) {} data_reference_p dr; tree offset; tree seg_len; }; /* This struct contains two dr_with_seg_len objects with aliasing data refs. Two comparisons are generated from them. */ struct dr_with_seg_len_pair_t { dr_with_seg_len_pair_t (const dr_with_seg_len& d1, const dr_with_seg_len& d2) : first (d1), second (d2) {} dr_with_seg_len first; dr_with_seg_len second; }; typedef struct _vect_peel_info { int npeel; struct data_reference *dr; unsigned int count; } *vect_peel_info; typedef struct _vect_peel_extended_info { struct _vect_peel_info peel_info; unsigned int inside_cost; unsigned int outside_cost; stmt_vector_for_cost body_cost_vec; } *vect_peel_extended_info; /* Peeling hashtable helpers. */ struct peel_info_hasher : typed_free_remove <_vect_peel_info> { typedef _vect_peel_info value_type; typedef _vect_peel_info compare_type; static inline hashval_t hash (const value_type *); static inline bool equal (const value_type *, const compare_type *); }; inline hashval_t peel_info_hasher::hash (const value_type *peel_info) { return (hashval_t) peel_info->npeel; } inline bool peel_info_hasher::equal (const value_type *a, const compare_type *b) { return (a->npeel == b->npeel); } /*-----------------------------------------------------------------*/ /* Info on vectorized loops. */ /*-----------------------------------------------------------------*/ typedef struct _loop_vec_info { /* The loop to which this info struct refers to. */ struct loop *loop; /* The loop basic blocks. */ basic_block *bbs; /* Number of latch executions. */ tree num_itersm1; /* Number of iterations. */ tree num_iters; /* Number of iterations of the original loop. */ tree num_iters_unchanged; /* Minimum number of iterations below which vectorization is expected to not be profitable (as estimated by the cost model). -1 indicates that vectorization will not be profitable. FORNOW: This field is an int. Will be a tree in the future, to represent values unknown at compile time. */ int min_profitable_iters; /* Threshold of number of iterations below which vectorzation will not be performed. It is calculated from MIN_PROFITABLE_ITERS and PARAM_MIN_VECT_LOOP_BOUND. */ unsigned int th; /* Is the loop vectorizable? */ bool vectorizable; /* Unrolling factor */ int vectorization_factor; /* Unknown DRs according to which loop was peeled. */ struct data_reference *unaligned_dr; /* peeling_for_alignment indicates whether peeling for alignment will take place, and what the peeling factor should be: peeling_for_alignment = X means: If X=0: Peeling for alignment will not be applied. If X>0: Peel first X iterations. If X=-1: Generate a runtime test to calculate the number of iterations to be peeled, using the dataref recorded in the field unaligned_dr. */ int peeling_for_alignment; /* The mask used to check the alignment of pointers or arrays. */ int ptr_mask; /* The loop nest in which the data dependences are computed. */ vec<loop_p> loop_nest; /* All data references in the loop. */ vec<data_reference_p> datarefs; /* All data dependences in the loop. */ vec<ddr_p> ddrs; /* Data Dependence Relations defining address ranges that are candidates for a run-time aliasing check. */ vec<ddr_p> may_alias_ddrs; /* Data Dependence Relations defining address ranges together with segment lengths from which the run-time aliasing check is built. */ vec<dr_with_seg_len_pair_t> comp_alias_ddrs; /* Statements in the loop that have data references that are candidates for a runtime (loop versioning) misalignment check. */ vec<gimple> may_misalign_stmts; /* All interleaving chains of stores in the loop, represented by the first stmt in the chain. */ vec<gimple> grouped_stores; /* All SLP instances in the loop. This is a subset of the set of GROUP_STORES of the loop. */ vec<slp_instance> slp_instances; /* The unrolling factor needed to SLP the loop. In case of that pure SLP is applied to the loop, i.e., no unrolling is needed, this is 1. */ unsigned slp_unrolling_factor; /* Reduction cycles detected in the loop. Used in loop-aware SLP. */ vec<gimple> reductions; /* All reduction chains in the loop, represented by the first stmt in the chain. */ vec<gimple> reduction_chains; /* Hash table used to choose the best peeling option. */ hash_table<peel_info_hasher> *peeling_htab; /* Cost data used by the target cost model. */ void *target_cost_data; /* When we have grouped data accesses with gaps, we may introduce invalid memory accesses. We peel the last iteration of the loop to prevent this. */ bool peeling_for_gaps; /* When the number of iterations is not a multiple of the vector size we need to peel off iterations at the end to form an epilogue loop. */ bool peeling_for_niter; /* Reductions are canonicalized so that the last operand is the reduction operand. If this places a constant into RHS1, this decanonicalizes GIMPLE for other phases, so we must track when this has occurred and fix it up. */ bool operands_swapped; /* True if there are no loop carried data dependencies in the loop. If loop->safelen <= 1, then this is always true, either the loop didn't have any loop carried data dependencies, or the loop is being vectorized guarded with some runtime alias checks, or couldn't be vectorized at all, but then this field shouldn't be used. For loop->safelen >= 2, the user has asserted that there are no backward dependencies, but there still could be loop carried forward dependencies in such loops. This flag will be false if normal vectorizer data dependency analysis would fail or require versioning for alias, but because of loop->safelen >= 2 it has been vectorized even without versioning for alias. E.g. in: #pragma omp simd for (int i = 0; i < m; i++) a[i] = a[i + k] * c; (or #pragma simd or #pragma ivdep) we can vectorize this and it will DTRT even for k > 0 && k < m, but without safelen we would not vectorize this, so this field would be false. */ bool no_data_dependencies; /* If if-conversion versioned this loop before conversion, this is the loop version without if-conversion. */ struct loop *scalar_loop; } *loop_vec_info; /* Access Functions. */ #define LOOP_VINFO_LOOP(L) (L)->loop #define LOOP_VINFO_BBS(L) (L)->bbs #define LOOP_VINFO_NITERSM1(L) (L)->num_itersm1 #define LOOP_VINFO_NITERS(L) (L)->num_iters /* Since LOOP_VINFO_NITERS and LOOP_VINFO_NITERSM1 can change after prologue peeling retain total unchanged scalar loop iterations for cost model. */ #define LOOP_VINFO_NITERS_UNCHANGED(L) (L)->num_iters_unchanged #define LOOP_VINFO_COST_MODEL_MIN_ITERS(L) (L)->min_profitable_iters #define LOOP_VINFO_COST_MODEL_THRESHOLD(L) (L)->th #define LOOP_VINFO_VECTORIZABLE_P(L) (L)->vectorizable #define LOOP_VINFO_VECT_FACTOR(L) (L)->vectorization_factor #define LOOP_VINFO_PTR_MASK(L) (L)->ptr_mask #define LOOP_VINFO_LOOP_NEST(L) (L)->loop_nest #define LOOP_VINFO_DATAREFS(L) (L)->datarefs #define LOOP_VINFO_DDRS(L) (L)->ddrs #define LOOP_VINFO_INT_NITERS(L) (TREE_INT_CST_LOW ((L)->num_iters)) #define LOOP_VINFO_PEELING_FOR_ALIGNMENT(L) (L)->peeling_for_alignment #define LOOP_VINFO_UNALIGNED_DR(L) (L)->unaligned_dr #define LOOP_VINFO_MAY_MISALIGN_STMTS(L) (L)->may_misalign_stmts #define LOOP_VINFO_MAY_ALIAS_DDRS(L) (L)->may_alias_ddrs #define LOOP_VINFO_COMP_ALIAS_DDRS(L) (L)->comp_alias_ddrs #define LOOP_VINFO_GROUPED_STORES(L) (L)->grouped_stores #define LOOP_VINFO_SLP_INSTANCES(L) (L)->slp_instances #define LOOP_VINFO_SLP_UNROLLING_FACTOR(L) (L)->slp_unrolling_factor #define LOOP_VINFO_REDUCTIONS(L) (L)->reductions #define LOOP_VINFO_REDUCTION_CHAINS(L) (L)->reduction_chains #define LOOP_VINFO_PEELING_HTAB(L) (L)->peeling_htab #define LOOP_VINFO_TARGET_COST_DATA(L) (L)->target_cost_data #define LOOP_VINFO_PEELING_FOR_GAPS(L) (L)->peeling_for_gaps #define LOOP_VINFO_OPERANDS_SWAPPED(L) (L)->operands_swapped #define LOOP_VINFO_PEELING_FOR_NITER(L) (L)->peeling_for_niter #define LOOP_VINFO_NO_DATA_DEPENDENCIES(L) (L)->no_data_dependencies #define LOOP_VINFO_SCALAR_LOOP(L) (L)->scalar_loop #define LOOP_REQUIRES_VERSIONING_FOR_ALIGNMENT(L) \ ((L)->may_misalign_stmts.length () > 0) #define LOOP_REQUIRES_VERSIONING_FOR_ALIAS(L) \ ((L)->may_alias_ddrs.length () > 0) #define LOOP_VINFO_NITERS_KNOWN_P(L) \ (tree_fits_shwi_p ((L)->num_iters) && tree_to_shwi ((L)->num_iters) > 0) static inline loop_vec_info loop_vec_info_for_loop (struct loop *loop) { return (loop_vec_info) loop->aux; } static inline bool nested_in_vect_loop_p (struct loop *loop, gimple stmt) { return (loop->inner && (loop->inner == (gimple_bb (stmt))->loop_father)); } typedef struct _bb_vec_info { basic_block bb; /* All interleaving chains of stores in the basic block, represented by the first stmt in the chain. */ vec<gimple> grouped_stores; /* All SLP instances in the basic block. This is a subset of the set of GROUP_STORES of the basic block. */ vec<slp_instance> slp_instances; /* All data references in the basic block. */ vec<data_reference_p> datarefs; /* All data dependences in the basic block. */ vec<ddr_p> ddrs; /* Cost data used by the target cost model. */ void *target_cost_data; } *bb_vec_info; #define BB_VINFO_BB(B) (B)->bb #define BB_VINFO_GROUPED_STORES(B) (B)->grouped_stores #define BB_VINFO_SLP_INSTANCES(B) (B)->slp_instances #define BB_VINFO_DATAREFS(B) (B)->datarefs #define BB_VINFO_DDRS(B) (B)->ddrs #define BB_VINFO_TARGET_COST_DATA(B) (B)->target_cost_data static inline bb_vec_info vec_info_for_bb (basic_block bb) { return (bb_vec_info) bb->aux; } /*-----------------------------------------------------------------*/ /* Info on vectorized defs. */ /*-----------------------------------------------------------------*/ enum stmt_vec_info_type { undef_vec_info_type = 0, load_vec_info_type, store_vec_info_type, shift_vec_info_type, op_vec_info_type, call_vec_info_type, call_simd_clone_vec_info_type, assignment_vec_info_type, condition_vec_info_type, reduc_vec_info_type, induc_vec_info_type, type_promotion_vec_info_type, type_demotion_vec_info_type, type_conversion_vec_info_type, loop_exit_ctrl_vec_info_type }; /* Indicates whether/how a variable is used in the scope of loop/basic block. */ enum vect_relevant { vect_unused_in_scope = 0, /* The def is in the inner loop, and the use is in the outer loop, and the use is a reduction stmt. */ vect_used_in_outer_by_reduction, /* The def is in the inner loop, and the use is in the outer loop (and is not part of reduction). */ vect_used_in_outer, /* defs that feed computations that end up (only) in a reduction. These defs may be used by non-reduction stmts, but eventually, any computations/values that are affected by these defs are used to compute a reduction (i.e. don't get stored to memory, for example). We use this to identify computations that we can change the order in which they are computed. */ vect_used_by_reduction, vect_used_in_scope }; /* The type of vectorization that can be applied to the stmt: regular loop-based vectorization; pure SLP - the stmt is a part of SLP instances and does not have uses outside SLP instances; or hybrid SLP and loop-based - the stmt is a part of SLP instance and also must be loop-based vectorized, since it has uses outside SLP sequences. In the loop context the meanings of pure and hybrid SLP are slightly different. By saying that pure SLP is applied to the loop, we mean that we exploit only intra-iteration parallelism in the loop; i.e., the loop can be vectorized without doing any conceptual unrolling, cause we don't pack together stmts from different iterations, only within a single iteration. Loop hybrid SLP means that we exploit both intra-iteration and inter-iteration parallelism (e.g., number of elements in the vector is 4 and the slp-group-size is 2, in which case we don't have enough parallelism within an iteration, so we obtain the rest of the parallelism from subsequent iterations by unrolling the loop by 2). */ enum slp_vect_type { loop_vect = 0, pure_slp, hybrid }; typedef struct data_reference *dr_p; typedef struct _stmt_vec_info { enum stmt_vec_info_type type; /* Indicates whether this stmts is part of a computation whose result is used outside the loop. */ bool live; /* Stmt is part of some pattern (computation idiom) */ bool in_pattern_p; /* The stmt to which this info struct refers to. */ gimple stmt; /* The loop_vec_info with respect to which STMT is vectorized. */ loop_vec_info loop_vinfo; /* The vector type to be used for the LHS of this statement. */ tree vectype; /* The vectorized version of the stmt. */ gimple vectorized_stmt; /** The following is relevant only for stmts that contain a non-scalar data-ref (array/pointer/struct access). A GIMPLE stmt is expected to have at most one such data-ref. **/ /* Information about the data-ref (access function, etc), relative to the inner-most containing loop. */ struct data_reference *data_ref_info; /* Information about the data-ref relative to this loop nest (the loop that is being considered for vectorization). */ tree dr_base_address; tree dr_init; tree dr_offset; tree dr_step; tree dr_aligned_to; /* For loop PHI nodes, the evolution part of it. This makes sure this information is still available in vect_update_ivs_after_vectorizer where we may not be able to re-analyze the PHI nodes evolution as peeling for the prologue loop can make it unanalyzable. The evolution part is still correct though. */ tree loop_phi_evolution_part; /* Used for various bookkeeping purposes, generally holding a pointer to some other stmt S that is in some way "related" to this stmt. Current use of this field is: If this stmt is part of a pattern (i.e. the field 'in_pattern_p' is true): S is the "pattern stmt" that represents (and replaces) the sequence of stmts that constitutes the pattern. Similarly, the related_stmt of the "pattern stmt" points back to this stmt (which is the last stmt in the original sequence of stmts that constitutes the pattern). */ gimple related_stmt; /* Used to keep a sequence of def stmts of a pattern stmt if such exists. */ gimple_seq pattern_def_seq; /* List of datarefs that are known to have the same alignment as the dataref of this stmt. */ vec<dr_p> same_align_refs; /* Selected SIMD clone's function info. First vector element is SIMD clone's function decl, followed by a pair of trees (base + step) for linear arguments (pair of NULLs for other arguments). */ vec<tree> simd_clone_info; /* Classify the def of this stmt. */ enum vect_def_type def_type; /* Whether the stmt is SLPed, loop-based vectorized, or both. */ enum slp_vect_type slp_type; /* Interleaving and reduction chains info. */ /* First element in the group. */ gimple first_element; /* Pointer to the next element in the group. */ gimple next_element; /* For data-refs, in case that two or more stmts share data-ref, this is the pointer to the previously detected stmt with the same dr. */ gimple same_dr_stmt; /* The size of the group. */ unsigned int size; /* For stores, number of stores from this group seen. We vectorize the last one. */ unsigned int store_count; /* For loads only, the gap from the previous load. For consecutive loads, GAP is 1. */ unsigned int gap; /* The minimum negative dependence distance this stmt participates in or zero if none. */ unsigned int min_neg_dist; /* Not all stmts in the loop need to be vectorized. e.g, the increment of the loop induction variable and computation of array indexes. relevant indicates whether the stmt needs to be vectorized. */ enum vect_relevant relevant; /* The bb_vec_info with respect to which STMT is vectorized. */ bb_vec_info bb_vinfo; /* Is this statement vectorizable or should it be skipped in (partial) vectorization. */ bool vectorizable; /* For loads only, true if this is a gather load. */ bool gather_p; bool stride_load_p; /* For both loads and stores. */ bool simd_lane_access_p; } *stmt_vec_info; /* Access Functions. */ #define STMT_VINFO_TYPE(S) (S)->type #define STMT_VINFO_STMT(S) (S)->stmt #define STMT_VINFO_LOOP_VINFO(S) (S)->loop_vinfo #define STMT_VINFO_BB_VINFO(S) (S)->bb_vinfo #define STMT_VINFO_RELEVANT(S) (S)->relevant #define STMT_VINFO_LIVE_P(S) (S)->live #define STMT_VINFO_VECTYPE(S) (S)->vectype #define STMT_VINFO_VEC_STMT(S) (S)->vectorized_stmt #define STMT_VINFO_VECTORIZABLE(S) (S)->vectorizable #define STMT_VINFO_DATA_REF(S) (S)->data_ref_info #define STMT_VINFO_GATHER_P(S) (S)->gather_p #define STMT_VINFO_STRIDE_LOAD_P(S) (S)->stride_load_p #define STMT_VINFO_SIMD_LANE_ACCESS_P(S) (S)->simd_lane_access_p #define STMT_VINFO_DR_BASE_ADDRESS(S) (S)->dr_base_address #define STMT_VINFO_DR_INIT(S) (S)->dr_init #define STMT_VINFO_DR_OFFSET(S) (S)->dr_offset #define STMT_VINFO_DR_STEP(S) (S)->dr_step #define STMT_VINFO_DR_ALIGNED_TO(S) (S)->dr_aligned_to #define STMT_VINFO_IN_PATTERN_P(S) (S)->in_pattern_p #define STMT_VINFO_RELATED_STMT(S) (S)->related_stmt #define STMT_VINFO_PATTERN_DEF_SEQ(S) (S)->pattern_def_seq #define STMT_VINFO_SAME_ALIGN_REFS(S) (S)->same_align_refs #define STMT_VINFO_SIMD_CLONE_INFO(S) (S)->simd_clone_info #define STMT_VINFO_DEF_TYPE(S) (S)->def_type #define STMT_VINFO_GROUP_FIRST_ELEMENT(S) (S)->first_element #define STMT_VINFO_GROUP_NEXT_ELEMENT(S) (S)->next_element #define STMT_VINFO_GROUP_SIZE(S) (S)->size #define STMT_VINFO_GROUP_STORE_COUNT(S) (S)->store_count #define STMT_VINFO_GROUP_GAP(S) (S)->gap #define STMT_VINFO_GROUP_SAME_DR_STMT(S) (S)->same_dr_stmt #define STMT_VINFO_GROUPED_ACCESS(S) ((S)->first_element != NULL && (S)->data_ref_info) #define STMT_VINFO_LOOP_PHI_EVOLUTION_PART(S) (S)->loop_phi_evolution_part #define STMT_VINFO_MIN_NEG_DIST(S) (S)->min_neg_dist #define GROUP_FIRST_ELEMENT(S) (S)->first_element #define GROUP_NEXT_ELEMENT(S) (S)->next_element #define GROUP_SIZE(S) (S)->size #define GROUP_STORE_COUNT(S) (S)->store_count #define GROUP_GAP(S) (S)->gap #define GROUP_SAME_DR_STMT(S) (S)->same_dr_stmt #define STMT_VINFO_RELEVANT_P(S) ((S)->relevant != vect_unused_in_scope) #define HYBRID_SLP_STMT(S) ((S)->slp_type == hybrid) #define PURE_SLP_STMT(S) ((S)->slp_type == pure_slp) #define STMT_SLP_TYPE(S) (S)->slp_type struct dataref_aux { tree base_decl; bool base_misaligned; int misalignment; }; #define VECT_MAX_COST 1000 /* The maximum number of intermediate steps required in multi-step type conversion. */ #define MAX_INTERM_CVT_STEPS 3 /* The maximum vectorization factor supported by any target (V64QI). */ #define MAX_VECTORIZATION_FACTOR 64 /* Avoid GTY(()) on stmt_vec_info. */ typedef void *vec_void_p; extern vec<vec_void_p> stmt_vec_info_vec; void init_stmt_vec_info_vec (void); void free_stmt_vec_info_vec (void); /* Return a stmt_vec_info corresponding to STMT. */ static inline stmt_vec_info vinfo_for_stmt (gimple stmt) { unsigned int uid = gimple_uid (stmt); if (uid == 0) return NULL; return (stmt_vec_info) stmt_vec_info_vec[uid - 1]; } /* Set vectorizer information INFO for STMT. */ static inline void set_vinfo_for_stmt (gimple stmt, stmt_vec_info info) { unsigned int uid = gimple_uid (stmt); if (uid == 0) { gcc_checking_assert (info); uid = stmt_vec_info_vec.length () + 1; gimple_set_uid (stmt, uid); stmt_vec_info_vec.safe_push ((vec_void_p) info); } else stmt_vec_info_vec[uid - 1] = (vec_void_p) info; } /* Return the earlier statement between STMT1 and STMT2. */ static inline gimple get_earlier_stmt (gimple stmt1, gimple stmt2) { unsigned int uid1, uid2; if (stmt1 == NULL) return stmt2; if (stmt2 == NULL) return stmt1; uid1 = gimple_uid (stmt1); uid2 = gimple_uid (stmt2); if (uid1 == 0 || uid2 == 0) return NULL; gcc_checking_assert (uid1 <= stmt_vec_info_vec.length () && uid2 <= stmt_vec_info_vec.length ()); if (uid1 < uid2) return stmt1; else return stmt2; } /* Return the later statement between STMT1 and STMT2. */ static inline gimple get_later_stmt (gimple stmt1, gimple stmt2) { unsigned int uid1, uid2; if (stmt1 == NULL) return stmt2; if (stmt2 == NULL) return stmt1; uid1 = gimple_uid (stmt1); uid2 = gimple_uid (stmt2); if (uid1 == 0 || uid2 == 0) return NULL; gcc_assert (uid1 <= stmt_vec_info_vec.length ()); gcc_assert (uid2 <= stmt_vec_info_vec.length ()); if (uid1 > uid2) return stmt1; else return stmt2; } /* Return TRUE if a statement represented by STMT_INFO is a part of a pattern. */ static inline bool is_pattern_stmt_p (stmt_vec_info stmt_info) { gimple related_stmt; stmt_vec_info related_stmt_info; related_stmt = STMT_VINFO_RELATED_STMT (stmt_info); if (related_stmt && (related_stmt_info = vinfo_for_stmt (related_stmt)) && STMT_VINFO_IN_PATTERN_P (related_stmt_info)) return true; return false; } /* Return true if BB is a loop header. */ static inline bool is_loop_header_bb_p (basic_block bb) { if (bb == (bb->loop_father)->header) return true; gcc_checking_assert (EDGE_COUNT (bb->preds) == 1); return false; } /* Return pow2 (X). */ static inline int vect_pow2 (int x) { int i, res = 1; for (i = 0; i < x; i++) res *= 2; return res; } /* Alias targetm.vectorize.builtin_vectorization_cost. */ static inline int builtin_vectorization_cost (enum vect_cost_for_stmt type_of_cost, tree vectype, int misalign) { return targetm.vectorize.builtin_vectorization_cost (type_of_cost, vectype, misalign); } /* Get cost by calling cost target builtin. */ static inline int vect_get_stmt_cost (enum vect_cost_for_stmt type_of_cost) { return builtin_vectorization_cost (type_of_cost, NULL, 0); } /* Alias targetm.vectorize.init_cost. */ static inline void * init_cost (struct loop *loop_info) { return targetm.vectorize.init_cost (loop_info); } /* Alias targetm.vectorize.add_stmt_cost. */ static inline unsigned add_stmt_cost (void *data, int count, enum vect_cost_for_stmt kind, stmt_vec_info stmt_info, int misalign, enum vect_cost_model_location where) { return targetm.vectorize.add_stmt_cost (data, count, kind, stmt_info, misalign, where); } /* Alias targetm.vectorize.finish_cost. */ static inline void finish_cost (void *data, unsigned *prologue_cost, unsigned *body_cost, unsigned *epilogue_cost) { targetm.vectorize.finish_cost (data, prologue_cost, body_cost, epilogue_cost); } /* Alias targetm.vectorize.destroy_cost_data. */ static inline void destroy_cost_data (void *data) { targetm.vectorize.destroy_cost_data (data); } /*-----------------------------------------------------------------*/ /* Info on data references alignment. */ /*-----------------------------------------------------------------*/ inline void set_dr_misalignment (struct data_reference *dr, int val) { dataref_aux *data_aux = (dataref_aux *) dr->aux; if (!data_aux) { data_aux = XCNEW (dataref_aux); dr->aux = data_aux; } data_aux->misalignment = val; } inline int dr_misalignment (struct data_reference *dr) { gcc_assert (dr->aux); return ((dataref_aux *) dr->aux)->misalignment; } /* Reflects actual alignment of first access in the vectorized loop, taking into account peeling/versioning if applied. */ #define DR_MISALIGNMENT(DR) dr_misalignment (DR) #define SET_DR_MISALIGNMENT(DR, VAL) set_dr_misalignment (DR, VAL) /* Return TRUE if the data access is aligned, and FALSE otherwise. */ static inline bool aligned_access_p (struct data_reference *data_ref_info) { return (DR_MISALIGNMENT (data_ref_info) == 0); } /* Return TRUE if the alignment of the data access is known, and FALSE otherwise. */ static inline bool known_alignment_for_access_p (struct data_reference *data_ref_info) { return (DR_MISALIGNMENT (data_ref_info) != -1); } /* Return true if the vect cost model is unlimited. */ static inline bool unlimited_cost_model (loop_p loop) { if (loop != NULL && loop->force_vectorize && flag_simd_cost_model != VECT_COST_MODEL_DEFAULT) return flag_simd_cost_model == VECT_COST_MODEL_UNLIMITED; return (flag_vect_cost_model == VECT_COST_MODEL_UNLIMITED); } /* Source location */ extern source_location vect_location; /*-----------------------------------------------------------------*/ /* Function prototypes. */ /*-----------------------------------------------------------------*/ /* Simple loop peeling and versioning utilities for vectorizer's purposes - in tree-vect-loop-manip.c. */ extern void slpeel_make_loop_iterate_ntimes (struct loop *, tree); extern bool slpeel_can_duplicate_loop_p (const struct loop *, const_edge); struct loop *slpeel_tree_duplicate_loop_to_edge_cfg (struct loop *, struct loop *, edge); extern void vect_loop_versioning (loop_vec_info, unsigned int, bool); extern void vect_do_peeling_for_loop_bound (loop_vec_info, tree, tree, unsigned int, bool); extern void vect_do_peeling_for_alignment (loop_vec_info, tree, unsigned int, bool); extern source_location find_loop_location (struct loop *); extern bool vect_can_advance_ivs_p (loop_vec_info); /* In tree-vect-stmts.c. */ extern unsigned int current_vector_size; extern tree get_vectype_for_scalar_type (tree); extern tree get_same_sized_vectype (tree, tree); extern bool vect_is_simple_use (tree, gimple, loop_vec_info, bb_vec_info, gimple *, tree *, enum vect_def_type *); extern bool vect_is_simple_use_1 (tree, gimple, loop_vec_info, bb_vec_info, gimple *, tree *, enum vect_def_type *, tree *); extern bool supportable_widening_operation (enum tree_code, gimple, tree, tree, enum tree_code *, enum tree_code *, int *, vec<tree> *); extern bool supportable_narrowing_operation (enum tree_code, tree, tree, enum tree_code *, int *, vec<tree> *); extern stmt_vec_info new_stmt_vec_info (gimple stmt, loop_vec_info, bb_vec_info); extern void free_stmt_vec_info (gimple stmt); extern tree vectorizable_function (gcall *, tree, tree); extern void vect_model_simple_cost (stmt_vec_info, int, enum vect_def_type *, stmt_vector_for_cost *, stmt_vector_for_cost *); extern void vect_model_store_cost (stmt_vec_info, int, bool, enum vect_def_type, slp_tree, stmt_vector_for_cost *, stmt_vector_for_cost *); extern void vect_model_load_cost (stmt_vec_info, int, bool, slp_tree, stmt_vector_for_cost *, stmt_vector_for_cost *); extern unsigned record_stmt_cost (stmt_vector_for_cost *, int, enum vect_cost_for_stmt, stmt_vec_info, int, enum vect_cost_model_location); extern void vect_finish_stmt_generation (gimple, gimple, gimple_stmt_iterator *); extern bool vect_mark_stmts_to_be_vectorized (loop_vec_info); extern tree vect_get_vec_def_for_operand (tree, gimple, tree *); extern tree vect_init_vector (gimple, tree, tree, gimple_stmt_iterator *); extern tree vect_get_vec_def_for_stmt_copy (enum vect_def_type, tree); extern bool vect_transform_stmt (gimple, gimple_stmt_iterator *, bool *, slp_tree, slp_instance); extern void vect_remove_stores (gimple); extern bool vect_analyze_stmt (gimple, bool *, slp_tree); extern bool vectorizable_condition (gimple, gimple_stmt_iterator *, gimple *, tree, int, slp_tree); extern void vect_get_load_cost (struct data_reference *, int, bool, unsigned int *, unsigned int *, stmt_vector_for_cost *, stmt_vector_for_cost *, bool); extern void vect_get_store_cost (struct data_reference *, int, unsigned int *, stmt_vector_for_cost *); extern bool vect_supportable_shift (enum tree_code, tree); extern void vect_get_vec_defs (tree, tree, gimple, vec<tree> *, vec<tree> *, slp_tree, int); extern tree vect_gen_perm_mask_any (tree, const unsigned char *); extern tree vect_gen_perm_mask_checked (tree, const unsigned char *); /* In tree-vect-data-refs.c. */ extern bool vect_can_force_dr_alignment_p (const_tree, unsigned int); extern enum dr_alignment_support vect_supportable_dr_alignment (struct data_reference *, bool); extern tree vect_get_smallest_scalar_type (gimple, HOST_WIDE_INT *, HOST_WIDE_INT *); extern bool vect_analyze_data_ref_dependences (loop_vec_info, int *); extern bool vect_slp_analyze_data_ref_dependences (bb_vec_info); extern bool vect_enhance_data_refs_alignment (loop_vec_info); extern bool vect_analyze_data_refs_alignment (loop_vec_info, bb_vec_info); extern bool vect_verify_datarefs_alignment (loop_vec_info, bb_vec_info); extern bool vect_analyze_data_ref_accesses (loop_vec_info, bb_vec_info); extern bool vect_prune_runtime_alias_test_list (loop_vec_info); extern tree vect_check_gather (gimple, loop_vec_info, tree *, tree *, int *); extern bool vect_analyze_data_refs (loop_vec_info, bb_vec_info, int *, unsigned *); extern tree vect_create_data_ref_ptr (gimple, tree, struct loop *, tree, tree *, gimple_stmt_iterator *, gimple *, bool, bool *, tree = NULL_TREE); extern tree bump_vector_ptr (tree, gimple, gimple_stmt_iterator *, gimple, tree); extern tree vect_create_destination_var (tree, tree); extern bool vect_grouped_store_supported (tree, unsigned HOST_WIDE_INT); extern bool vect_store_lanes_supported (tree, unsigned HOST_WIDE_INT); extern bool vect_grouped_load_supported (tree, unsigned HOST_WIDE_INT); extern bool vect_load_lanes_supported (tree, unsigned HOST_WIDE_INT); extern void vect_permute_store_chain (vec<tree> ,unsigned int, gimple, gimple_stmt_iterator *, vec<tree> *); extern tree vect_setup_realignment (gimple, gimple_stmt_iterator *, tree *, enum dr_alignment_support, tree, struct loop **); extern void vect_transform_grouped_load (gimple, vec<tree> , int, gimple_stmt_iterator *); extern void vect_record_grouped_load_vectors (gimple, vec<tree> ); extern tree vect_get_new_vect_var (tree, enum vect_var_kind, const char *); extern tree vect_create_addr_base_for_vector_ref (gimple, gimple_seq *, tree, struct loop *, tree = NULL_TREE); /* In tree-vect-loop.c. */ /* FORNOW: Used in tree-parloops.c. */ extern void destroy_loop_vec_info (loop_vec_info, bool); extern gimple vect_force_simple_reduction (loop_vec_info, gimple, bool, bool *); /* Drive for loop analysis stage. */ extern loop_vec_info vect_analyze_loop (struct loop *); /* Drive for loop transformation stage. */ extern void vect_transform_loop (loop_vec_info); extern loop_vec_info vect_analyze_loop_form (struct loop *); extern bool vectorizable_live_operation (gimple, gimple_stmt_iterator *, gimple *); extern bool vectorizable_reduction (gimple, gimple_stmt_iterator *, gimple *, slp_tree); extern bool vectorizable_induction (gimple, gimple_stmt_iterator *, gimple *); extern tree get_initial_def_for_reduction (gimple, tree, tree *); extern int vect_min_worthwhile_factor (enum tree_code); extern int vect_get_known_peeling_cost (loop_vec_info, int, int *, int, stmt_vector_for_cost *, stmt_vector_for_cost *); extern int vect_get_single_scalar_iteration_cost (loop_vec_info); /* In tree-vect-slp.c. */ extern void vect_free_slp_instance (slp_instance); extern bool vect_transform_slp_perm_load (slp_tree, vec<tree> , gimple_stmt_iterator *, int, slp_instance, bool); extern bool vect_schedule_slp (loop_vec_info, bb_vec_info); extern void vect_update_slp_costs_according_to_vf (loop_vec_info); extern bool vect_analyze_slp (loop_vec_info, bb_vec_info, unsigned); extern bool vect_make_slp_decision (loop_vec_info); extern void vect_detect_hybrid_slp (loop_vec_info); extern void vect_get_slp_defs (vec<tree> , slp_tree, vec<vec<tree> > *, int); extern source_location find_bb_location (basic_block); extern bb_vec_info vect_slp_analyze_bb (basic_block); extern void vect_slp_transform_bb (basic_block); /* In tree-vect-patterns.c. */ /* Pattern recognition functions. Additional pattern recognition functions can (and will) be added in the future. */ typedef gimple (* vect_recog_func_ptr) (vec<gimple> *, tree *, tree *); #define NUM_PATTERNS 12 void vect_pattern_recog (loop_vec_info, bb_vec_info); /* In tree-vectorizer.c. */ unsigned vectorize_loops (void); void vect_destroy_datarefs (loop_vec_info, bb_vec_info); #endif /* GCC_TREE_VECTORIZER_H */
omp_detach_taskwait.c
// RUN: %libomp-compile && env OMP_NUM_THREADS='3' %libomp-run // RUN: %libomp-compile && env OMP_NUM_THREADS='1' %libomp-run // Checked gcc 10.1 still does not support detach clause on task construct. // UNSUPPORTED: gcc-4, gcc-5, gcc-6, gcc-7, gcc-8, gcc-9, gcc-10 // gcc 11 introduced detach clause, but gomp interface in libomp has no support // XFAIL: gcc-11, gcc-12 // clang supports detach clause since version 11. // UNSUPPORTED: clang-10, clang-9, clang-8, clang-7 // icc compiler does not support detach clause. // UNSUPPORTED: icc #include <omp.h> int main() { #pragma omp parallel #pragma omp master { omp_event_handle_t event; #pragma omp task detach(event) { omp_fulfill_event(event); } #pragma omp taskwait } return 0; }
pcptdesencryptecbcaomp.c
/******************************************************************************* * Copyright 2002-2018 Intel Corporation * All Rights Reserved. * * If this software was obtained under the Intel Simplified Software License, * the following terms apply: * * The source code, information and material ("Material") contained herein is * owned by Intel Corporation or its suppliers or licensors, and title to such * Material remains with Intel Corporation or its suppliers or licensors. The * Material contains proprietary information of Intel or its suppliers and * licensors. The Material is protected by worldwide copyright laws and treaty * provisions. No part of the Material may be used, copied, reproduced, * modified, published, uploaded, posted, transmitted, distributed or disclosed * in any way without Intel's prior express written permission. No license under * any patent, copyright or other intellectual property rights in the Material * is granted to or conferred upon you, either expressly, by implication, * inducement, estoppel or otherwise. Any license under such intellectual * property rights must be express and approved by Intel in writing. * * Unless otherwise agreed by Intel in writing, you may not remove or alter this * notice or any other notice embedded in Materials by Intel or Intel's * suppliers or licensors in any way. * * * If this software was obtained under the Apache License, Version 2.0 (the * "License"), the following terms apply: * * 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. *******************************************************************************/ /* // Name: // ippsTDESEncryptECB // // Purpose: // Cryptography Primitives. // Encrypt byte data stream according to TDES. // // */ #include "owndefs.h" #if defined ( _OPENMP ) #include "owncp.h" #include "pcpdes.h" #include "pcptool.h" #include "omp.h" /*F* // Name: // ippsTDESEncryptECB // // Purpose: // Encrypt byte data stream according to TDES in ECB mode // using OpenMP API. // // Returns: // ippStsNoErr No errors, it's OK. // ippStsNullPtrErr ( pCtx1 == NULL ) || ( pCtx2 == NULL ) || // ( pCtx3 == NULL ) || ( pSrc == NULL ) || // ( pDst == NULL ) // ippStsLengthErr srcLen < 1 // ippStsContextMatchErr ( pCtx1->idCtx != idCtxDES ) || // ( pCtx2->idCtx != idCtxDES ) || // ( pCtx3->idCtx != idCtxDES ) // ippStsUnderRunErr srcLen % 8 // // Parameters: // pSrc Pointer to the input ciphertext byte data stream. // pDst Pointer to the output plaintext byte data stream. // srcLen Ciphertext data stream length in bytes. // pCtx1 Pointer to the IppsDESSpec context. // pCtx2 Pointer to the IppsDESSpec context. // pCtx3 Pointer to the IppsDESSpec context. // padding Padding scheme indicator *F*/ static void TDES_EncECB_processing(const Ipp8u* pSrc, Ipp8u* pDst, int nBlocks, const RoundKeyDES* pRKey[3]) { /* // encrypt block-by-block aligned streams */ if( !(IPP_UINT_PTR(pSrc) & 0x7) && !(IPP_UINT_PTR(pDst) & 0x7)) { ECB_TDES((const Ipp64u*)pSrc, (Ipp64u*)pDst, nBlocks, pRKey, DESspbox); } /* // encrypt block-by-block misaligned streams */ else { Ipp64u block; while(nBlocks) { CopyBlock8(pSrc, &block); block = Cipher_DES(block, pRKey[0], DESspbox); block = Cipher_DES(block, pRKey[1], DESspbox); block = Cipher_DES(block, pRKey[2], DESspbox); CopyBlock8(&block, pDst); pSrc += MBS_DES; pDst += MBS_DES; nBlocks--; } } } IPPFUN(IppStatus, ippsTDESEncryptECB,(const Ipp8u* pSrc, Ipp8u* pDst, int srcLen, const IppsDESSpec* pCtx1, const IppsDESSpec* pCtx2, const IppsDESSpec* pCtx3, IppsPadding padding)) { /* test the pointers */ IPP_BAD_PTR2_RET(pSrc, pDst); IPP_BAD_PTR3_RET(pCtx1, pCtx2, pCtx3); /* align the contexts */ pCtx1 = (IppsDESSpec*)(IPP_ALIGNED_PTR(pCtx1, DES_ALIGNMENT)); pCtx2 = (IppsDESSpec*)(IPP_ALIGNED_PTR(pCtx2, DES_ALIGNMENT)); pCtx3 = (IppsDESSpec*)(IPP_ALIGNED_PTR(pCtx3, DES_ALIGNMENT)); /* test the contexts */ IPP_BADARG_RET(!DES_ID_TEST(pCtx1), ippStsContextMatchErr); IPP_BADARG_RET(!DES_ID_TEST(pCtx2), ippStsContextMatchErr); IPP_BADARG_RET(!DES_ID_TEST(pCtx3), ippStsContextMatchErr); /* test the data stream length */ IPP_BADARG_RET((srcLen<1), ippStsLengthErr); /* test the data stream integrity */ IPP_BADARG_RET((srcLen&(MBS_DES-1)), ippStsUnderRunErr); UNREFERENCED_PARAMETER(padding); { int nBlocks = srcLen / MBS_DES; int nThreads = IPP_MIN(IPPCP_GET_NUM_THREADS(), IPP_MAX(nBlocks/TDES_MIN_BLK_PER_THREAD, 1)); const RoundKeyDES* pRKey[3]; pRKey[0] = DES_EKEYS(pCtx1); pRKey[1] = DES_DKEYS(pCtx2); pRKey[2] = DES_EKEYS(pCtx3); if(1==nThreads) TDES_EncECB_processing(pSrc, pDst, nBlocks, pRKey); else { int blksThreadReg; int blksThreadTail; #pragma omp parallel IPPCP_OMP_LIMIT_MAX_NUM_THREADS(nThreads) { #pragma omp master { nThreads = omp_get_num_threads(); blksThreadReg = nBlocks / nThreads; blksThreadTail = blksThreadReg + nBlocks % nThreads; } #pragma omp barrier { int id = omp_get_thread_num(); Ipp8u* pThreadSrc = (Ipp8u*)pSrc + id*blksThreadReg * MBS_DES; Ipp8u* pThreadDst = (Ipp8u*)pDst + id*blksThreadReg * MBS_DES; int blkThread = (id==(nThreads-1))? blksThreadTail : blksThreadReg; TDES_EncECB_processing(pThreadSrc, pThreadDst, blkThread, pRKey); } } } return ippStsNoErr; } } #endif /* #ifdef _OPENMP */
sparse_msg_filter.c
/*BHEADER********************************************************************** * Copyright (c) 2008, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * This file is part of HYPRE. See file COPYRIGHT for details. * * HYPRE 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 dated February 1999. * * $Revision$ ***********************************************************************EHEADER*/ #include "_hypre_struct_ls.h" #if 0 /*-------------------------------------------------------------------------- * hypre_SparseMSGFilterSetup *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SparseMSGFilterSetup( hypre_StructMatrix *A, HYPRE_Int *num_grids, HYPRE_Int lx, HYPRE_Int ly, HYPRE_Int lz, HYPRE_Int jump, hypre_StructVector *visitx, hypre_StructVector *visity, hypre_StructVector *visitz ) { HYPRE_Int ierr = 0; hypre_BoxArray *compute_boxes; hypre_Box *compute_box; hypre_Box *A_dbox; hypre_Box *v_dbox; HYPRE_Int Ai; HYPRE_Int vi; HYPRE_Real *Ap; HYPRE_Real *vxp; HYPRE_Real *vyp; HYPRE_Real *vzp; HYPRE_Real lambdax; HYPRE_Real lambday; HYPRE_Real lambdaz; HYPRE_Real lambda_max; hypre_StructStencil *stencil; hypre_Index *stencil_shape; HYPRE_Int stencil_size; HYPRE_Int Astenc; hypre_Index loop_size; hypre_Index cindex; hypre_IndexRef start; hypre_Index startv; hypre_Index stride; hypre_Index stridev; HYPRE_Int i, si, dir, k, l; /*---------------------------------------------------------- * Initialize some things *----------------------------------------------------------*/ stencil = hypre_StructMatrixStencil(A); stencil_shape = hypre_StructStencilShape(stencil); stencil_size = hypre_StructStencilSize(stencil); /*----------------------------------------------------- * Compute encoding digit and strides *-----------------------------------------------------*/ hypre_SetIndex3(stride, 1, 1, 1); l = lx + ly + lz; if ((l >= 1) && (l <= jump)) { k = 1 >> l; hypre_SetIndex3(stridev, (1 >> lx), (1 >> ly), (1 >> lz)); } else { k = 1; hypre_SetIndex3(stridev, 1, 1, 1); hypre_StructVectorSetConstantValues(visitx, 0.0); hypre_StructVectorSetConstantValues(visity, 0.0); hypre_StructVectorSetConstantValues(visitz, 0.0); } /*----------------------------------------------------- * Compute visit vectors *-----------------------------------------------------*/ hypre_SetIndex3(cindex, 0, 0, 0); compute_boxes = hypre_StructGridBoxes(hypre_StructMatrixGrid(A)); hypre_ForBoxI(i, compute_boxes) { compute_box = hypre_BoxArrayBox(compute_boxes, i); A_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(A), i); v_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(visitx), i); vxp = hypre_StructVectorBoxData(visitx, i); vyp = hypre_StructVectorBoxData(visity, i); vzp = hypre_StructVectorBoxData(visitz, i); start = hypre_BoxIMin(compute_box); hypre_StructMapCoarseToFine(start, cindex, stridev, startv); hypre_BoxGetSize(compute_box, loop_size); hypre_BoxLoop2Begin(hypre_StructMatrixNDim(A), loop_size, A_dbox, start, stride, Ai, v_dbox, startv, stridev, vi); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,Ai,vi,lambdax,lambday,lambdaz,si,Ap,Astenc,lambda_max,dir) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop2For(Ai, vi) { lambdax = 0.0; lambday = 0.0; lambdaz = 0.0; for (si = 0; si < stencil_size; si++) { Ap = hypre_StructMatrixBoxData(A, i, si); /* compute lambdax */ Astenc = hypre_IndexD(stencil_shape[si], 0); if (Astenc == 0) { lambdax += Ap[Ai]; } else { lambdax -= Ap[Ai]; } /* compute lambday */ Astenc = hypre_IndexD(stencil_shape[si], 1); if (Astenc == 0) { lambday += Ap[Ai]; } else { lambday -= Ap[Ai]; } /* compute lambdaz */ Astenc = hypre_IndexD(stencil_shape[si], 2); if (Astenc == 0) { lambdaz += Ap[Ai]; } else { lambdaz -= Ap[Ai]; } } lambdax *= lambdax; lambday *= lambday; lambdaz *= lambdaz; lambda_max = 0; dir = -1; if ((lx < num_grids[0] - 1) && (lambdax > lambda_max)) { lambda_max = lambdax; dir = 0; } if ((ly < num_grids[1] - 1) && (lambday > lambda_max)) { lambda_max = lambday; dir = 1; } if ((lz < num_grids[2] - 1) && (lambdaz > lambda_max)) { lambda_max = lambdaz; dir = 2; } if (dir == 0) { vxp[vi] = (HYPRE_Real) ( ((HYPRE_Int) vxp[vi]) | k ); } else if (dir == 1) { vyp[vi] = (HYPRE_Real) ( ((HYPRE_Int) vyp[vi]) | k ); } else if (dir == 2) { vzp[vi] = (HYPRE_Real) ( ((HYPRE_Int) vzp[vi]) | k ); } } hypre_BoxLoop2End(Ai, vi); } return ierr; } /*-------------------------------------------------------------------------- * hypre_SparseMSGFilter *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SparseMSGFilter( hypre_StructVector *visit, hypre_StructVector *e, HYPRE_Int lx, HYPRE_Int ly, HYPRE_Int lz, HYPRE_Int jump ) { HYPRE_Int ierr = 0; hypre_BoxArray *compute_boxes; hypre_Box *compute_box; hypre_Box *e_dbox; hypre_Box *v_dbox; HYPRE_Int ei; HYPRE_Int vi; HYPRE_Real *ep; HYPRE_Real *vp; hypre_Index loop_size; hypre_Index cindex; hypre_IndexRef start; hypre_Index startv; hypre_Index stride; hypre_Index stridev; HYPRE_Int i, k, l; /*----------------------------------------------------- * Compute encoding digit and strides *-----------------------------------------------------*/ hypre_SetIndex3(stride, 1, 1, 1); l = lx + ly + lz; if ((l >= 1) && (l <= jump)) { k = 1 >> l; hypre_SetIndex3(stridev, (1 >> lx), (1 >> ly), (1 >> lz)); } else { k = 1; hypre_SetIndex3(stridev, 1, 1, 1); } /*----------------------------------------------------- * Filter interpolated error *-----------------------------------------------------*/ hypre_SetIndex3(cindex, 0, 0, 0); compute_boxes = hypre_StructGridBoxes(hypre_StructVectorGrid(e)); hypre_ForBoxI(i, compute_boxes) { compute_box = hypre_BoxArrayBox(compute_boxes, i); e_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(e), i); v_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(visit), i); ep = hypre_StructVectorBoxData(e, i); vp = hypre_StructVectorBoxData(visit, i); start = hypre_BoxIMin(compute_box); hypre_StructMapCoarseToFine(start, cindex, stridev, startv); hypre_BoxGetSize(compute_box, loop_size); hypre_BoxLoop2Begin(hypre_StructVectorNDim(e), loop_size, e_dbox, start, stride, ei, v_dbox, startv, stridev, vi); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,ei,vi) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop2For(ei, vi) { if ( !(((HYPRE_Int) vp[vi]) & k) ) { ep[ei] = 0.0; } } hypre_BoxLoop2End(ei, vi); } return ierr; } #else /*-------------------------------------------------------------------------- * hypre_SparseMSGFilterSetup *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SparseMSGFilterSetup( hypre_StructMatrix *A, HYPRE_Int *num_grids, HYPRE_Int lx, HYPRE_Int ly, HYPRE_Int lz, HYPRE_Int jump, hypre_StructVector *visitx, hypre_StructVector *visity, hypre_StructVector *visitz ) { HYPRE_Int ierr = 0; hypre_BoxArray *compute_boxes; hypre_Box *compute_box; hypre_Box *A_dbox; hypre_Box *v_dbox; HYPRE_Int Ai; HYPRE_Int vi; HYPRE_Real *Ap; HYPRE_Real *vxp; HYPRE_Real *vyp; HYPRE_Real *vzp; HYPRE_Real lambdax; HYPRE_Real lambday; HYPRE_Real lambdaz; hypre_StructStencil *stencil; hypre_Index *stencil_shape; HYPRE_Int stencil_size; HYPRE_Int Astenc; hypre_Index loop_size; hypre_Index cindex; hypre_IndexRef start; hypre_Index startv; hypre_Index stride; hypre_Index stridev; HYPRE_Int i, si; /*---------------------------------------------------------- * Initialize some things *----------------------------------------------------------*/ stencil = hypre_StructMatrixStencil(A); stencil_shape = hypre_StructStencilShape(stencil); stencil_size = hypre_StructStencilSize(stencil); /*----------------------------------------------------- * Compute encoding digit and strides *-----------------------------------------------------*/ hypre_SetIndex3(stride, 1, 1, 1); hypre_SetIndex3(stridev, 1, 1, 1); /*----------------------------------------------------- * Compute visit vectors *-----------------------------------------------------*/ hypre_SetIndex3(cindex, 0, 0, 0); compute_boxes = hypre_StructGridBoxes(hypre_StructMatrixGrid(A)); hypre_ForBoxI(i, compute_boxes) { compute_box = hypre_BoxArrayBox(compute_boxes, i); A_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(A), i); v_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(visitx), i); vxp = hypre_StructVectorBoxData(visitx, i); vyp = hypre_StructVectorBoxData(visity, i); vzp = hypre_StructVectorBoxData(visitz, i); start = hypre_BoxIMin(compute_box); hypre_StructMapCoarseToFine(start, cindex, stridev, startv); hypre_BoxGetSize(compute_box, loop_size); hypre_BoxLoop2Begin(hypre_StructMatrixNDim(A), loop_size, A_dbox, start, stride, Ai, v_dbox, startv, stridev, vi); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,Ai,vi,lambdax,lambday,lambdaz,si,Ap,Astenc) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop2For(Ai, vi) { lambdax = 0.0; lambday = 0.0; lambdaz = 0.0; for (si = 0; si < stencil_size; si++) { Ap = hypre_StructMatrixBoxData(A, i, si); /* compute lambdax */ Astenc = hypre_IndexD(stencil_shape[si], 0); if (Astenc == 0) { lambdax += Ap[Ai]; } else { lambdax -= Ap[Ai]; } /* compute lambday */ Astenc = hypre_IndexD(stencil_shape[si], 1); if (Astenc == 0) { lambday += Ap[Ai]; } else { lambday -= Ap[Ai]; } /* compute lambdaz */ Astenc = hypre_IndexD(stencil_shape[si], 2); if (Astenc == 0) { lambdaz += Ap[Ai]; } else { lambdaz -= Ap[Ai]; } } lambdax *= lambdax; lambday *= lambday; lambdaz *= lambdaz; vxp[vi] = lambdax / (lambdax + lambday + lambdaz); vyp[vi] = lambday / (lambdax + lambday + lambdaz); vzp[vi] = lambdaz / (lambdax + lambday + lambdaz); } hypre_BoxLoop2End(Ai, vi); } return ierr; } /*-------------------------------------------------------------------------- * hypre_SparseMSGFilter *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SparseMSGFilter( hypre_StructVector *visit, hypre_StructVector *e, HYPRE_Int lx, HYPRE_Int ly, HYPRE_Int lz, HYPRE_Int jump ) { HYPRE_Int ierr = 0; hypre_BoxArray *compute_boxes; hypre_Box *compute_box; hypre_Box *e_dbox; hypre_Box *v_dbox; HYPRE_Int ei; HYPRE_Int vi; HYPRE_Real *ep; HYPRE_Real *vp; hypre_Index loop_size; hypre_Index cindex; hypre_IndexRef start; hypre_Index startv; hypre_Index stride; hypre_Index stridev; HYPRE_Int i; /*----------------------------------------------------- * Compute encoding digit and strides *-----------------------------------------------------*/ hypre_SetIndex3(stride, 1, 1, 1); hypre_SetIndex3(stridev, 1, 1, 1); /*----------------------------------------------------- * Filter interpolated error *-----------------------------------------------------*/ hypre_SetIndex3(cindex, 0, 0, 0); compute_boxes = hypre_StructGridBoxes(hypre_StructVectorGrid(e)); hypre_ForBoxI(i, compute_boxes) { compute_box = hypre_BoxArrayBox(compute_boxes, i); e_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(e), i); v_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(visit), i); ep = hypre_StructVectorBoxData(e, i); vp = hypre_StructVectorBoxData(visit, i); start = hypre_BoxIMin(compute_box); hypre_StructMapCoarseToFine(start, cindex, stridev, startv); hypre_BoxGetSize(compute_box, loop_size); hypre_BoxLoop2Begin(hypre_StructVectorNDim(e), loop_size, e_dbox, start, stride, ei, v_dbox, startv, stridev, vi); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,ei,vi) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop2For(ei, vi) { ep[ei] *= vp[vi]; } hypre_BoxLoop2End(ei, vi); } return ierr; } #endif
hot.c
#include "hot.h" #include "../../comms.h" #include "../../omp4/shared.h" #include "../../profiler.h" #include "../hot_data.h" #include "../hot_interface.h" #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> // Performs the CG solve, you always want to perform these steps, regardless // of the context of the problem etc. void solve_diffusion_2d(const int nx, const int ny, Mesh* mesh, const int max_inners, const double dt, const double heat_capacity, const double conductivity, double* temperature, double* r, double* p, double* density, double* s_x, double* s_y, double* Ap, int* end_niters, double* end_error, double* reduce_array, const double* edgedx, const double* edgedy) { // Store initial residual double local_old_r2 = initialise_cg(nx, ny, mesh->pad, dt, heat_capacity, conductivity, p, r, temperature, density, s_x, s_y, edgedx, edgedy); double global_old_r2 = reduce_all_sum(local_old_r2); handle_boundary_2d(nx, ny, mesh, p, NO_INVERT, PACK); handle_boundary_2d(nx, ny, mesh, temperature, NO_INVERT, PACK); // TODO: Can one of the allreduces be removed with kernel fusion? int ii = 0; for (ii = 0; ii < max_inners; ++ii) { const double local_pAp = calculate_pAp(nx, ny, mesh->pad, s_x, s_y, p, Ap); const double global_pAp = reduce_all_sum(local_pAp); const double alpha = global_old_r2 / global_pAp; const double local_new_r2 = calculate_new_r2(nx, ny, mesh->pad, alpha, temperature, p, r, Ap); const double global_new_r2 = reduce_all_sum(local_new_r2); const double beta = global_new_r2 / global_old_r2; handle_boundary_2d(nx, ny, mesh, temperature, NO_INVERT, PACK); // Check if the solution has converged if (fabs(global_new_r2) < EPS) { global_old_r2 = global_new_r2; printf("Successfully converged.\n"); break; } update_conjugate(nx, ny, mesh->pad, beta, r, p); handle_boundary_2d(nx, ny, mesh, p, NO_INVERT, PACK); // Store the old squared residual global_old_r2 = global_new_r2; } *end_niters = ii + 1; *end_error = global_old_r2; } // Initialises the CG solver double initialise_cg(const int nx, const int ny, const int pad, const double dt, const double heat_capacity, const double conductivity, double* p, double* r, const double* temperature, const double* density, double* s_x, double* s_y, const double* edgedx, const double* edgedy) { START_PROFILING(&compute_profile); int nteams; // https://inldigitallibrary.inl.gov/sti/3952796.pdf // Take the average of the coefficients at the cells surrounding // each face #ifdef CLANG nteams = (int)ceil((nx + 1) * ny / (double)NTHREADS); #pragma omp target teams distribute parallel for collapse(2) \ thread_limit(NTHREADS) num_teams(nteams) #else #pragma omp target teams distribute parallel for #endif for (int ii = pad; ii < ny - pad; ++ii) { for (int jj = pad; jj < (nx + 1) - pad; ++jj) { s_x[(ii) * (nx + 1) + (jj)] = (dt * conductivity * (density[(ii)*nx + (jj)] + density[(ii)*nx + (jj - 1)])) / (2.0 * density[(ii)*nx + (jj)] * density[(ii)*nx + (jj - 1)] * edgedx[jj] * edgedx[jj] * heat_capacity); } } #ifdef CLANG nteams = (int)ceil(nx * (ny + 1) / (double)NTHREADS); #pragma omp target teams distribute parallel for collapse(2) \ thread_limit(NTHREADS) num_teams(nteams) #else #pragma omp target teams distribute parallel for #endif for (int ii = pad; ii < (ny + 1) - pad; ++ii) { for (int jj = pad; jj < nx - pad; ++jj) { s_y[(ii)*nx + (jj)] = (dt * conductivity * (density[(ii)*nx + (jj)] + density[(ii - 1) * nx + (jj)])) / (2.0 * density[(ii)*nx + (jj)] * density[(ii - 1) * nx + (jj)] * edgedy[ii] * edgedy[ii] * heat_capacity); } } double initial_r2 = 0.0; nteams = (int)ceil(nx * ny / (double)NTHREADS); #ifdef CLANG #pragma omp target teams distribute parallel for collapse(2) \ thread_limit(NTHREADS) num_teams(nteams) map(tofrom : initial_r2) \ reduction(+ : initial_r2) #else #pragma omp target teams distribute parallel for reduction(+ : initial_r2) #endif for (int ii = pad; ii < ny - pad; ++ii) { for (int jj = pad; jj < nx - pad; ++jj) { r[(ii)*nx + (jj)] = temperature[(ii)*nx + (jj)] - ((s_y[(ii)*nx + (jj)] + s_x[(ii) * (nx + 1) + (jj)] + 1.0 + s_x[(ii) * (nx + 1) + (jj + 1)] + s_y[(ii + 1) * nx + (jj)]) * temperature[(ii)*nx + (jj)] - s_y[(ii)*nx + (jj)] * temperature[(ii - 1) * nx + (jj)] - s_x[(ii) * (nx + 1) + (jj)] * temperature[(ii)*nx + (jj - 1)] - s_x[(ii) * (nx + 1) + (jj + 1)] * temperature[(ii)*nx + (jj + 1)] - s_y[(ii + 1) * nx + (jj)] * temperature[(ii + 1) * nx + (jj)]); p[(ii)*nx + (jj)] = r[(ii)*nx + (jj)]; initial_r2 += r[(ii)*nx + (jj)] * r[(ii)*nx + (jj)]; } } STOP_PROFILING(&compute_profile, "initialise cg"); return initial_r2; } // Calculates a value for alpha double calculate_pAp(const int nx, const int ny, const int pad, const double* s_x, const double* s_y, double* p, double* Ap) { START_PROFILING(&compute_profile); // You don't need to use a matrix as the band matrix is fully predictable // from the 5pt stencil double pAp = 0.0; #ifdef CLANG const int nteams = (int)ceil(nx * ny / (double)NTHREADS); #pragma omp target teams distribute parallel for collapse(2) thread_limit( \ NTHREADS) num_teams(nteams) map(tofrom : pAp) reduction(+ : pAp) #else #pragma omp target teams distribute parallel for reduction(+ : pAp) #endif for (int ii = pad; ii < ny - pad; ++ii) { for (int jj = pad; jj < nx - pad; ++jj) { Ap[(ii)*nx + (jj)] = (s_y[(ii)*nx + (jj)] + s_x[(ii) * (nx + 1) + (jj)] + 1.0 + s_x[(ii) * (nx + 1) + (jj + 1)] + s_y[(ii + 1) * nx + (jj)]) * p[(ii)*nx + (jj)] - s_y[(ii)*nx + (jj)] * p[(ii - 1) * nx + (jj)] - s_x[(ii) * (nx + 1) + (jj)] * p[(ii)*nx + (jj - 1)] - s_x[(ii) * (nx + 1) + (jj + 1)] * p[(ii)*nx + (jj + 1)] - s_y[(ii + 1) * nx + (jj)] * p[(ii + 1) * nx + (jj)]; pAp += p[(ii)*nx + (jj)] * Ap[(ii)*nx + (jj)]; } } STOP_PROFILING(&compute_profile, "calculate alpha"); return pAp; } // Updates the current guess using the calculated alpha double calculate_new_r2(const int nx, const int ny, const int pad, double alpha, double* temperature, double* p, double* r, double* Ap) { START_PROFILING(&compute_profile); double new_r2 = 0.0; #ifdef CLANG const int nteams = (int)ceil(nx * ny / (double)NTHREADS); #pragma omp target teams distribute parallel for collapse(2) thread_limit( \ NTHREADS) num_teams(nteams) map(tofrom : new_r2) reduction(+ : new_r2) #else #pragma omp target teams distribute parallel for reduction(+ : new_r2) #endif for (int ii = pad; ii < ny - pad; ++ii) { for (int jj = pad; jj < nx - pad; ++jj) { temperature[(ii)*nx + (jj)] += alpha * p[(ii)*nx + (jj)]; r[(ii)*nx + (jj)] -= alpha * Ap[(ii)*nx + (jj)]; new_r2 += r[(ii)*nx + (jj)] * r[(ii)*nx + (jj)]; } } STOP_PROFILING(&compute_profile, "calculate new r2"); return new_r2; } // Updates the conjugate from the calculated beta and residual void update_conjugate(const int nx, const int ny, const int pad, const double beta, const double* r, double* p) { START_PROFILING(&compute_profile); #ifdef CLANG const int nteams = (int)ceil(nx * ny / (double)NTHREADS); #pragma omp target teams distribute parallel for collapse(2) \ thread_limit(NTHREADS) num_teams(nteams) #else #pragma omp target teams distribute parallel for #endif for (int ii = pad; ii < ny - pad; ++ii) { for (int jj = pad; jj < nx - pad; ++jj) { p[(ii)*nx + (jj)] = r[(ii)*nx + (jj)] + beta * p[(ii)*nx + (jj)]; } } STOP_PROFILING(&compute_profile, "update conjugate"); }
LBMClass.h
#ifndef LIDDRIVENCAVITYLBM_LBMCLASS_H #define LIDDRIVENCAVITYLBM_LBMCLASS_H #include <iostream> #include <vector> #include <math.h> #include <omp.h> using namespace std; extern const double Re; extern const unsigned int N; extern const double Utop; extern const double Ubot; extern const double Vlef; extern const double Vrig; extern const int SAVETXT; extern const double THRESH; extern const int THREADS; extern const int MBounds; extern const int MCollide; extern const int BC; extern const unsigned int Q; extern const double MAXITER; extern const double NU; extern const double TAU; extern const double MAGIC; extern const double RHO0; extern const unsigned int N2; extern const unsigned int NQ; extern const double w[9]; extern const int c[9][2]; extern const int opp[9]; extern const int half[4]; extern const int prntInt; extern const unsigned int Nm1; extern const unsigned int Nm2; extern const int GM[9][9]; extern const double GMinv[9][9]; extern double start,stop; class LBMClass{ public: LBMClass(): _f1(NQ,0.0), _f2(NQ,0.0), _fstar(NQ, 0.0), _u1(N2, 0.0) ,_u2(N2, 0.0), _rho(N2, RHO0), _x(N, 0.0), _error(100, 0.0),_vmag(N2,0.0),_stress(N2, 0.0), _vort(N2, 0.0),_df(),_df0(), _filename1(),_filename2(), _OMEGA(0.0), _OMEGAm(0.0), _CS(0.0), _MACH(0.0), _rhobar(1.0),_omega_e(),_omega_eps(), _omega_q(),_omega_nu(), _GS{} { // Initialize x if (MBounds == 0) linspace(_x,(0.5 / N), (N - 0.5) / N,N); else linspace(_x, 0.0,1.0 ,N); _CS = 1.0 / sqrt(3.0); _MACH = Utop / _CS; _OMEGA = 1.0 / TAU; _OMEGAm = 1.0 / (0.5 + ((MAGIC) / ((1.0 / (_OMEGA)) - 0.5))); _omega_e = 1.1; // Bulk viscosity _omega_eps = 1.1; // free parameter _omega_q = 1.1; // free parameter _omega_nu = _OMEGA; // Shear viscosity _GS[0] = 0.0; _GS[1] = _omega_e; _GS[2] = _omega_eps; _GS[3] = 0.0; _GS[4] = _omega_q; _GS[5] = 0.0; _GS[6] = _omega_q; _GS[7] = _omega_nu; _GS[8] = _omega_nu; sprintf(_filename1,"Solution_n=%d_Re=%.0f_BCM=%d_CM=%d_U=%0.2f.dat",N,Re,MBounds,MCollide, Utop); sprintf(_filename2,"Error_n=%d_Re=%.0f_BCM=%d_CM=%d_U=%0.2f.txt",N,Re,MBounds,MCollide,Utop); // Initialize f int ind1,ind2; #pragma omp parallel for private(ind1,ind2) collapse(2) for (unsigned int i = 0; i < N; i++) { for (unsigned int j = 0; j < N; j++) { ind1 = LU2(i, j); for (unsigned int k = 0; k < Q; k++) { ind2 = LU3(i, j, k); _f1[ind2] = calcfeq(k,ind1,1); _f2[ind2] = _f1[ind2]; } } } // Print parameters printf("Re =\t%.0f\n", Re); printf("U =\t%.3e\n", Utop); printf("M =\t%.3e\n", Utop * sqrt(3)); printf("N =\t%d\n", N); printf("tau =\t%.3e\n", TAU); printf("nu =\t%.3e\n", NU); } // Collide Methods inline void collideSRT() { int ind1{}, ind2{}; double Fsource{}; #pragma omp parallel for private(ind1, ind2,Fsource) collapse(2) for (unsigned int i = 0; i < N; i++) { for (unsigned int j = 0; j < N; j++) { ind1 = LU2(i, j); for (unsigned int k = 0; k < Q; k++) { ind2 = LU3(i, j, k); _fstar[ind2] = (1.0 - _OMEGA) * _f1[ind2] + _OMEGA * calcfeq(k, ind1,1); if (BC == 1){ Fsource = (1.0 - 0.5 * _OMEGA) * w[k] * (3.0 * (c[k][0] - _u1[ind1]) + 9.0 * (c[k][0] * _u1[ind1] + c[k][1] * _u2[ind1]) * c[k][0]) * _forceX + (3.0 * (c[k][1] - _u2[ind1]) + 9.0 * (c[k][0] * _u1[ind1] + c[k][1] * _u2[ind1]) * c[k][1]) * _forceY; _fstar[ind2] += Fsource; } } } } if (BC == 0 || BC == 1) virtualnode(); } inline void collideTRT(){ double fplus{},fminus{},feqplus{},feqminus{},feq[9]{}; int ind1{},l{},notl{}; #pragma omp parallel for private(fplus,fminus,feqplus,feqminus,feq,l,notl,ind1) collapse(2) for (unsigned int i = 0; i < N; i++){ for (unsigned int j = 0; j < N; j++){ ind1 = LU2(i, j); for (unsigned int k = 0; k < Q; k++) feq[k] = calcfeq(k,ind1,1); // Rest population fplus = _f1[LU3(i,j,0)]; feqplus = feq[0]; _fstar[LU3(i, j, 0)] = _f1[LU3(i, j, 0)] - _OMEGA * (fplus - feqplus); for (unsigned int k = 0; k < 4; k++) { l = half[k]; notl = opp[l]; fplus = 0.5 * (_f1[LU3(i,j,l)] + _f1[LU3(i,j,notl)]); fminus = 0.5 * (_f1[LU3(i,j,l)] - _f1[LU3(i,j,notl)]); feqplus = 0.5 * (feq[l] + feq[notl]); feqminus = 0.5 * (feq[l] - feq[notl]); fplus = _OMEGA * (fplus - feqplus); fminus = _OMEGAm * (fminus - feqminus); _fstar[LU3(i, j, l)] = _f1[LU3(i, j, l)] - fplus - fminus; _fstar[LU3(i, j, notl)] = _f1[LU3(i, j, notl)] - fplus + fminus; } } } if (BC == 0 || BC == 1) virtualnode(); } inline void collideMRT(){ #pragma omp parallel { int ind1; vector<double> _meq(Q,0.0),_mstar(Q,0.0); // moments double _m{}; // moments #pragma omp for collapse(2) for (unsigned int i = 0; i < N; i++) { for (unsigned int j = 0; j < N; j++) { ind1 = LU2(i,j); calcmeq(_meq, _u1[ind1], _u2[ind1], _rho[ind1]); for (unsigned int k = 0; k < Q; k++){ _m = GM[k][0] * _f1[LU3(i,j,0)] + GM[k][1] * _f1[LU3(i,j,1)] + GM[k][2] * _f1[LU3(i,j,2)] +GM[k][3] * _f1[LU3(i,j,3)] + GM[k][4] * _f1[LU3(i,j,4)] + GM[k][5] * _f1[LU3(i,j,5)] + GM[k][6] * _f1[LU3(i,j,6)] + GM[k][7] * _f1[LU3(i,j,7)] + GM[k][8] * _f1[LU3(i,j,8)]; _mstar[k] = _m - _GS[k] * (_m - _meq[k]); } if (BC == 1) { _mstar[1] += (1.0 - 0.5 * _GS[1]) * (6.0 * (_forceX * _u1[ind1] + _forceY * _u2[ind1])); _mstar[2] += (1.0 - 0.5 * _GS[2]) * (-6.0 * (_forceX * _u1[ind1] + _forceY * _u2[ind1])); _mstar[3] += (1.0 - 0.5 * _GS[3]) * (_forceX); _mstar[4] += (1.0 - 0.5 * _GS[4]) * (-_forceX); _mstar[5] += (1.0 - 0.5 * _GS[5]) * (_forceY); _mstar[6] += (1.0 - 0.5 * _GS[6]) * (-_forceY); _mstar[7] += (1.0 - 0.5 * _GS[7]) * (2.0 * (_forceX * _u1[ind1] - _forceY * _u2[ind1])); _mstar[8] += (1.0 - 0.5 * _GS[8]) * (_forceY * _u1[ind1] + _forceX * _u2[ind1]); } for (unsigned int k = 0; k < Q; k++){ _fstar[LU3(i, j, k)] = GMinv[k][0] * _mstar[0] + GMinv[k][1] * _mstar[1] + GMinv[k][2] * _mstar[2] + GMinv[k][3] * _mstar[3] + GMinv[k][4] * _mstar[4] + GMinv[k][5] * _mstar[5] + GMinv[k][6] * _mstar[6] + GMinv[k][7] * _mstar[7] + GMinv[k][8] * _mstar[8]; } } } } if (BC == 0 || BC == 1) virtualnode(); } // Stream Methods inline void streamPush() { #pragma omp parallel { int inew, jnew; #pragma omp for collapse(2) for (unsigned int i = 0; i < N; i++) { for (unsigned int j = 0; j < N; j++) { for (unsigned int k = 0; k < Q; k++) { inew = i + c[k][0]; jnew = j + c[k][1]; if (inew < N && inew >= 0 && jnew < N && jnew >= 0) _f2[LU3(inew, jnew, k)] = _fstar[LU3(i, j, k)]; } } } } } inline void streamPull() { #pragma omp parallel { int iold, jold; #pragma omp for collapse(2) for (unsigned int i = 0; i < N; i++) { for (unsigned int j = 0; j < N; j++) { for (unsigned int k = 0; k < Q; k++) { iold = i - c[k][0]; jold = j - c[k][1]; if (iold < N && iold >= 0 && jold < N && jold >= 0) _f2[LU3(i, j, k)] = _fstar[LU3(iold, jold, k)]; } } } } } // Bounday Condition Methods inline void NEBB(){ switch (BC){ case 2 : { // Lid-driven cavity flow const double sixth = 1.0 / 6.0, twothirds = 2.0 / 3.0, twelfth = 1.0 / 12.0; double rho{_rhobar}; for (unsigned int i = 1; i < N - 1; i++) { // Left wall, general case rho = _f2[LU3(0, i, 0)] + _f2[LU3(0, i, 2)] + _f2[LU3(0, i, 4)] + 2.0 * (_f2[LU3(0, i, 3)] + _f2[LU3(0, i, 6)] + _f2[LU3(0, i, 7)]); _f2[LU3(0, i, 1)] = _f2[LU3(0, i, 3)]; _f2[LU3(0, i, 5)] = _f2[LU3(0, i, 7)] - 0.5 * (_f2[LU3(0, i, 2)] - _f2[LU3(0, i, 4)]) + 0.5 * rho * Vlef; _f2[LU3(0, i, 8)] = _f2[LU3(0, i, 6)] + 0.5 * (_f2[LU3(0, i, 2)] - _f2[LU3(0, i, 4)]) - 0.5 * rho * Vlef; // Right wall, general case rho = _f2[LU3(Nm1, i, 0)] + _f2[LU3(Nm1, i, 2)] + _f2[LU3(Nm1, i, 4)] + 2.0 * (_f2[LU3(Nm1, i, 1)] + _f2[LU3(Nm1, i, 5)] + _f2[LU3(Nm1, i, 8)]); _f2[LU3(Nm1, i, 3)] = _f2[LU3(Nm1, i, 1)]; _f2[LU3(Nm1, i, 7)] = _f2[LU3(Nm1, i, 5)] + 0.5 * (_f2[LU3(Nm1, i, 2)] - _f2[LU3(Nm1, i, 4)]) - 0.5 * rho * Vrig; _f2[LU3(Nm1, i, 6)] = _f2[LU3(Nm1, i, 8)] - 0.5 * (_f2[LU3(Nm1, i, 2)] - _f2[LU3(Nm1, i, 4)]) + 0.5 * rho * Vrig; // Top wall, general case rho = _f2[LU3(i, Nm1, 0)] + _f2[LU3(i, Nm1, 1)] + _f2[LU3(i, Nm1, 3)] + 2.0 * (_f2[LU3(i, Nm1, 2)] + _f2[LU3(i, Nm1, 6)] + _f2[LU3(i, Nm1, 5)]); _f2[LU3(i, Nm1, 4)] = _f2[LU3(i, Nm1, 2)]; _f2[LU3(i, Nm1, 7)] = _f2[LU3(i, Nm1, 5)] + 0.5 * (_f2[LU3(i, Nm1, 1)] - _f2[LU3(i, Nm1, 3)]) - 0.5 * rho * Utop; _f2[LU3(i, Nm1, 8)] = _f2[LU3(i, Nm1, 6)] - 0.5 * (_f2[LU3(i, Nm1, 1)] - _f2[LU3(i, Nm1, 3)]) + 0.5 * rho * Utop; // Bottom wall, general case rho = _f2[LU3(i, 0, 0)] + _f2[LU3(i, 0, 1)] + _f2[LU3(i, 0, 3)] + 2.0 * (_f2[LU3(i, 0, 4)] + _f2[LU3(i, 0, 7)] + _f2[LU3(i, 0, 8)]); _f2[LU3(i, 0, 2)] = _f2[LU3(i, 0, 4)]; _f2[LU3(i, 0, 5)] = _f2[LU3(i, 0, 7)] - 0.5 * (_f2[LU3(i, 0, 1)] - _f2[LU3(i, 0, 3)]) + 0.5 * rho * Ubot; _f2[LU3(i, 0, 6)] = _f2[LU3(i, 0, 8)] + 0.5 * (_f2[LU3(i, 0, 1)] - _f2[LU3(i, 0, 3)]) - 0.5 * rho * Ubot; } // Corners rho = 1.0; // Bottom Left (0,0) knowns: 1,5,2, unknowns: 0,6,8 _f2[LU3(0, 0, 1)] = _f2[LU3(0, 0, 3)] + twothirds * rho * Ubot; _f2[LU3(0, 0, 2)] = _f2[LU3(0, 0, 4)] + twothirds * rho * Vlef; _f2[LU3(0, 0, 5)] = _f2[LU3(0, 0, 7)] + sixth * rho * (Ubot + Vlef); _f2[LU3(0, 0, 6)] = twelfth * rho * (Vlef - Ubot); _f2[LU3(0, 0, 8)] = -_f2[LU3(0, 0, 6)]; _f2[LU3(0, 0, 0)] = rho - (_f2[LU3(0, 0, 1)] + _f2[LU3(0, 0, 2)] + _f2[LU3(0, 0, 3)] + _f2[LU3(0, 0, 4)] + _f2[LU3(0, 0, 5)] + _f2[LU3(0, 0, 6)] + _f2[LU3(0, 0, 7)] + _f2[LU3(0, 0, 8)]); // Bottom Right (Nm1,0) knowns: 2,3,6, unknowns: 0, 5, 7 // rho = 0.5 * (_rho[LU2(Nm2,0)] + _rho[LU2(Nm1,1)]); _f2[LU3(Nm1, 0, 2)] = _f2[LU3(Nm1, 0, 4)] + twothirds * rho * Vrig; _f2[LU3(Nm1, 0, 3)] = _f2[LU3(Nm1, 0, 1)] - twothirds * rho * Ubot; _f2[LU3(Nm1, 0, 6)] = _f2[LU3(Nm1, 0, 8)] + sixth * rho * (-Ubot + Vrig); _f2[LU3(Nm1, 0, 5)] = twelfth * rho * (Vrig + Ubot); _f2[LU3(Nm1, 0, 7)] = -_f2[LU3(Nm1, 0, 5)]; _f2[LU3(Nm1, 0, 0)] = rho - (_f2[LU3(Nm1, 0, 1)] + _f2[LU3(Nm1, 0, 2)] + _f2[LU3(Nm1, 0, 3)] + _f2[LU3(Nm1, 0, 4)] + _f2[LU3(Nm1, 0, 5)] + _f2[LU3(Nm1, 0, 6)] + _f2[LU3(Nm1, 0, 7)] + _f2[LU3(Nm1, 0, 8)]); // Top Left (0,Nm1) knowns: 1,4,8, unknowns: 0, 5, 7 // rho = 0.5 * (_rho[LU2(0, Nm2)] + _rho[LU2(1, Nm1)]); _f2[LU3(0, Nm1, 1)] = _f2[LU3(0, Nm1, 3)] + twothirds * rho * Utop; _f2[LU3(0, Nm1, 4)] = _f2[LU3(0, Nm1, 2)] - twothirds * rho * Vlef; _f2[LU3(0, Nm1, 8)] = _f2[LU3(0, Nm1, 6)] + sixth * rho * (Utop - Vlef); _f2[LU3(0, Nm1, 5)] = twelfth * rho * (Vlef + Utop); _f2[LU3(0, Nm1, 7)] = -_f2[LU3(0, Nm1, 5)]; _f2[LU3(0, Nm1, 0)] = rho - (_f2[LU3(0, Nm1, 1)] + _f2[LU3(0, Nm1, 2)] + _f2[LU3(0, Nm1, 3)] + _f2[LU3(0, Nm1, 4)] + _f2[LU3(0, Nm1, 5)] + _f2[LU3(0, Nm1, 6)] + _f2[LU3(0, Nm1, 7)] + _f2[LU3(0, Nm1, 8)]); // Top Right (Nm1,Nm1) knowns: 3,7,4, unknowns: 0, 6, 8 // rho = 0.5 * (_rho[LU2(Nm2, Nm1)] + _rho[LU2(Nm1, Nm2)]); _f2[LU3(Nm1, Nm1, 4)] = _f2[LU3(Nm1, Nm1, 2)] - twothirds * rho * Vrig; _f2[LU3(Nm1, Nm1, 3)] = _f2[LU3(Nm1, Nm1, 1)] - twothirds * rho * Utop; _f2[LU3(Nm1, Nm1, 7)] = _f2[LU3(Nm1, Nm1, 5)] - sixth * rho * (Utop + Vrig); _f2[LU3(Nm1, Nm1, 6)] = twelfth * rho * (Vrig - Utop); _f2[LU3(Nm1, Nm1, 8)] = -_f2[LU3(Nm1, Nm1, 6)]; _f2[LU3(Nm1, Nm1, 0)] = rho - (_f2[LU3(Nm1, Nm1, 1)] + _f2[LU3(Nm1, Nm1, 2)] + _f2[LU3(Nm1, Nm1, 3)] + _f2[LU3(Nm1, Nm1, 4)] + _f2[LU3(Nm1, Nm1, 5)] + _f2[LU3(Nm1, Nm1, 6)] + _f2[LU3(Nm1, Nm1, 7)] + _f2[LU3(Nm1, Nm1, 8)]); break; } case 1: { // Poiseuille Flow for (unsigned int i = 0; i < N; i++) { // Top wall, general case _f2[LU3(i, Nm1, 4)] = _f2[LU3(i, Nm1, 2)]; _f2[LU3(i, Nm1, 7)] = _f2[LU3(i, Nm1, 5)] + 0.5 * (_f2[LU3(i, Nm1, 1)] - _f2[LU3(i, Nm1, 3)]); _f2[LU3(i, Nm1, 8)] = _f2[LU3(i, Nm1, 6)] - 0.5 * (_f2[LU3(i, Nm1, 1)] - _f2[LU3(i, Nm1, 3)]); // Bottom wall, general case _f2[LU3(i, 0, 2)] = _f2[LU3(i, 0, 4)]; _f2[LU3(i, 0, 5)] = _f2[LU3(i, 0, 7)] - 0.5 * (_f2[LU3(i, 0, 1)] - _f2[LU3(i, 0, 3)]); _f2[LU3(i, 0, 6)] = _f2[LU3(i, 0, 8)] + 0.5 * (_f2[LU3(i, 0, 1)] - _f2[LU3(i, 0, 3)]); } break; } case 0: { // Couette Flow double rho{}; for (unsigned int i = 0; i < N; i++) { // Top wall, general case rho = _f2[LU3(i, Nm1, 0)] + _f2[LU3(i, Nm1, 1)] + _f2[LU3(i, Nm1, 3)] + 2.0 * (_f2[LU3(i, Nm1, 2)] + _f2[LU3(i, Nm1, 6)] + _f2[LU3(i, Nm1, 5)]); _f2[LU3(i, Nm1, 4)] = _f2[LU3(i, Nm1, 2)]; _f2[LU3(i, Nm1, 7)] = _f2[LU3(i, Nm1, 5)] + 0.5 * (_f2[LU3(i, Nm1, 1)] - _f2[LU3(i, Nm1, 3)]) - 0.5 * rho * Utop; _f2[LU3(i, Nm1, 8)] = _f2[LU3(i, Nm1, 6)] - 0.5 * (_f2[LU3(i, Nm1, 1)] - _f2[LU3(i, Nm1, 3)]) + 0.5 * rho * Utop; // Bottom wall, general case rho = _f2[LU3(i, 0, 0)] + _f2[LU3(i, 0, 1)] + _f2[LU3(i, 0, 3)] + 2.0 * (_f2[LU3(i, 0, 4)] + _f2[LU3(i, 0, 7)] + _f2[LU3(i, 0, 8)]); _f2[LU3(i, 0, 2)] = _f2[LU3(i, 0, 4)]; _f2[LU3(i, 0, 5)] = _f2[LU3(i, 0, 7)] - 0.5 * (_f2[LU3(i, 0, 1)] - _f2[LU3(i, 0, 3)]) + 0.5 * rho * Ubot; _f2[LU3(i, 0, 6)] = _f2[LU3(i, 0, 8)] + 0.5 * (_f2[LU3(i, 0, 1)] - _f2[LU3(i, 0, 3)]) - 0.5 * rho * Ubot; } break; } default: { std::printf("Error: Invalid Boundary condition case number\n"); exit(1); } } } // Non-equilibrium extrapolation inline void NEE() { switch (BC){ case 2: { // Lid-driven cavity flow #pragma omp parallel { double rhof{},u1f{},u2f{}; double rhowall{1.0}; #pragma omp for for (unsigned int i = 1; i < N-1; i++){ // Bottom wall, (i, 0) rhowall = _f2[LU3(i,0,0)] +_f2[LU3(i,0,1)] +_f2[LU3(i,0,3)] + 2.0 * (_f2[LU3(i,0,4)] +_f2[LU3(i,0,7)] +_f2[LU3(i,0,8)]); rhof = _f2[LU3(i,1,0)] + _f2[LU3(i,1,1)] + _f2[LU3(i,1,2)] + _f2[LU3(i,1,3)] + _f2[LU3(i,1,4)] + _f2[LU3(i,1,5)]+ _f2[LU3(i,1,6)]+ _f2[LU3(i,1,7)]+ _f2[LU3(i,1,8)]; u1f = ((_f2[LU3(i,1,1)] + _f2[LU3(i,1,5)] + _f2[LU3(i,1,8)]) - (_f2[LU3(i,1,3)] + _f2[LU3(i,1,6)] + _f2[LU3(i,1,7)])) / rhof; u2f = ((_f2[LU3(i,1,2)] + _f2[LU3(i,1,5)] + _f2[LU3(i,1,6)]) - (_f2[LU3(i,1,4)] + _f2[LU3(i,1,7)] + _f2[LU3(i,1,8)])) / rhof; for (unsigned int k = 0; k < Q; k++) _f2[LU3(i,0,k)] = calcfeq(k,Ubot,0.0,rhowall,1) + (_f2[LU3(i,1,k)] - calcfeq(k, u1f, u2f, rhof,1)); // Top Wall, (i,Nm1) rhowall = _f2[LU3(i,Nm1,0)] +_f2[LU3(i,Nm1,1)] +_f2[LU3(i,Nm1,3)] + 2.0 * (_f2[LU3(i,Nm1,2)] +_f2[LU3(i,Nm1,6)] +_f2[LU3(i,Nm1,5)]); rhof = _f2[LU3(i,Nm2,0)] + _f2[LU3(i,Nm2,1)] + _f2[LU3(i,Nm2,2)] + _f2[LU3(i,Nm2,3)] + _f2[LU3(i,Nm2,4)] + _f2[LU3(i,Nm2,5)]+ _f2[LU3(i,Nm2,6)]+ _f2[LU3(i,Nm2,7)]+ _f2[LU3(i,Nm2,8)]; u1f = ((_f2[LU3(i,Nm2,1)] + _f2[LU3(i,Nm2,5)] + _f2[LU3(i,Nm2,8)]) - (_f2[LU3(i,Nm2,3)] + _f2[LU3(i,Nm2,6)] + _f2[LU3(i,Nm2,7)])) / rhof; u2f = ((_f2[LU3(i,Nm2,2)] + _f2[LU3(i,Nm2,5)] + _f2[LU3(i,Nm2,6)]) - (_f2[LU3(i,Nm2,4)] + _f2[LU3(i,Nm2,7)] + _f2[LU3(i,Nm2,8)])) / rhof; for (unsigned int k = 0; k < Q; k++) _f2[LU3(i,Nm1,k)] = calcfeq(k,Utop,0.0,rhowall,1) + (_f2[LU3(i,Nm2,k)] - calcfeq(k, u1f, u2f, rhof,1)); // Left wall, (0,i) rhowall = _f2[LU3(0,i,0)] +_f2[LU3(0,i,2)] +_f2[LU3(0,i,4)] + 2.0 * (_f2[LU3(0,i,3)] +_f2[LU3(0,i,6)] +_f2[LU3(0,i,7)]); rhof = _f2[LU3(1,i,0)] + _f2[LU3(1,i,1)] + _f2[LU3(1,i,2)] + _f2[LU3(1,i,3)] + _f2[LU3(1,i,4)] + _f2[LU3(1,i,5)]+ _f2[LU3(1,i,6)]+ _f2[LU3(1,i,7)]+ _f2[LU3(1,i,8)]; u1f = ((_f2[LU3(1,i,1)] + _f2[LU3(1,i,5)] + _f2[LU3(1,i,8)]) - (_f2[LU3(1,i,3)] + _f2[LU3(1,i,6)] + _f2[LU3(1,i,7)])) / rhof; u2f = ((_f2[LU3(1,i,2)] + _f2[LU3(1,i,5)] + _f2[LU3(1,i,6)]) - (_f2[LU3(1,i,4)] + _f2[LU3(1,i,7)] + _f2[LU3(1,i,8)])) / rhof; for (unsigned int k = 0; k < Q; k++) _f2[LU3(0,i,k)] = calcfeq(k,0.0,Vlef,rhowall,1) + (_f2[LU3(1,i,k)] - calcfeq(k, u1f, u2f, rhof,1)); // Right Wall (Nm1, i) rhowall = _f2[LU3(Nm1,i,0)] +_f2[LU3(Nm1,i,2)] +_f2[LU3(Nm1,i,4)] + 2.0 * (_f2[LU3(Nm1,i,1)] +_f2[LU3(Nm1,i,5)] +_f2[LU3(Nm1,i,8)]); rhof = _f2[LU3(Nm2,i,0)] + _f2[LU3(Nm2,i,1)] + _f2[LU3(Nm2,i,2)] + _f2[LU3(Nm2,i,3)] + _f2[LU3(Nm2,i,4)] + _f2[LU3(Nm2,i,5)]+ _f2[LU3(Nm2,i,6)]+ _f2[LU3(Nm2,i,7)]+ _f2[LU3(Nm2,i,8)]; u1f = ((_f2[LU3(Nm2,i,1)] + _f2[LU3(Nm2,i,5)] + _f2[LU3(Nm2,i,8)]) - (_f2[LU3(Nm2,i,3)] + _f2[LU3(Nm2,i,6)] + _f2[LU3(Nm2,i,7)])) / rhof; u2f = ((_f2[LU3(Nm2,i,2)] + _f2[LU3(Nm2,i,5)] + _f2[LU3(Nm2,i,6)]) - (_f2[LU3(Nm2,i,4)] + _f2[LU3(Nm2,i,7)] + _f2[LU3(Nm2,i,8)])) / rhof; for (unsigned int k = 0; k < Q; k++) _f2[LU3(Nm1,i,k)] = calcfeq(k,0.0,Vrig,rhowall,1) + (_f2[LU3(Nm2,i,k)] - calcfeq(k, u1f, u2f, rhof,1)); } // Corners // Bottom left (0,0) rhof = _f2[LU3(1,1,0)] + _f2[LU3(1,1,1)] + _f2[LU3(1,1,2)] + _f2[LU3(1,1,3)] + _f2[LU3(1,1,4)] + _f2[LU3(1,1,5)]+ _f2[LU3(1,1,6)]+ _f2[LU3(1,1,7)]+ _f2[LU3(1,1,8)]; u1f = ((_f2[LU3(1,1,1)] + _f2[LU3(1,1,5)] + _f2[LU3(1,1,8)]) - (_f2[LU3(1,1,3)] + _f2[LU3(1,1,6)] + _f2[LU3(1,1,7)])) / rhof; u2f = ((_f2[LU3(1,1,2)] + _f2[LU3(1,1,5)] + _f2[LU3(1,1,6)]) - (_f2[LU3(1,1,4)] + _f2[LU3(1,1,7)] + _f2[LU3(1,1,8)])) / rhof; rhowall = 1.0; #pragma omp for for (unsigned int k = 0; k < Q; k++) _f2[LU3(0,0,k)] = calcfeq(k,Ubot,Vlef,rhowall,1) + (_f2[LU3(1,1,k)] - calcfeq(k, u1f, u2f, rhof,1)); // Bottom Right (Nm1,0) rhof = _f2[LU3(Nm2,1,0)] + _f2[LU3(Nm2,1,1)] + _f2[LU3(Nm2,1,2)] + _f2[LU3(Nm2,1,3)] + _f2[LU3(Nm2,1,4)] + _f2[LU3(Nm2,1,5)]+ _f2[LU3(Nm2,1,6)]+ _f2[LU3(Nm2,1,7)]+ _f2[LU3(Nm2,1,8)]; u1f = ((_f2[LU3(Nm2,1,1)] + _f2[LU3(Nm2,1,5)] + _f2[LU3(Nm2,1,8)]) - (_f2[LU3(Nm2,1,3)] + _f2[LU3(Nm2,1,6)] + _f2[LU3(Nm2,1,7)])) / rhof; u2f = ((_f2[LU3(Nm2,1,2)] + _f2[LU3(Nm2,1,5)] + _f2[LU3(Nm2,1,6)]) - (_f2[LU3(Nm2,1,4)] + _f2[LU3(Nm2,1,7)] + _f2[LU3(Nm2,1,8)])) / rhof; #pragma omp for for (unsigned int k = 0; k < Q; k++) _f2[LU3(Nm1,0,k)] = calcfeq(k,Ubot,Vrig,rhowall,1) + (_f2[LU3(Nm2,1,k)] - calcfeq(k, u1f, u2f, rhof,1)); // Top Right (Nm1,Nm1) rhof = _f2[LU3(Nm2,Nm2,0)] + _f2[LU3(Nm2,Nm2,1)] + _f2[LU3(Nm2,Nm2,2)] + _f2[LU3(Nm2,Nm2,3)] + _f2[LU3(Nm2,Nm2,4)] + _f2[LU3(Nm2,Nm2,5)]+ _f2[LU3(Nm2,Nm2,6)]+ _f2[LU3(Nm2,Nm2,7)]+ _f2[LU3(Nm2,Nm2,8)]; u1f = ((_f2[LU3(Nm2,Nm2,1)] + _f2[LU3(Nm2,Nm2,5)] + _f2[LU3(Nm2,Nm2,8)]) - (_f2[LU3(Nm2,Nm2,3)] + _f2[LU3(Nm2,Nm2,6)] + _f2[LU3(Nm2,Nm2,7)])) / rhof; u2f = ((_f2[LU3(Nm2,Nm2,2)] + _f2[LU3(Nm2,Nm2,5)] + _f2[LU3(Nm2,Nm2,6)]) - (_f2[LU3(Nm2,Nm2,4)] + _f2[LU3(Nm2,Nm2,7)] + _f2[LU3(Nm2,Nm2,8)])) / rhof; #pragma omp for for (unsigned int k = 0; k < Q; k++) _f2[LU3(Nm1,Nm1,k)] = calcfeq(k,Utop,Vrig,rhowall,1) + (_f2[LU3(Nm2,Nm2,k)] - calcfeq(k, u1f, u2f, rhof,1)); // Top Left (0,Nm1) rhof = _f2[LU3(1,Nm2,0)] + _f2[LU3(1,Nm2,1)] + _f2[LU3(1,Nm2,2)] + _f2[LU3(1,Nm2,3)] + _f2[LU3(1,Nm2,4)] + _f2[LU3(1,Nm2,5)]+ _f2[LU3(1,Nm2,6)]+ _f2[LU3(1,Nm2,7)]+ _f2[LU3(1,Nm2,8)]; u1f = ((_f2[LU3(1,Nm2,1)] + _f2[LU3(1,Nm2,5)] + _f2[LU3(1,Nm2,8)]) - (_f2[LU3(1,Nm2,3)] + _f2[LU3(1,Nm2,6)] + _f2[LU3(1,Nm2,7)])) / rhof; u2f = ((_f2[LU3(1,Nm2,2)] + _f2[LU3(1,Nm2,5)] + _f2[LU3(1,Nm2,6)]) - (_f2[LU3(1,Nm2,4)] + _f2[LU3(1,Nm2,7)] + _f2[LU3(1,Nm2,8)])) / rhof; #pragma omp for for (unsigned int k = 0; k < Q; k++) _f2[LU3(0,Nm1,k)] = calcfeq(k,Utop,Vlef,rhowall,1) + (_f2[LU3(1,Nm2,k)] - calcfeq(k, u1f, u2f, rhof,1)); }; break; } case 1: { // Poiseuille Flow #pragma omp parallel { double rhof{},u1f{},u2f{}; double rhowall{1.0}; #pragma omp for for (unsigned int i = 1; i < N-1; i++){ // Bottom wall, (i, 0) rhowall = _f2[LU3(i,0,0)] +_f2[LU3(i,0,1)] +_f2[LU3(i,0,3)] + 2.0 * (_f2[LU3(i,0,4)] +_f2[LU3(i,0,7)] +_f2[LU3(i,0,8)]); rhof = _f2[LU3(i,1,0)] + _f2[LU3(i,1,1)] + _f2[LU3(i,1,2)] + _f2[LU3(i,1,3)] + _f2[LU3(i,1,4)] + _f2[LU3(i,1,5)]+ _f2[LU3(i,1,6)]+ _f2[LU3(i,1,7)]+ _f2[LU3(i,1,8)]; u1f = ((_f2[LU3(i,1,1)] + _f2[LU3(i,1,5)] + _f2[LU3(i,1,8)]) - (_f2[LU3(i,1,3)] + _f2[LU3(i,1,6)] + _f2[LU3(i,1,7)])) / rhof; u2f = ((_f2[LU3(i,1,2)] + _f2[LU3(i,1,5)] + _f2[LU3(i,1,6)]) - (_f2[LU3(i,1,4)] + _f2[LU3(i,1,7)] + _f2[LU3(i,1,8)])) / rhof; for (unsigned int k = 0; k < Q; k++) _f2[LU3(i,0,k)] = calcfeq(k,0.0,0.0,rhowall,1) + (_f2[LU3(i,1,k)] - calcfeq(k, u1f, u2f, rhof,1)); // Top Wall, (i,Nm1) rhowall = _f2[LU3(i,Nm1,0)] +_f2[LU3(i,Nm1,1)] +_f2[LU3(i,Nm1,3)] + 2.0 * (_f2[LU3(i,Nm1,2)] +_f2[LU3(i,Nm1,6)] +_f2[LU3(i,Nm1,5)]); rhof = _f2[LU3(i,Nm2,0)] + _f2[LU3(i,Nm2,1)] + _f2[LU3(i,Nm2,2)] + _f2[LU3(i,Nm2,3)] + _f2[LU3(i,Nm2,4)] + _f2[LU3(i,Nm2,5)]+ _f2[LU3(i,Nm2,6)]+ _f2[LU3(i,Nm2,7)]+ _f2[LU3(i,Nm2,8)]; u1f = ((_f2[LU3(i,Nm2,1)] + _f2[LU3(i,Nm2,5)] + _f2[LU3(i,Nm2,8)]) - (_f2[LU3(i,Nm2,3)] + _f2[LU3(i,Nm2,6)] + _f2[LU3(i,Nm2,7)])) / rhof; u2f = ((_f2[LU3(i,Nm2,2)] + _f2[LU3(i,Nm2,5)] + _f2[LU3(i,Nm2,6)]) - (_f2[LU3(i,Nm2,4)] + _f2[LU3(i,Nm2,7)] + _f2[LU3(i,Nm2,8)])) / rhof; for (unsigned int k = 0; k < Q; k++) _f2[LU3(i,Nm1,k)] = calcfeq(k,0.0,0.0,rhowall,1) + (_f2[LU3(i,Nm2,k)] - calcfeq(k, u1f, u2f, rhof,1)); } } break; } case 0: { // Couette Flow #pragma omp parallel { double rhof{},u1f{},u2f{}; double rhowall{1.0}; #pragma omp for for (unsigned int i = 1; i < N-1; i++){ // Bottom wall, (i, 0) rhowall = _f2[LU3(i,0,0)] +_f2[LU3(i,0,1)] +_f2[LU3(i,0,3)] + 2.0 * (_f2[LU3(i,0,4)] +_f2[LU3(i,0,7)] +_f2[LU3(i,0,8)]); rhof = _f2[LU3(i,1,0)] + _f2[LU3(i,1,1)] + _f2[LU3(i,1,2)] + _f2[LU3(i,1,3)] + _f2[LU3(i,1,4)] + _f2[LU3(i,1,5)]+ _f2[LU3(i,1,6)]+ _f2[LU3(i,1,7)]+ _f2[LU3(i,1,8)]; u1f = ((_f2[LU3(i,1,1)] + _f2[LU3(i,1,5)] + _f2[LU3(i,1,8)]) - (_f2[LU3(i,1,3)] + _f2[LU3(i,1,6)] + _f2[LU3(i,1,7)])) / rhof; u2f = ((_f2[LU3(i,1,2)] + _f2[LU3(i,1,5)] + _f2[LU3(i,1,6)]) - (_f2[LU3(i,1,4)] + _f2[LU3(i,1,7)] + _f2[LU3(i,1,8)])) / rhof; for (unsigned int k = 0; k < Q; k++) _f2[LU3(i,0,k)] = calcfeq(k,Ubot,0.0,rhowall,1) + (_f2[LU3(i,1,k)] - calcfeq(k, u1f, u2f, rhof,1)); // Top Wall, (i,Nm1) rhowall = _f2[LU3(i,Nm1,0)] +_f2[LU3(i,Nm1,1)] +_f2[LU3(i,Nm1,3)] + 2.0 * (_f2[LU3(i,Nm1,2)] +_f2[LU3(i,Nm1,6)] +_f2[LU3(i,Nm1,5)]); rhof = _f2[LU3(i,Nm2,0)] + _f2[LU3(i,Nm2,1)] + _f2[LU3(i,Nm2,2)] + _f2[LU3(i,Nm2,3)] + _f2[LU3(i,Nm2,4)] + _f2[LU3(i,Nm2,5)]+ _f2[LU3(i,Nm2,6)]+ _f2[LU3(i,Nm2,7)]+ _f2[LU3(i,Nm2,8)]; u1f = ((_f2[LU3(i,Nm2,1)] + _f2[LU3(i,Nm2,5)] + _f2[LU3(i,Nm2,8)]) - (_f2[LU3(i,Nm2,3)] + _f2[LU3(i,Nm2,6)] + _f2[LU3(i,Nm2,7)])) / rhof; u2f = ((_f2[LU3(i,Nm2,2)] + _f2[LU3(i,Nm2,5)] + _f2[LU3(i,Nm2,6)]) - (_f2[LU3(i,Nm2,4)] + _f2[LU3(i,Nm2,7)] + _f2[LU3(i,Nm2,8)])) / rhof; for (unsigned int k = 0; k < Q; k++) _f2[LU3(i,Nm1,k)] = calcfeq(k,Utop,0.0,rhowall,1) + (_f2[LU3(i,Nm2,k)] - calcfeq(k, u1f, u2f, rhof,1)); } } break; } default: { std::printf("Error: Invalid Boundary condition case number\n"); exit(1); } } }; inline void HWBB(){ double rhowall = 1.0; switch (BC){ case 2: { // Lid-driven cavity flow #pragma omp parallel for for (unsigned int i = 1; i < N-1; i++){ // Bottom wall _f2[LU3(i, 0, 6)] = _fstar[LU3(i, 0, 8)] - 2.0 * w[8] * rhowall * c[8][0] * Ubot * 3.0; _f2[LU3(i, 0, 2)] = _fstar[LU3(i, 0, 4)]; _f2[LU3(i, 0, 5)] = _fstar[LU3(i, 0, 7)] - 2.0 * w[7] * rhowall * c[7][0] * Ubot * 3.0; // Top wall _f2[LU3(i, Nm1, 8)] = _fstar[LU3(i, Nm1, 6)] - 2.0 * w[6] * rhowall * c[6][0] * Utop * 3.0; _f2[LU3(i, Nm1, 4)] = _fstar[LU3(i, Nm1, 2)]; _f2[LU3(i, Nm1, 7)] = _fstar[LU3(i, Nm1, 5)] - 2.0 * w[5] * rhowall * c[5][0] * Utop * 3.0; // Left wall _f2[LU3(0, i, 5)] = _fstar[LU3(0, i, 7)] - 2.0 * w[7] * rhowall * c[7][1] * Vlef * 3.0; _f2[LU3(0, i, 1)] = _fstar[LU3(0, i, 3)]; _f2[LU3(0, i, 8)] = _fstar[LU3(0, i, 6)] - 2.0 * w[6] * rhowall * c[6][1] * Vlef * 3.0; // Right wall _f2[LU3(Nm1, i, 7)] = _fstar[LU3(Nm1, i, 5)] - 2.0 * w[5] * rhowall * c[5][1] * Vrig * 3.0; _f2[LU3(Nm1, i, 3)] = _fstar[LU3(Nm1, i, 1)]; _f2[LU3(Nm1, i, 6)] = _fstar[LU3(Nm1, i, 8)] - 2.0 * w[8] * rhowall * c[8][1] * Vrig * 3.0; } // Corners // Top left _f2[LU3(0, Nm1, 1)] = _fstar[LU3(0, Nm1, 3)]; _f2[LU3(0, Nm1, 8)] = _fstar[LU3(0, Nm1, 6)] - 2.0 * w[6] * rhowall * (c[6][0] * Utop + c[6][1] * Vlef) * 3.0; _f2[LU3(0, Nm1, 4)] = _fstar[LU3(0, Nm1, 2)]; // Bottom Left _f2[LU3(0, 0, 1)] = _fstar[LU3(0, 0, 3)]; _f2[LU3(0, 0, 5)] = _fstar[LU3(0, 0, 7)] - 2.0 * w[7] * rhowall * (c[7][0] * Ubot + c[7][1] * Vlef) * 3.0; _f2[LU3(0, 0, 2)] = _fstar[LU3(0, 0, 4)]; // Top Right _f2[LU3(Nm1, Nm1, 3)] = _fstar[LU3(Nm1, Nm1, 1)]; _f2[LU3(Nm1, Nm1, 7)] = _fstar[LU3(Nm1, Nm1, 5)] - 2.0 * w[5] * rhowall * (c[5][0] * Utop + c[5][1] * Vrig) * 3.0; _f2[LU3(Nm1, Nm1, 4)] = _fstar[LU3(Nm1, Nm1, 2)]; // Bottom Right _f2[LU3(Nm1, 0, 3)] = _fstar[LU3(Nm1, 0, 1)]; _f2[LU3(Nm1, 0, 6)] = _fstar[LU3(Nm1, 0, 8)] - 2.0 * w[8] * rhowall * (c[8][0] * Ubot + c[8][1] * Vrig) * 3.0; _f2[LU3(Nm1, 0, 2)] = _fstar[LU3(Nm1, 0, 4)]; break; } case 1: { // Poiseuille Flow #pragma omp parallel for for (unsigned int i = 0; i < N; i++){ // Bottom wall _f2[LU3(i, 0, 6)] = _fstar[LU3(i, 0, 8)]; _f2[LU3(i, 0, 2)] = _fstar[LU3(i, 0, 4)]; _f2[LU3(i, 0, 5)] = _fstar[LU3(i, 0, 7)]; // Top wall _f2[LU3(i, Nm1, 8)] = _fstar[LU3(i, Nm1, 6)]; _f2[LU3(i, Nm1, 4)] = _fstar[LU3(i, Nm1, 2)]; _f2[LU3(i, Nm1, 7)] = _fstar[LU3(i, Nm1, 5)]; } break; } case 0: { // Couette flow #pragma omp parallel for for (unsigned int i = 0; i < N; i++){ // Bottom wall _f2[LU3(i, 0, 6)] = _fstar[LU3(i, 0, 8)] - 2.0 * w[8] * _rhobar * c[8][0] * Ubot * 3.0; _f2[LU3(i, 0, 2)] = _fstar[LU3(i, 0, 4)] - 2.0 * w[4] * _rhobar * c[4][0] * Ubot * 3.0; _f2[LU3(i, 0, 5)] = _fstar[LU3(i, 0, 7)] - 2.0 * w[7] * _rhobar * c[7][0] * Ubot * 3.0; // Top wall _f2[LU3(i, Nm1, 8)] = _fstar[LU3(i, Nm1, 6)] - 2.0 * w[6] * _rhobar * c[6][0] * Utop * 3.0; _f2[LU3(i, Nm1, 4)] = _fstar[LU3(i, Nm1, 2)] - 2.0 * w[2] * _rhobar * c[2][0] * Utop * 3.0; _f2[LU3(i, Nm1, 7)] = _fstar[LU3(i, Nm1, 5)] - 2.0 * w[5] * _rhobar * c[5][0] * Utop * 3.0; } break; } default: { std::printf("Error: Invalid Boundary condition case number\n"); exit(1); } } } inline void swap(){ _f1.swap(_f2); } inline bool convergence(const unsigned int t){ if (t == 0) _df0 = 1.0 / rmsError(); if (t % 1000 == 0) { _df = rmsError() * _df0; if (t / 1000 == _error.size()) _error.resize(2 * t / 1000); _error[t / 1000] = _df; } if (t % prntInt == 0) { cout << "\nIteration " << t << ":" << endl; printf("df/df0:\t%.3e\n", _df); stop = omp_get_wtime(); printf("Time:\t%.3e s\n", stop-start); printf("rho:\t%.3e\n", _rhobar); start = omp_get_wtime(); } return (_df < THRESH); } inline void macroVars(){ double temp; int ind1; _rhobar = 0.0; #pragma omp parallel for private(temp,ind1) collapse(2) reduction(+:_rhobar) for (unsigned int i = 0; i < N; i++){ for (unsigned int j = 0; j < N; j++){ ind1 = LU2(i,j); temp = _f2[LU3(i,j,0)] + _f2[LU3(i,j,1)] + _f2[LU3(i,j,2)] + _f2[LU3(i,j,3)] + _f2[LU3(i,j,4)] + _f2[LU3(i,j,5)] + _f2[LU3(i,j,6)] + _f2[LU3(i,j,7)] + _f2[LU3(i,j,8)]; _rho[ind1] = temp; _rhobar += (temp / N2); _u1[ind1] = ((_f2[LU3(i,j,1)] + _f2[LU3(i,j,5)] + _f2[LU3(i,j,8)]) - (_f2[LU3(i,j,3)] + _f2[LU3(i,j,6)] + _f2[LU3(i,j,7)])) / temp; _u2[ind1] = ((_f2[LU3(i,j,2)] + _f2[LU3(i,j,5)] + _f2[LU3(i,j,6)]) - (_f2[LU3(i,j,4)] + _f2[LU3(i,j,7)] + _f2[LU3(i,j,8)])) / temp; if (BC == 1) { _u1[ind1] += 0.5 * _forceX / temp; _u2[ind1] += 0.5 * _forceY / temp; } } } } inline void output(){ calcvmag(); calcstress(); calcVort(); FILE *f = fopen(_filename1,"w"); int ind1; if (f == nullptr) { printf("Error opening file!\n"); exit(1); } fprintf(f, "TITLE=\"%s\" VARIABLES=\"x\", \"y\", \"u\", \"v\", \"vmag\", \"omegaxy\", \"vortz\" ZONE T=\"%s\" I=%d J=%d F=POINT\n", _filename1, _filename1,N,N); for (unsigned int i = 0; i < N; i++) { for (unsigned int j = 0; j < N ; j++) { ind1 = LU2(i,j); fprintf(f, "%.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f\n", _x[i], _x[j], _u1[ind1] / _Umax,_u2[ind1] / _Umax, _vmag[ind1], _stress[ind1], _vort[ind1]); } } fclose(f); FILE *f2 = fopen(_filename2,"w"); if (f2 == nullptr) { printf("Error opening file!\n"); exit(1); } for (unsigned int i = 0; i < _error.size(); i++) { if (_error[i] == 0.0) break; else fprintf(f2, "%d\t%.10e\n", 1000*i,_error[i]); } fclose(f2); } private: vector<double> _f1; vector<double> _f2; vector<double> _fstar; vector<double> _u1; vector<double> _u2; vector<double> _rho; vector<double> _x; vector<double> _error; vector<double> _vmag; vector<double> _stress; vector<double> _vort; double _df, _df0, _OMEGA, _OMEGAm, _CS, _MACH, _rhobar; char _filename1[80]; char _filename2[80]; double _omega_e,_omega_eps,_omega_q,_omega_nu, _GS[9]; double _Umax = max(max(Utop,Ubot),max(Vlef,Vrig)); const double _forceX = 8.0 * NU * max(max(Utop, Ubot),max(Vlef, Vrig)) / N2, _forceY = 0.0; // Left-right periodicity inline void virtualnode(){ #pragma omp parallel for for (unsigned int j = 1; j < Nm1; j++) { _fstar[LU3(0, j, 1)] = _fstar[LU3(Nm2, j, 1)]; _fstar[LU3(0, j, 5)] = _fstar[LU3(Nm2, j, 5)]; _fstar[LU3(0, j, 8)] = _fstar[LU3(Nm2, j, 8)]; _fstar[LU3(Nm1, j, 3)] = _fstar[LU3(1, j, 3)]; _fstar[LU3(Nm1, j, 6)] = _fstar[LU3(1, j, 6)]; _fstar[LU3(Nm1, j, 7)] = _fstar[LU3(1, j, 7)]; } // Top Left _fstar[LU3(0, Nm1, 1)] = _fstar[LU3(Nm2, Nm1, 1)]; _fstar[LU3(0, Nm1, 4)] = _fstar[LU3(Nm2, Nm1, 4)]; _fstar[LU3(0, Nm1, 8)] = _fstar[LU3(Nm2, Nm1, 8)]; // Top Right _fstar[LU3(Nm1, Nm1, 3)] = _fstar[LU3(1, Nm1, 3)]; _fstar[LU3(Nm1, Nm1, 7)] = _fstar[LU3(1, Nm1, 7)]; _fstar[LU3(Nm1, Nm1, 4)] = _fstar[LU3(1, Nm1, 4)]; // Bottom Left _fstar[LU3(0, 0, 1)] = _fstar[LU3(Nm2, 0, 1)]; _fstar[LU3(0, 0, 2)] = _fstar[LU3(Nm2, 0, 2)]; _fstar[LU3(0, 0, 5)] = _fstar[LU3(Nm2, 0, 5)]; // Bottom Right _fstar[LU3(Nm1, 0, 3)] = _fstar[LU3(1, 0, 3)]; _fstar[LU3(Nm1, 0, 2)] = _fstar[LU3(1, 0, 2)]; _fstar[LU3(Nm1, 0, 6)] = _fstar[LU3(1, 0, 6)]; } // Intitializes x vector inline void linspace(vector<double> &x, const double _start, const double _end, const int _num){ for (unsigned int i = 0; i < _num; i++) x[i] = _start + i * (_end - _start) / (_num - 1.0); } inline double calcfeq(const int k, const int ind, const int check){ const double u1ij=_u1[ind], u2ij = _u2[ind]; double cdotu{},feq{},u2{},rho0=_rho[ind]; u2 = P2(u1ij) + P2(u2ij); cdotu = c[k][0] * u1ij + c[k][1] * u2ij; feq = w[k] * (_rho[ind] + rho0 * (3.0 * cdotu + (4.5 * P2(cdotu) - 1.5 * u2))); if (check == 1) checkfeq(feq); return feq; } inline double calcfeq(const int k, const double u1ij, const double u2ij, const double rhoij, const int check){ double cdotu{},feq{},u2{}, rho0=rhoij; u2 = P2(u1ij) + P2(u2ij); cdotu = c[k][0] * u1ij + c[k][1] * u2ij; feq = w[k] * (rhoij + rho0 * (3.0 * cdotu + (4.5 * P2(cdotu) - 1.5 * u2))); if (check == 1) checkfeq(feq); return feq; } // Checks for negative feq inline void checkfeq(const double value){ if (value < 0) { printf("Error: negative feq. Therefore, unstable.\n"); exit(1); } } inline double rmsError(){ double difference{}; #pragma omp parallel for reduction(+:difference) for (unsigned int i = 0; i < NQ; i++){ difference += P2(_f2[i] - _f1[i]); } return sqrt(difference / NQ); } inline void calcmeq(vector<double> &meq, const double u1, const double u2, const double rho) { const double u12 = P2(u1); const double u22 = P2(u2); const double rho0 = rho; meq[0] = rho; // rho meq[1] = -2 * rho + 3 * rho0 * (u12 + u22); // e meq[2] = rho - 3 * rho0 * (u12 + u22); // eps meq[3] = rho0 * u1; // jx meq[4] = -meq[3]; // qx meq[5] = rho0 * u2; // jy meq[6] = -meq[5]; // qy meq[7] = rho0 * (u12 - u22); // pxx meq[8] = rho0 * u1 * u2; // pxy } inline int LU2(const int i, const int j) { return N*j + i; } inline int LU3(const int i, const int j, const int k) { return N2*k + N*j + i; } inline double P2(const double value){ return (value * value); } inline void calcvmag(){ #pragma omp parallel for for (unsigned int i = 0; i < N2; i++) _vmag[i] = sqrt(P2(_u1[i]) + P2(_u2[i])); } inline void calcstress(){ #pragma omp parallel { int ind1; #pragma omp for collapse(2) for (unsigned int i = 0; i < N; i++){ for (unsigned int j = 0; j < N; j++){ ind1 = LU2(i,j); for (unsigned int k = 0; k < Q; k++){ _stress[ind1] -= (1.0 - 0.5 * _OMEGA) * c[k][0] * c[k][1] * (_f2[LU3(i,j,k)] - calcfeq(k,ind1,1)); } if (BC == 1) _stress[ind1] -= 0.5 * (1.0 - 0.5 * _OMEGA) * (_forceX * _u2[ind1] + _forceY * _u1[ind1]); } } } } inline void calcVort(){ double dvdx{},dudy{}; const double h2 = P2(_x[1] - _x[0]); int ind1; #pragma omp parallel for private(ind1,dvdx,dudy), collapse(2) // Internal region for (unsigned int i = 1; i < Nm1; i++) { for (unsigned int j = 1; j < Nm1; j++) { ind1 = LU2(i,j); dvdx = (_u2[LU2(i-1,j)] - 2.0 * _u2[ind1] + _u2[LU2(i+1,j)]) / (h2 * _Umax); dudy = (_u1[LU2(i,j-1)] - 2.0 * _u1[ind1] + _u1[LU2(i,j+1)]) / (h2 * _Umax); _vort[ind1] = dvdx - dudy; } } #pragma omp parallel for private(dvdx,dudy) // boundary for (unsigned int i = 1; i < N-1; i++) { // Top dvdx = (_u2[LU2(i-1,Nm1)] - 2.0 * _u2[LU2(i-1,Nm1)] + _u2[LU2(i+1,Nm1)]) / (h2 * _Umax); dudy = (_u1[LU2(i,Nm1)] - 2.0 * _u1[LU2(i,Nm2)] + _u1[LU2(i,N - 3)]) / (h2 * _Umax); _vort[LU2(i,Nm1)] = dvdx - dudy; // Bottom dvdx = (_u2[LU2(i-1,0)] - 2.0 * _u2[LU2(i-1,0)] + _u2[LU2(i+1,0)]) / (h2 * _Umax); dudy = (_u1[LU2(i,2)] - 2.0 * _u1[LU2(i,1)] + _u1[LU2(i,0)]) / (h2 * _Umax); _vort[LU2(i,0)] = dvdx - dudy; // Left dvdx = (_u2[LU2(2,i)] - 2.0 * _u2[LU2(1,i)] + _u2[LU2(0,i)]) / (h2 * _Umax); dudy = (_u1[LU2(0,i+1)] - 2.0 * _u1[LU2(0,i)] + _u1[LU2(0,i-1)]) / (h2 * _Umax); _vort[LU2(0,i)] = dvdx - dudy; // Right dvdx = (_u2[LU2(Nm1,i)] - 2.0 * _u2[LU2(Nm2,i)] + _u2[LU2(N - 3,i)]) / (h2 * _Umax); dudy = (_u1[LU2(Nm1,i+1)] - 2.0 * _u1[LU2(Nm1,i)] + _u1[LU2(Nm1,i-1)]) / (h2 * _Umax); _vort[LU2(0,i)] = dvdx - dudy; } // Corners // Bottom Left dvdx = (_u2[LU2(2,0)] - 2.0 * _u2[LU2(1,0)] + _u2[LU2(0,0)]) / (h2 * _Umax); dudy = (_u1[LU2(0,2)] - 2.0 * _u1[LU2(0,1)] + _u1[LU2(0,0)]) / (h2 * _Umax); _vort[LU2(0,0)] = dvdx - dudy; // Bottom Right dvdx = (_u2[LU2(Nm1,0)] - 2.0 * _u2[LU2(Nm2,0)] + _u2[LU2(N - 3,0)]) / (h2 * _Umax); dudy = (_u1[LU2(Nm1,2)] - 2.0 * _u1[LU2(Nm1,1)] + _u1[LU2(Nm1,0)]) / (h2 * _Umax); _vort[LU2(Nm1,0)] = dvdx - dudy; // Top Left dvdx = (_u2[LU2(2,Nm1)] - 2.0 * _u2[LU2(1,Nm1)] + _u2[LU2(0,Nm1)]) / (h2 * _Umax); dudy = (_u1[LU2(0,Nm1)] - 2.0 * _u1[LU2(0,Nm2)] + _u1[LU2(0,N - 3)]) / (h2 * _Umax); _vort[LU2(0,Nm1)] = dvdx - dudy; // Top Right dvdx = (_u2[LU2(Nm1,Nm1)] - 2.0 * _u2[LU2(Nm2,Nm1)] + _u2[LU2(N - 3,Nm1)]) / (h2 * _Umax); dudy = (_u1[LU2(Nm1,Nm1)] - 2.0 * _u1[LU2(Nm1,Nm2)] + _u1[LU2(Nm1,N - 3)]) / (h2 * _Umax); _vort[LU2(Nm1,Nm1)] = dvdx - dudy; } }; #endif //LIDDRIVENCAVITYLBM_LBMCLASS_H
omp.c
// RUN: mlir-clang %s --function=* -fopenmp -S | FileCheck %s void square(double* x, int sstart, int send, int sinc) { #pragma omp parallel for for(int i=sstart; i < send; i+= sinc) { x[i] = i; } } // CHECK: func @square(%arg0: memref<?xf64>, %arg1: i32, %arg2: i32, %arg3: i32) attributes {llvm.linkage = #llvm.linkage<external>} { // CHECK-NEXT: %c-1_i32 = arith.constant -1 : i32 // CHECK-NEXT: %0 = arith.index_cast %arg1 : i32 to index // CHECK-NEXT: %1 = arith.subi %arg2, %arg1 : i32 // CHECK-NEXT: %2 = arith.addi %1, %c-1_i32 : i32 // CHECK-NEXT: %3 = arith.addi %2, %arg3 : i32 // CHECK-NEXT: %4 = arith.divui %3, %arg3 : i32 // CHECK-NEXT: %5 = arith.muli %4, %arg3 : i32 // CHECK-NEXT: %6 = arith.addi %arg1, %5 : i32 // CHECK-NEXT: %7 = arith.index_cast %6 : i32 to index // CHECK-NEXT: %8 = arith.index_cast %arg3 : i32 to index // CHECK-NEXT: scf.parallel (%arg4) = (%0) to (%7) step (%8) { // CHECK-NEXT: %9 = arith.index_cast %arg4 : index to i32 // CHECK-NEXT: %10 = arith.sitofp %9 : i32 to f64 // CHECK-NEXT: memref.store %10, %arg0[%arg4] : memref<?xf64> // CHECK-NEXT: scf.yield // CHECK-NEXT: } // CHECK-NEXT: return // CHECK-NEXT: }
pragma09.c
/* Test a mix of OpenMP pragma with comments and label. In OpenMP pragma must be between the label and the loop, if any. */ void pragma09() { int i; // Comment #pragma omp parallel for for(i = 0; i < 10; i++) { int j = i + 1; } // Comment before #pragma omp parallel for // After for(i = 0; i < 10; i++) { int j = i + 1; } label1: # \ pragma omp parallel for for(i = 0; i < 10; i++) { int j = i + 1; } label2: /* Some comment */ # \ pragma omp parallel for // And other for(i = 0; i < 10; i++) { int j = i + 1; } // Before label3: /* Some comment */ # pragma omp \ parallel\ for // And after for(i = 0; i < 10; i++) { int j = i + 1; } //Before far_away: //After ; // The end }
SampleMotifFinder.h
#ifndef __SAMPLE_MOTIF_FINDER_H__ #define __SAMPLE_MOTIF_FINDER_H__ #include <algorithm> #include "MotifFinder.h" class SampleMotifFinder : public MotifFinder { public: SampleMotifFinder(TraversalPlan* plan, Graph* rel, size_t thread_num) : MotifFinder(plan, rel, thread_num) {} ~SampleMotifFinder() {} virtual void Execute() { AllConnType intersect_levels; AllCondType conditions; plan_->GetOrderedConnectivity(intersect_levels); plan_->GetOrderedOrdering(conditions); edge_cross_times_ = new size_t[graph_->GetEdgeCount()]; memset(edge_cross_times_, 0, sizeof(size_t) * graph_->GetEdgeCount()); locks_ = new SpinLock[graph_->GetEdgeCount()]; for (size_t i = 0; i < graph_->GetEdgeCount(); ++i) { locks_[i].Init(); } size_t pattern_vertex_count = plan_->GetVertexCount(); auto path = new uintV*[thread_num_]; auto permutate_orders = new uintV*[thread_num_]; bool*** pred = new bool**[thread_num_]; for (size_t thread_id = 0; thread_id < thread_num_; ++thread_id) { path[thread_id] = new uintV[pattern_vertex_count]; permutate_orders[thread_id] = new uintV[pattern_vertex_count]; pred[thread_id] = new bool*[pattern_vertex_count]; for (size_t i = 0; i < pattern_vertex_count; ++i) { pred[thread_id][i] = new bool[pattern_vertex_count]; } } long long* thread_cross_times = new long long[thread_num_]; memset(thread_cross_times, 0, sizeof(long long) * thread_num_); long long* thread_pass_vertices_num = new long long[thread_num_]; memset(thread_pass_vertices_num, 0, sizeof(long long) * thread_num_); TimeMeasurer timer; timer.StartTimer(); #if defined(OPENMP) omp_set_num_threads(thread_num_); size_t levels_num = pattern_vertex_count; auto row_ptrs = graph_->GetRowPtrs(); auto cols = graph_->GetCols(); #pragma omp parallel for schedule(dynamic) for (uintV u = 0; u < graph_->GetVertexCount(); ++u) { for (size_t t = 0; t < kRandomWalkSampleNum; ++t) { // start from each vertex, sample kRandomWalkSampleNum times size_t thread_id = omp_get_thread_num(); auto v = u; size_t pos = 0; while (1) { thread_pass_vertices_num[thread_id]++; path[thread_id][pos % levels_num] = v; pos++; if (pos >= levels_num) { // validate whether to form a motif for (size_t i = 0; i < levels_num; ++i) permutate_orders[thread_id][i] = i; for (size_t i = 0; i < levels_num; ++i) { for (size_t j = i + 1; j < levels_num; ++j) { auto v1 = path[thread_id][i]; auto v2 = path[thread_id][j]; auto posj = std::lower_bound(cols + row_ptrs[v1], cols + row_ptrs[v1 + 1], v2) - cols; if (posj < row_ptrs[v1 + 1] && cols[posj] == v2) { pred[thread_id][i][j] = pred[thread_id][j][i] = true; } else { pred[thread_id][i][j] = pred[thread_id][j][i] = false; } } } do { if (MatchPattern(path[thread_id], permutate_orders[thread_id], pred[thread_id], intersect_levels, conditions, levels_num)) { UpdateCrossEdgeTimes(path[thread_id], permutate_orders[thread_id]); thread_cross_times[thread_id]++; } } while (std::next_permutation( permutate_orders[thread_id], permutate_orders[thread_id] + levels_num)); } int rn = rand(); double x = rn * 1.0 / RAND_MAX; if (x < ALPHA) break; // randomly choose a neighbor if (row_ptrs[v + 1] - row_ptrs[v] == 0) { v = u; continue; } size_t nindex = rn % (row_ptrs[v + 1] - row_ptrs[v]); auto nv = cols[row_ptrs[v] + nindex]; v = nv; } } } #endif long long total_cross_times = 0; long long total_pass_vertices_times = 0; for (size_t thread_id = 0; thread_id < thread_num_; ++thread_id) { total_cross_times += thread_cross_times[thread_id]; total_pass_vertices_times += thread_pass_vertices_num[thread_id]; } timer.EndTimer(); std::cout << "elapsed_time=" << timer.GetElapsedMicroSeconds() / 1000.0 << "ms, total_cross_motif_times=" << total_cross_times << ",total_pass_vertices_times=" << total_pass_vertices_times << std::endl; for (size_t thread_id = 0; thread_id < thread_num_; ++thread_id) { delete[] path[thread_id]; path[thread_id] = NULL; delete[] permutate_orders[thread_id]; permutate_orders[thread_id] = NULL; } delete[] path; path = NULL; } void UpdateCrossEdgeTimes(uintV* path, uintV* permutate_orders) { size_t pattern_vertex_count = plan_->GetVertexCount(); auto row_ptrs = graph_->GetRowPtrs(); auto cols = graph_->GetCols(); auto& connectivity = plan_->GetConnectivity(); for (size_t l = 0; l < pattern_vertex_count; ++l) { for (size_t pred_id = 0; pred_id < connectivity[l].size(); ++pred_id) { size_t l2 = connectivity[l][pred_id]; auto u = path[permutate_orders[l]]; auto v = path[permutate_orders[l2]]; auto pv = std::lower_bound(cols + row_ptrs[u], cols + row_ptrs[u + 1], v) - cols; assert(pv < row_ptrs[u + 1] && cols[pv] == v); locks_[pv].Lock(); edge_cross_times_[pv]++; locks_[pv].Unlock(); } } } static bool MatchPattern(uintV* path, uintV* permutate_orders, bool** pred, AllConnType& intersect_levels, AllCondType& conditions, size_t levels_num) { for (size_t l = 0; l < levels_num; ++l) { for (size_t j = 0; j < intersect_levels[l].size(); ++j) { size_t nl = intersect_levels[l][j]; if (pred[permutate_orders[l]][permutate_orders[nl]] == false) return false; } auto u = path[permutate_orders[l]]; for (size_t j = 0; j < conditions[l].size(); ++j) { size_t nl = conditions[l][j].second; auto v = path[permutate_orders[nl]]; size_t condtype = conditions[l][j].first; if (condtype == LESS_THAN) { if (!(u < v)) return false; } else if (condtype == LARGER_THAN) { if (!(u > v)) return false; } } for (size_t nl = 0; nl < l; ++nl) { auto v = path[permutate_orders[nl]]; if (u == v) return false; } } return true; } }; #endif
GB_binop__gt_uint32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__gt_uint32) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__gt_uint32) // A.*B function (eWiseMult): GB (_AemultB_03__gt_uint32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__gt_uint32) // A*D function (colscale): GB (_AxD__gt_uint32) // D*A function (rowscale): GB (_DxB__gt_uint32) // C+=B function (dense accum): GB (_Cdense_accumB__gt_uint32) // C+=b function (dense accum): GB (_Cdense_accumb__gt_uint32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__gt_uint32) // C=scalar+B GB (_bind1st__gt_uint32) // C=scalar+B' GB (_bind1st_tran__gt_uint32) // C=A+scalar GB (_bind2nd__gt_uint32) // C=A'+scalar GB (_bind2nd_tran__gt_uint32) // C type: bool // A type: uint32_t // B,b type: uint32_t // BinaryOp: cij = (aij > bij) #define GB_ATYPE \ uint32_t #define GB_BTYPE \ uint32_t #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint32_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = (x > y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_GT || GxB_NO_UINT32 || GxB_NO_GT_UINT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__gt_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__gt_uint32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__gt_uint32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type uint32_t uint32_t bwork = (*((uint32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__gt_uint32) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__gt_uint32) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__gt_uint32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__gt_uint32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__gt_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__gt_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__gt_uint32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__gt_uint32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; uint32_t x = (*((uint32_t *) x_input)) ; uint32_t *Bx = (uint32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; uint32_t bij = Bx [p] ; Cx [p] = (x > bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__gt_uint32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; uint32_t *Ax = (uint32_t *) Ax_input ; uint32_t y = (*((uint32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint32_t aij = Ax [p] ; Cx [p] = (aij > y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = Ax [pA] ; \ Cx [pC] = (x > aij) ; \ } GrB_Info GB (_bind1st_tran__gt_uint32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t x = (*((const uint32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = Ax [pA] ; \ Cx [pC] = (aij > y) ; \ } GrB_Info GB (_bind2nd_tran__gt_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t y = (*((const uint32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
bitshuffle_core.c
/* * Bitshuffle - Filter for improving compression of typed binary data. * * Author: Kiyoshi Masui <kiyo@physics.ubc.ca> * Website: http://www.github.com/kiyo-masui/bitshuffle * Created: 2014 * * See LICENSE file for details about copyright and rights to use. * */ #include "bitshuffle_core.h" #include "bitshuffle_internals.h" #include <stdio.h> #include <string.h> #if defined(__AVX2__) && defined (__SSE2__) #define USEAVX2 #endif #if defined(__SSE2__) || defined(NO_WARN_X86_INTRINSICS) #define USESSE2 #endif #if defined(__ARM_NEON__) || (__ARM_NEON) #ifdef __aarch64__ #define USEARMNEON #endif #endif // Conditional includes for SSE2 and AVX2. #ifdef USEAVX2 #include <immintrin.h> #elif defined USESSE2 #include <emmintrin.h> #elif defined USEARMNEON #include <arm_neon.h> #endif #if defined(_OPENMP) && defined(_MSC_VER) typedef int64_t omp_size_t; #else typedef size_t omp_size_t; #endif // Macros. #define CHECK_MULT_EIGHT(n) if (n % 8) return -80; #define MAX(X,Y) ((X) > (Y) ? (X) : (Y)) /* ---- Functions indicating compile time instruction set. ---- */ int bshuf_using_NEON(void) { #ifdef USEARMNEON return 1; #else return 0; #endif } int bshuf_using_SSE2(void) { #ifdef USESSE2 return 1; #else return 0; #endif } int bshuf_using_AVX2(void) { #ifdef USEAVX2 return 1; #else return 0; #endif } /* ---- Worker code not requiring special instruction sets. ---- * * The following code does not use any x86 specific vectorized instructions * and should compile on any machine * */ /* Transpose 8x8 bit array packed into a single quadword *x*. * *t* is workspace. */ #define TRANS_BIT_8X8(x, t) { \ t = (x ^ (x >> 7)) & 0x00AA00AA00AA00AALL; \ x = x ^ t ^ (t << 7); \ t = (x ^ (x >> 14)) & 0x0000CCCC0000CCCCLL; \ x = x ^ t ^ (t << 14); \ t = (x ^ (x >> 28)) & 0x00000000F0F0F0F0LL; \ x = x ^ t ^ (t << 28); \ } /* Transpose 8x8 bit array along the diagonal from upper right to lower left */ #define TRANS_BIT_8X8_BE(x, t) { \ t = (x ^ (x >> 9)) & 0x0055005500550055LL; \ x = x ^ t ^ (t << 9); \ t = (x ^ (x >> 18)) & 0x0000333300003333LL; \ x = x ^ t ^ (t << 18); \ t = (x ^ (x >> 36)) & 0x000000000F0F0F0FLL; \ x = x ^ t ^ (t << 36); \ } /* Transpose of an array of arbitrarily typed elements. */ #define TRANS_ELEM_TYPE(in, out, lda, ldb, type_t) { \ size_t ii, jj, kk; \ const type_t* in_type = (const type_t*) in; \ type_t* out_type = (type_t*) out; \ for(ii = 0; ii + 7 < lda; ii += 8) { \ for(jj = 0; jj < ldb; jj++) { \ for(kk = 0; kk < 8; kk++) { \ out_type[jj*lda + ii + kk] = \ in_type[ii*ldb + kk * ldb + jj]; \ } \ } \ } \ for(ii = lda - lda % 8; ii < lda; ii ++) { \ for(jj = 0; jj < ldb; jj++) { \ out_type[jj*lda + ii] = in_type[ii*ldb + jj]; \ } \ } \ } /* Memory copy with bshuf call signature. For testing and profiling. */ int64_t bshuf_copy(const void* in, void* out, const size_t size, const size_t elem_size) { const char* in_b = (const char*) in; char* out_b = (char*) out; memcpy(out_b, in_b, size * elem_size); return size * elem_size; } /* Transpose bytes within elements, starting partway through input. */ int64_t bshuf_trans_byte_elem_remainder(const void* in, void* out, const size_t size, const size_t elem_size, const size_t start) { size_t ii, jj, kk; const char* in_b = (const char*) in; char* out_b = (char*) out; CHECK_MULT_EIGHT(start); if (size > start) { // ii loop separated into 2 loops so the compiler can unroll // the inner one. for (ii = start; ii + 7 < size; ii += 8) { for (jj = 0; jj < elem_size; jj++) { for (kk = 0; kk < 8; kk++) { out_b[jj * size + ii + kk] = in_b[ii * elem_size + kk * elem_size + jj]; } } } for (ii = size - size % 8; ii < size; ii ++) { for (jj = 0; jj < elem_size; jj++) { out_b[jj * size + ii] = in_b[ii * elem_size + jj]; } } } return size * elem_size; } /* Transpose bytes within elements. */ int64_t bshuf_trans_byte_elem_scal(const void* in, void* out, const size_t size, const size_t elem_size) { return bshuf_trans_byte_elem_remainder(in, out, size, elem_size, 0); } /* Transpose bits within bytes. */ int64_t bshuf_trans_bit_byte_remainder(const void* in, void* out, const size_t size, const size_t elem_size, const size_t start_byte) { const uint64_t* in_b = (const uint64_t*) in; uint8_t* out_b = (uint8_t*) out; uint64_t x, t; size_t ii, kk; size_t nbyte = elem_size * size; size_t nbyte_bitrow = nbyte / 8; uint64_t e=1; const int little_endian = *(uint8_t *) &e == 1; const size_t bit_row_skip = little_endian ? nbyte_bitrow : -nbyte_bitrow; const int64_t bit_row_offset = little_endian ? 0 : 7 * nbyte_bitrow; CHECK_MULT_EIGHT(nbyte); CHECK_MULT_EIGHT(start_byte); for (ii = start_byte / 8; ii < nbyte_bitrow; ii ++) { x = in_b[ii]; if (little_endian) { TRANS_BIT_8X8(x, t); } else { TRANS_BIT_8X8_BE(x, t); } for (kk = 0; kk < 8; kk ++) { out_b[bit_row_offset + kk * bit_row_skip + ii] = x; x = x >> 8; } } return size * elem_size; } /* Transpose bits within bytes. */ int64_t bshuf_trans_bit_byte_scal(const void* in, void* out, const size_t size, const size_t elem_size) { return bshuf_trans_bit_byte_remainder(in, out, size, elem_size, 0); } /* General transpose of an array, optimized for large element sizes. */ int64_t bshuf_trans_elem(const void* in, void* out, const size_t lda, const size_t ldb, const size_t elem_size) { size_t ii, jj; const char* in_b = (const char*) in; char* out_b = (char*) out; for(ii = 0; ii < lda; ii++) { for(jj = 0; jj < ldb; jj++) { memcpy(&out_b[(jj*lda + ii) * elem_size], &in_b[(ii*ldb + jj) * elem_size], elem_size); } } return lda * ldb * elem_size; } /* Transpose rows of shuffled bits (size / 8 bytes) within groups of 8. */ int64_t bshuf_trans_bitrow_eight(const void* in, void* out, const size_t size, const size_t elem_size) { size_t nbyte_bitrow = size / 8; CHECK_MULT_EIGHT(size); return bshuf_trans_elem(in, out, 8, elem_size, nbyte_bitrow); } /* Transpose bits within elements. */ int64_t bshuf_trans_bit_elem_scal(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; void *tmp_buf; CHECK_MULT_EIGHT(size); tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; count = bshuf_trans_byte_elem_scal(in, out, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_trans_bit_byte_scal(out, tmp_buf, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_trans_bitrow_eight(tmp_buf, out, size, elem_size); free(tmp_buf); return count; } /* For data organized into a row for each bit (8 * elem_size rows), transpose * the bytes. */ int64_t bshuf_trans_byte_bitrow_scal(const void* in, void* out, const size_t size, const size_t elem_size) { size_t ii, jj, kk, nbyte_row; const char *in_b; char *out_b; in_b = (const char*) in; out_b = (char*) out; nbyte_row = size / 8; CHECK_MULT_EIGHT(size); for (jj = 0; jj < elem_size; jj++) { for (ii = 0; ii < nbyte_row; ii++) { for (kk = 0; kk < 8; kk++) { out_b[ii * 8 * elem_size + jj * 8 + kk] = \ in_b[(jj * 8 + kk) * nbyte_row + ii]; } } } return size * elem_size; } /* Shuffle bits within the bytes of eight element blocks. */ int64_t bshuf_shuffle_bit_eightelem_scal(const void* in, void* out, \ const size_t size, const size_t elem_size) { const char *in_b; char *out_b; uint64_t x, t; size_t ii, jj, kk; size_t nbyte, out_index; uint64_t e=1; const int little_endian = *(uint8_t *) &e == 1; const size_t elem_skip = little_endian ? elem_size : -elem_size; const uint64_t elem_offset = little_endian ? 0 : 7 * elem_size; CHECK_MULT_EIGHT(size); in_b = (const char*) in; out_b = (char*) out; nbyte = elem_size * size; for (jj = 0; jj < 8 * elem_size; jj += 8) { for (ii = 0; ii + 8 * elem_size - 1 < nbyte; ii += 8 * elem_size) { x = *((uint64_t*) &in_b[ii + jj]); if (little_endian) { TRANS_BIT_8X8(x, t); } else { TRANS_BIT_8X8_BE(x, t); } for (kk = 0; kk < 8; kk++) { out_index = ii + jj / 8 + elem_offset + kk * elem_skip; *((uint8_t*) &out_b[out_index]) = x; x = x >> 8; } } } return size * elem_size; } /* Untranspose bits within elements. */ int64_t bshuf_untrans_bit_elem_scal(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; void *tmp_buf; CHECK_MULT_EIGHT(size); tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; count = bshuf_trans_byte_bitrow_scal(in, tmp_buf, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_shuffle_bit_eightelem_scal(tmp_buf, out, size, elem_size); free(tmp_buf); return count; } /* ---- Worker code that uses Arm NEON ---- * * The following code makes use of the Arm NEON instruction set. * NEON technology is the implementation of the ARM Advanced Single * Instruction Multiple Data (SIMD) extension. * The NEON unit is the component of the processor that executes SIMD instructions. * It is also called the NEON Media Processing Engine (MPE). * */ #ifdef USEARMNEON /* Transpose bytes within elements for 16 bit elements. */ int64_t bshuf_trans_byte_elem_NEON_16(const void* in, void* out, const size_t size) { size_t ii; const char *in_b = (const char*) in; char *out_b = (char*) out; int8x16_t a0, b0, a1, b1; for (ii=0; ii + 15 < size; ii += 16) { a0 = vld1q_s8(in_b + 2*ii + 0*16); b0 = vld1q_s8(in_b + 2*ii + 1*16); a1 = vzip1q_s8(a0, b0); b1 = vzip2q_s8(a0, b0); a0 = vzip1q_s8(a1, b1); b0 = vzip2q_s8(a1, b1); a1 = vzip1q_s8(a0, b0); b1 = vzip2q_s8(a0, b0); a0 = vzip1q_s8(a1, b1); b0 = vzip2q_s8(a1, b1); vst1q_s8(out_b + 0*size + ii, a0); vst1q_s8(out_b + 1*size + ii, b0); } return bshuf_trans_byte_elem_remainder(in, out, size, 2, size - size % 16); } /* Transpose bytes within elements for 32 bit elements. */ int64_t bshuf_trans_byte_elem_NEON_32(const void* in, void* out, const size_t size) { size_t ii; const char *in_b; char *out_b; in_b = (const char*) in; out_b = (char*) out; int8x16_t a0, b0, c0, d0, a1, b1, c1, d1; int64x2_t a2, b2, c2, d2; for (ii=0; ii + 15 < size; ii += 16) { a0 = vld1q_s8(in_b + 4*ii + 0*16); b0 = vld1q_s8(in_b + 4*ii + 1*16); c0 = vld1q_s8(in_b + 4*ii + 2*16); d0 = vld1q_s8(in_b + 4*ii + 3*16); a1 = vzip1q_s8(a0, b0); b1 = vzip2q_s8(a0, b0); c1 = vzip1q_s8(c0, d0); d1 = vzip2q_s8(c0, d0); a0 = vzip1q_s8(a1, b1); b0 = vzip2q_s8(a1, b1); c0 = vzip1q_s8(c1, d1); d0 = vzip2q_s8(c1, d1); a1 = vzip1q_s8(a0, b0); b1 = vzip2q_s8(a0, b0); c1 = vzip1q_s8(c0, d0); d1 = vzip2q_s8(c0, d0); a2 = vzip1q_s64(vreinterpretq_s64_s8(a1), vreinterpretq_s64_s8(c1)); b2 = vzip2q_s64(vreinterpretq_s64_s8(a1), vreinterpretq_s64_s8(c1)); c2 = vzip1q_s64(vreinterpretq_s64_s8(b1), vreinterpretq_s64_s8(d1)); d2 = vzip2q_s64(vreinterpretq_s64_s8(b1), vreinterpretq_s64_s8(d1)); vst1q_s64((int64_t *) (out_b + 0*size + ii), a2); vst1q_s64((int64_t *) (out_b + 1*size + ii), b2); vst1q_s64((int64_t *) (out_b + 2*size + ii), c2); vst1q_s64((int64_t *) (out_b + 3*size + ii), d2); } return bshuf_trans_byte_elem_remainder(in, out, size, 4, size - size % 16); } /* Transpose bytes within elements for 64 bit elements. */ int64_t bshuf_trans_byte_elem_NEON_64(const void* in, void* out, const size_t size) { size_t ii; const char* in_b = (const char*) in; char* out_b = (char*) out; int8x16_t a0, b0, c0, d0, e0, f0, g0, h0; int8x16_t a1, b1, c1, d1, e1, f1, g1, h1; for (ii=0; ii + 15 < size; ii += 16) { a0 = vld1q_s8(in_b + 8*ii + 0*16); b0 = vld1q_s8(in_b + 8*ii + 1*16); c0 = vld1q_s8(in_b + 8*ii + 2*16); d0 = vld1q_s8(in_b + 8*ii + 3*16); e0 = vld1q_s8(in_b + 8*ii + 4*16); f0 = vld1q_s8(in_b + 8*ii + 5*16); g0 = vld1q_s8(in_b + 8*ii + 6*16); h0 = vld1q_s8(in_b + 8*ii + 7*16); a1 = vzip1q_s8 (a0, b0); b1 = vzip2q_s8 (a0, b0); c1 = vzip1q_s8 (c0, d0); d1 = vzip2q_s8 (c0, d0); e1 = vzip1q_s8 (e0, f0); f1 = vzip2q_s8 (e0, f0); g1 = vzip1q_s8 (g0, h0); h1 = vzip2q_s8 (g0, h0); a0 = vzip1q_s8 (a1, b1); b0 = vzip2q_s8 (a1, b1); c0 = vzip1q_s8 (c1, d1); d0 = vzip2q_s8 (c1, d1); e0 = vzip1q_s8 (e1, f1); f0 = vzip2q_s8 (e1, f1); g0 = vzip1q_s8 (g1, h1); h0 = vzip2q_s8 (g1, h1); a1 = (int8x16_t) vzip1q_s32 (vreinterpretq_s32_s8 (a0), vreinterpretq_s32_s8 (c0)); b1 = (int8x16_t) vzip2q_s32 (vreinterpretq_s32_s8 (a0), vreinterpretq_s32_s8 (c0)); c1 = (int8x16_t) vzip1q_s32 (vreinterpretq_s32_s8 (b0), vreinterpretq_s32_s8 (d0)); d1 = (int8x16_t) vzip2q_s32 (vreinterpretq_s32_s8 (b0), vreinterpretq_s32_s8 (d0)); e1 = (int8x16_t) vzip1q_s32 (vreinterpretq_s32_s8 (e0), vreinterpretq_s32_s8 (g0)); f1 = (int8x16_t) vzip2q_s32 (vreinterpretq_s32_s8 (e0), vreinterpretq_s32_s8 (g0)); g1 = (int8x16_t) vzip1q_s32 (vreinterpretq_s32_s8 (f0), vreinterpretq_s32_s8 (h0)); h1 = (int8x16_t) vzip2q_s32 (vreinterpretq_s32_s8 (f0), vreinterpretq_s32_s8 (h0)); a0 = (int8x16_t) vzip1q_s64 (vreinterpretq_s64_s8 (a1), vreinterpretq_s64_s8 (e1)); b0 = (int8x16_t) vzip2q_s64 (vreinterpretq_s64_s8 (a1), vreinterpretq_s64_s8 (e1)); c0 = (int8x16_t) vzip1q_s64 (vreinterpretq_s64_s8 (b1), vreinterpretq_s64_s8 (f1)); d0 = (int8x16_t) vzip2q_s64 (vreinterpretq_s64_s8 (b1), vreinterpretq_s64_s8 (f1)); e0 = (int8x16_t) vzip1q_s64 (vreinterpretq_s64_s8 (c1), vreinterpretq_s64_s8 (g1)); f0 = (int8x16_t) vzip2q_s64 (vreinterpretq_s64_s8 (c1), vreinterpretq_s64_s8 (g1)); g0 = (int8x16_t) vzip1q_s64 (vreinterpretq_s64_s8 (d1), vreinterpretq_s64_s8 (h1)); h0 = (int8x16_t) vzip2q_s64 (vreinterpretq_s64_s8 (d1), vreinterpretq_s64_s8 (h1)); vst1q_s8(out_b + 0*size + ii, a0); vst1q_s8(out_b + 1*size + ii, b0); vst1q_s8(out_b + 2*size + ii, c0); vst1q_s8(out_b + 3*size + ii, d0); vst1q_s8(out_b + 4*size + ii, e0); vst1q_s8(out_b + 5*size + ii, f0); vst1q_s8(out_b + 6*size + ii, g0); vst1q_s8(out_b + 7*size + ii, h0); } return bshuf_trans_byte_elem_remainder(in, out, size, 8, size - size % 16); } /* Transpose bytes within elements using best NEON algorithm available. */ int64_t bshuf_trans_byte_elem_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; // Trivial cases: power of 2 bytes. switch (elem_size) { case 1: count = bshuf_copy(in, out, size, elem_size); return count; case 2: count = bshuf_trans_byte_elem_NEON_16(in, out, size); return count; case 4: count = bshuf_trans_byte_elem_NEON_32(in, out, size); return count; case 8: count = bshuf_trans_byte_elem_NEON_64(in, out, size); return count; } // Worst case: odd number of bytes. Turns out that this is faster for // (odd * 2) byte elements as well (hence % 4). if (elem_size % 4) { count = bshuf_trans_byte_elem_scal(in, out, size, elem_size); return count; } // Multiple of power of 2: transpose hierarchically. { size_t nchunk_elem; void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; if ((elem_size % 8) == 0) { nchunk_elem = elem_size / 8; TRANS_ELEM_TYPE(in, out, size, nchunk_elem, int64_t); count = bshuf_trans_byte_elem_NEON_64(out, tmp_buf, size * nchunk_elem); bshuf_trans_elem(tmp_buf, out, 8, nchunk_elem, size); } else if ((elem_size % 4) == 0) { nchunk_elem = elem_size / 4; TRANS_ELEM_TYPE(in, out, size, nchunk_elem, int32_t); count = bshuf_trans_byte_elem_NEON_32(out, tmp_buf, size * nchunk_elem); bshuf_trans_elem(tmp_buf, out, 4, nchunk_elem, size); } else { // Not used since scalar algorithm is faster. nchunk_elem = elem_size / 2; TRANS_ELEM_TYPE(in, out, size, nchunk_elem, int16_t); count = bshuf_trans_byte_elem_NEON_16(out, tmp_buf, size * nchunk_elem); bshuf_trans_elem(tmp_buf, out, 2, nchunk_elem, size); } free(tmp_buf); return count; } } /* Creates a mask made up of the most significant * bit of each byte of 'input' */ int32_t move_byte_mask_neon(uint8x16_t input) { return ( ((input[0] & 0x80) >> 7) | (((input[1] & 0x80) >> 7) << 1) | (((input[2] & 0x80) >> 7) << 2) | (((input[3] & 0x80) >> 7) << 3) | (((input[4] & 0x80) >> 7) << 4) | (((input[5] & 0x80) >> 7) << 5) | (((input[6] & 0x80) >> 7) << 6) | (((input[7] & 0x80) >> 7) << 7) | (((input[8] & 0x80) >> 7) << 8) | (((input[9] & 0x80) >> 7) << 9) | (((input[10] & 0x80) >> 7) << 10) | (((input[11] & 0x80) >> 7) << 11) | (((input[12] & 0x80) >> 7) << 12) | (((input[13] & 0x80) >> 7) << 13) | (((input[14] & 0x80) >> 7) << 14) | (((input[15] & 0x80) >> 7) << 15) ); } /* Transpose bits within bytes. */ int64_t bshuf_trans_bit_byte_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { size_t ii, kk; const char* in_b = (const char*) in; char* out_b = (char*) out; uint16_t* out_ui16; int64_t count; size_t nbyte = elem_size * size; CHECK_MULT_EIGHT(nbyte); int16x8_t xmm; int32_t bt; for (ii = 0; ii + 15 < nbyte; ii += 16) { xmm = vld1q_s16((int16_t *) (in_b + ii)); for (kk = 0; kk < 8; kk++) { bt = move_byte_mask_neon((uint8x16_t) xmm); xmm = vshlq_n_s16(xmm, 1); out_ui16 = (uint16_t*) &out_b[((7 - kk) * nbyte + ii) / 8]; *out_ui16 = bt; } } count = bshuf_trans_bit_byte_remainder(in, out, size, elem_size, nbyte - nbyte % 16); return count; } /* Transpose bits within elements. */ int64_t bshuf_trans_bit_elem_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; CHECK_MULT_EIGHT(size); void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; count = bshuf_trans_byte_elem_NEON(in, out, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_trans_bit_byte_NEON(out, tmp_buf, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_trans_bitrow_eight(tmp_buf, out, size, elem_size); free(tmp_buf); return count; } /* For data organized into a row for each bit (8 * elem_size rows), transpose * the bytes. */ int64_t bshuf_trans_byte_bitrow_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { size_t ii, jj; const char* in_b = (const char*) in; char* out_b = (char*) out; CHECK_MULT_EIGHT(size); size_t nrows = 8 * elem_size; size_t nbyte_row = size / 8; int8x16_t a0, b0, c0, d0, e0, f0, g0, h0; int8x16_t a1, b1, c1, d1, e1, f1, g1, h1; int64x1_t *as, *bs, *cs, *ds, *es, *fs, *gs, *hs; for (ii = 0; ii + 7 < nrows; ii += 8) { for (jj = 0; jj + 15 < nbyte_row; jj += 16) { a0 = vld1q_s8(in_b + (ii + 0)*nbyte_row + jj); b0 = vld1q_s8(in_b + (ii + 1)*nbyte_row + jj); c0 = vld1q_s8(in_b + (ii + 2)*nbyte_row + jj); d0 = vld1q_s8(in_b + (ii + 3)*nbyte_row + jj); e0 = vld1q_s8(in_b + (ii + 4)*nbyte_row + jj); f0 = vld1q_s8(in_b + (ii + 5)*nbyte_row + jj); g0 = vld1q_s8(in_b + (ii + 6)*nbyte_row + jj); h0 = vld1q_s8(in_b + (ii + 7)*nbyte_row + jj); a1 = vzip1q_s8(a0, b0); b1 = vzip1q_s8(c0, d0); c1 = vzip1q_s8(e0, f0); d1 = vzip1q_s8(g0, h0); e1 = vzip2q_s8(a0, b0); f1 = vzip2q_s8(c0, d0); g1 = vzip2q_s8(e0, f0); h1 = vzip2q_s8(g0, h0); a0 = (int8x16_t) vzip1q_s16 (vreinterpretq_s16_s8 (a1), vreinterpretq_s16_s8 (b1)); b0= (int8x16_t) vzip1q_s16 (vreinterpretq_s16_s8 (c1), vreinterpretq_s16_s8 (d1)); c0 = (int8x16_t) vzip2q_s16 (vreinterpretq_s16_s8 (a1), vreinterpretq_s16_s8 (b1)); d0 = (int8x16_t) vzip2q_s16 (vreinterpretq_s16_s8 (c1), vreinterpretq_s16_s8 (d1)); e0 = (int8x16_t) vzip1q_s16 (vreinterpretq_s16_s8 (e1), vreinterpretq_s16_s8 (f1)); f0 = (int8x16_t) vzip1q_s16 (vreinterpretq_s16_s8 (g1), vreinterpretq_s16_s8 (h1)); g0 = (int8x16_t) vzip2q_s16 (vreinterpretq_s16_s8 (e1), vreinterpretq_s16_s8 (f1)); h0 = (int8x16_t) vzip2q_s16 (vreinterpretq_s16_s8 (g1), vreinterpretq_s16_s8 (h1)); a1 = (int8x16_t) vzip1q_s32 (vreinterpretq_s32_s8 (a0), vreinterpretq_s32_s8 (b0)); b1 = (int8x16_t) vzip2q_s32 (vreinterpretq_s32_s8 (a0), vreinterpretq_s32_s8 (b0)); c1 = (int8x16_t) vzip1q_s32 (vreinterpretq_s32_s8 (c0), vreinterpretq_s32_s8 (d0)); d1 = (int8x16_t) vzip2q_s32 (vreinterpretq_s32_s8 (c0), vreinterpretq_s32_s8 (d0)); e1 = (int8x16_t) vzip1q_s32 (vreinterpretq_s32_s8 (e0), vreinterpretq_s32_s8 (f0)); f1 = (int8x16_t) vzip2q_s32 (vreinterpretq_s32_s8 (e0), vreinterpretq_s32_s8 (f0)); g1 = (int8x16_t) vzip1q_s32 (vreinterpretq_s32_s8 (g0), vreinterpretq_s32_s8 (h0)); h1 = (int8x16_t) vzip2q_s32 (vreinterpretq_s32_s8 (g0), vreinterpretq_s32_s8 (h0)); as = (int64x1_t *) &a1; bs = (int64x1_t *) &b1; cs = (int64x1_t *) &c1; ds = (int64x1_t *) &d1; es = (int64x1_t *) &e1; fs = (int64x1_t *) &f1; gs = (int64x1_t *) &g1; hs = (int64x1_t *) &h1; vst1_s64((int64_t *)(out_b + (jj + 0) * nrows + ii), *as); vst1_s64((int64_t *)(out_b + (jj + 1) * nrows + ii), *(as + 1)); vst1_s64((int64_t *)(out_b + (jj + 2) * nrows + ii), *bs); vst1_s64((int64_t *)(out_b + (jj + 3) * nrows + ii), *(bs + 1)); vst1_s64((int64_t *)(out_b + (jj + 4) * nrows + ii), *cs); vst1_s64((int64_t *)(out_b + (jj + 5) * nrows + ii), *(cs + 1)); vst1_s64((int64_t *)(out_b + (jj + 6) * nrows + ii), *ds); vst1_s64((int64_t *)(out_b + (jj + 7) * nrows + ii), *(ds + 1)); vst1_s64((int64_t *)(out_b + (jj + 8) * nrows + ii), *es); vst1_s64((int64_t *)(out_b + (jj + 9) * nrows + ii), *(es + 1)); vst1_s64((int64_t *)(out_b + (jj + 10) * nrows + ii), *fs); vst1_s64((int64_t *)(out_b + (jj + 11) * nrows + ii), *(fs + 1)); vst1_s64((int64_t *)(out_b + (jj + 12) * nrows + ii), *gs); vst1_s64((int64_t *)(out_b + (jj + 13) * nrows + ii), *(gs + 1)); vst1_s64((int64_t *)(out_b + (jj + 14) * nrows + ii), *hs); vst1_s64((int64_t *)(out_b + (jj + 15) * nrows + ii), *(hs + 1)); } for (jj = nbyte_row - nbyte_row % 16; jj < nbyte_row; jj ++) { out_b[jj * nrows + ii + 0] = in_b[(ii + 0)*nbyte_row + jj]; out_b[jj * nrows + ii + 1] = in_b[(ii + 1)*nbyte_row + jj]; out_b[jj * nrows + ii + 2] = in_b[(ii + 2)*nbyte_row + jj]; out_b[jj * nrows + ii + 3] = in_b[(ii + 3)*nbyte_row + jj]; out_b[jj * nrows + ii + 4] = in_b[(ii + 4)*nbyte_row + jj]; out_b[jj * nrows + ii + 5] = in_b[(ii + 5)*nbyte_row + jj]; out_b[jj * nrows + ii + 6] = in_b[(ii + 6)*nbyte_row + jj]; out_b[jj * nrows + ii + 7] = in_b[(ii + 7)*nbyte_row + jj]; } } return size * elem_size; } /* Shuffle bits within the bytes of eight element blocks. */ int64_t bshuf_shuffle_bit_eightelem_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { CHECK_MULT_EIGHT(size); // With a bit of care, this could be written such that such that it is // in_buf = out_buf safe. const char* in_b = (const char*) in; uint16_t* out_ui16 = (uint16_t*) out; size_t ii, jj, kk; size_t nbyte = elem_size * size; int16x8_t xmm; int32_t bt; if (elem_size % 2) { bshuf_shuffle_bit_eightelem_scal(in, out, size, elem_size); } else { for (ii = 0; ii + 8 * elem_size - 1 < nbyte; ii += 8 * elem_size) { for (jj = 0; jj + 15 < 8 * elem_size; jj += 16) { xmm = vld1q_s16((int16_t *) &in_b[ii + jj]); for (kk = 0; kk < 8; kk++) { bt = move_byte_mask_neon((uint8x16_t) xmm); xmm = vshlq_n_s16(xmm, 1); size_t ind = (ii + jj / 8 + (7 - kk) * elem_size); out_ui16[ind / 2] = bt; } } } } return size * elem_size; } /* Untranspose bits within elements. */ int64_t bshuf_untrans_bit_elem_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; CHECK_MULT_EIGHT(size); void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; count = bshuf_trans_byte_bitrow_NEON(in, tmp_buf, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_shuffle_bit_eightelem_NEON(tmp_buf, out, size, elem_size); free(tmp_buf); return count; } #else // #ifdef USEARMNEON int64_t bshuf_untrans_bit_elem_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { return -13; } int64_t bshuf_trans_bit_elem_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { return -13; } int64_t bshuf_trans_byte_bitrow_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { return -13; } int64_t bshuf_trans_bit_byte_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { return -13; } int64_t bshuf_trans_byte_elem_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { return -13; } int64_t bshuf_trans_byte_elem_NEON_64(const void* in, void* out, const size_t size) { return -13; } int64_t bshuf_trans_byte_elem_NEON_32(const void* in, void* out, const size_t size) { return -13; } int64_t bshuf_trans_byte_elem_NEON_16(const void* in, void* out, const size_t size) { return -13; } int64_t bshuf_shuffle_bit_eightelem_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { return -13; } #endif /* ---- Worker code that uses SSE2 ---- * * The following code makes use of the SSE2 instruction set and specialized * 16 byte registers. The SSE2 instructions are present on modern x86 * processors. The first Intel processor microarchitecture supporting SSE2 was * Pentium 4 (2000). * */ #ifdef USESSE2 /* Transpose bytes within elements for 16 bit elements. */ int64_t bshuf_trans_byte_elem_SSE_16(const void* in, void* out, const size_t size) { size_t ii; const char *in_b = (const char*) in; char *out_b = (char*) out; __m128i a0, b0, a1, b1; for (ii=0; ii + 15 < size; ii += 16) { a0 = _mm_loadu_si128((__m128i *) &in_b[2*ii + 0*16]); b0 = _mm_loadu_si128((__m128i *) &in_b[2*ii + 1*16]); a1 = _mm_unpacklo_epi8(a0, b0); b1 = _mm_unpackhi_epi8(a0, b0); a0 = _mm_unpacklo_epi8(a1, b1); b0 = _mm_unpackhi_epi8(a1, b1); a1 = _mm_unpacklo_epi8(a0, b0); b1 = _mm_unpackhi_epi8(a0, b0); a0 = _mm_unpacklo_epi8(a1, b1); b0 = _mm_unpackhi_epi8(a1, b1); _mm_storeu_si128((__m128i *) &out_b[0*size + ii], a0); _mm_storeu_si128((__m128i *) &out_b[1*size + ii], b0); } return bshuf_trans_byte_elem_remainder(in, out, size, 2, size - size % 16); } /* Transpose bytes within elements for 32 bit elements. */ int64_t bshuf_trans_byte_elem_SSE_32(const void* in, void* out, const size_t size) { size_t ii; const char *in_b; char *out_b; in_b = (const char*) in; out_b = (char*) out; __m128i a0, b0, c0, d0, a1, b1, c1, d1; for (ii=0; ii + 15 < size; ii += 16) { a0 = _mm_loadu_si128((__m128i *) &in_b[4*ii + 0*16]); b0 = _mm_loadu_si128((__m128i *) &in_b[4*ii + 1*16]); c0 = _mm_loadu_si128((__m128i *) &in_b[4*ii + 2*16]); d0 = _mm_loadu_si128((__m128i *) &in_b[4*ii + 3*16]); a1 = _mm_unpacklo_epi8(a0, b0); b1 = _mm_unpackhi_epi8(a0, b0); c1 = _mm_unpacklo_epi8(c0, d0); d1 = _mm_unpackhi_epi8(c0, d0); a0 = _mm_unpacklo_epi8(a1, b1); b0 = _mm_unpackhi_epi8(a1, b1); c0 = _mm_unpacklo_epi8(c1, d1); d0 = _mm_unpackhi_epi8(c1, d1); a1 = _mm_unpacklo_epi8(a0, b0); b1 = _mm_unpackhi_epi8(a0, b0); c1 = _mm_unpacklo_epi8(c0, d0); d1 = _mm_unpackhi_epi8(c0, d0); a0 = _mm_unpacklo_epi64(a1, c1); b0 = _mm_unpackhi_epi64(a1, c1); c0 = _mm_unpacklo_epi64(b1, d1); d0 = _mm_unpackhi_epi64(b1, d1); _mm_storeu_si128((__m128i *) &out_b[0*size + ii], a0); _mm_storeu_si128((__m128i *) &out_b[1*size + ii], b0); _mm_storeu_si128((__m128i *) &out_b[2*size + ii], c0); _mm_storeu_si128((__m128i *) &out_b[3*size + ii], d0); } return bshuf_trans_byte_elem_remainder(in, out, size, 4, size - size % 16); } /* Transpose bytes within elements for 64 bit elements. */ int64_t bshuf_trans_byte_elem_SSE_64(const void* in, void* out, const size_t size) { size_t ii; const char* in_b = (const char*) in; char* out_b = (char*) out; __m128i a0, b0, c0, d0, e0, f0, g0, h0; __m128i a1, b1, c1, d1, e1, f1, g1, h1; for (ii=0; ii + 15 < size; ii += 16) { a0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 0*16]); b0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 1*16]); c0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 2*16]); d0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 3*16]); e0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 4*16]); f0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 5*16]); g0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 6*16]); h0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 7*16]); a1 = _mm_unpacklo_epi8(a0, b0); b1 = _mm_unpackhi_epi8(a0, b0); c1 = _mm_unpacklo_epi8(c0, d0); d1 = _mm_unpackhi_epi8(c0, d0); e1 = _mm_unpacklo_epi8(e0, f0); f1 = _mm_unpackhi_epi8(e0, f0); g1 = _mm_unpacklo_epi8(g0, h0); h1 = _mm_unpackhi_epi8(g0, h0); a0 = _mm_unpacklo_epi8(a1, b1); b0 = _mm_unpackhi_epi8(a1, b1); c0 = _mm_unpacklo_epi8(c1, d1); d0 = _mm_unpackhi_epi8(c1, d1); e0 = _mm_unpacklo_epi8(e1, f1); f0 = _mm_unpackhi_epi8(e1, f1); g0 = _mm_unpacklo_epi8(g1, h1); h0 = _mm_unpackhi_epi8(g1, h1); a1 = _mm_unpacklo_epi32(a0, c0); b1 = _mm_unpackhi_epi32(a0, c0); c1 = _mm_unpacklo_epi32(b0, d0); d1 = _mm_unpackhi_epi32(b0, d0); e1 = _mm_unpacklo_epi32(e0, g0); f1 = _mm_unpackhi_epi32(e0, g0); g1 = _mm_unpacklo_epi32(f0, h0); h1 = _mm_unpackhi_epi32(f0, h0); a0 = _mm_unpacklo_epi64(a1, e1); b0 = _mm_unpackhi_epi64(a1, e1); c0 = _mm_unpacklo_epi64(b1, f1); d0 = _mm_unpackhi_epi64(b1, f1); e0 = _mm_unpacklo_epi64(c1, g1); f0 = _mm_unpackhi_epi64(c1, g1); g0 = _mm_unpacklo_epi64(d1, h1); h0 = _mm_unpackhi_epi64(d1, h1); _mm_storeu_si128((__m128i *) &out_b[0*size + ii], a0); _mm_storeu_si128((__m128i *) &out_b[1*size + ii], b0); _mm_storeu_si128((__m128i *) &out_b[2*size + ii], c0); _mm_storeu_si128((__m128i *) &out_b[3*size + ii], d0); _mm_storeu_si128((__m128i *) &out_b[4*size + ii], e0); _mm_storeu_si128((__m128i *) &out_b[5*size + ii], f0); _mm_storeu_si128((__m128i *) &out_b[6*size + ii], g0); _mm_storeu_si128((__m128i *) &out_b[7*size + ii], h0); } return bshuf_trans_byte_elem_remainder(in, out, size, 8, size - size % 16); } /* Transpose bytes within elements using best SSE algorithm available. */ int64_t bshuf_trans_byte_elem_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; // Trivial cases: power of 2 bytes. switch (elem_size) { case 1: count = bshuf_copy(in, out, size, elem_size); return count; case 2: count = bshuf_trans_byte_elem_SSE_16(in, out, size); return count; case 4: count = bshuf_trans_byte_elem_SSE_32(in, out, size); return count; case 8: count = bshuf_trans_byte_elem_SSE_64(in, out, size); return count; } // Worst case: odd number of bytes. Turns out that this is faster for // (odd * 2) byte elements as well (hence % 4). if (elem_size % 4) { count = bshuf_trans_byte_elem_scal(in, out, size, elem_size); return count; } // Multiple of power of 2: transpose hierarchically. { size_t nchunk_elem; void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; if ((elem_size % 8) == 0) { nchunk_elem = elem_size / 8; TRANS_ELEM_TYPE(in, out, size, nchunk_elem, int64_t); count = bshuf_trans_byte_elem_SSE_64(out, tmp_buf, size * nchunk_elem); bshuf_trans_elem(tmp_buf, out, 8, nchunk_elem, size); } else if ((elem_size % 4) == 0) { nchunk_elem = elem_size / 4; TRANS_ELEM_TYPE(in, out, size, nchunk_elem, int32_t); count = bshuf_trans_byte_elem_SSE_32(out, tmp_buf, size * nchunk_elem); bshuf_trans_elem(tmp_buf, out, 4, nchunk_elem, size); } else { // Not used since scalar algorithm is faster. nchunk_elem = elem_size / 2; TRANS_ELEM_TYPE(in, out, size, nchunk_elem, int16_t); count = bshuf_trans_byte_elem_SSE_16(out, tmp_buf, size * nchunk_elem); bshuf_trans_elem(tmp_buf, out, 2, nchunk_elem, size); } free(tmp_buf); return count; } } /* Transpose bits within bytes. */ int64_t bshuf_trans_bit_byte_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { size_t ii, kk; const char* in_b = (const char*) in; char* out_b = (char*) out; uint16_t* out_ui16; int64_t count; size_t nbyte = elem_size * size; CHECK_MULT_EIGHT(nbyte); __m128i xmm; int32_t bt; for (ii = 0; ii + 15 < nbyte; ii += 16) { xmm = _mm_loadu_si128((__m128i *) &in_b[ii]); for (kk = 0; kk < 8; kk++) { bt = _mm_movemask_epi8(xmm); xmm = _mm_slli_epi16(xmm, 1); out_ui16 = (uint16_t*) &out_b[((7 - kk) * nbyte + ii) / 8]; *out_ui16 = bt; } } count = bshuf_trans_bit_byte_remainder(in, out, size, elem_size, nbyte - nbyte % 16); return count; } /* Transpose bits within elements. */ int64_t bshuf_trans_bit_elem_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; CHECK_MULT_EIGHT(size); void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; count = bshuf_trans_byte_elem_SSE(in, out, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_trans_bit_byte_SSE(out, tmp_buf, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_trans_bitrow_eight(tmp_buf, out, size, elem_size); free(tmp_buf); return count; } /* For data organized into a row for each bit (8 * elem_size rows), transpose * the bytes. */ int64_t bshuf_trans_byte_bitrow_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { size_t ii, jj; const char* in_b = (const char*) in; char* out_b = (char*) out; CHECK_MULT_EIGHT(size); size_t nrows = 8 * elem_size; size_t nbyte_row = size / 8; __m128i a0, b0, c0, d0, e0, f0, g0, h0; __m128i a1, b1, c1, d1, e1, f1, g1, h1; __m128 *as, *bs, *cs, *ds, *es, *fs, *gs, *hs; for (ii = 0; ii + 7 < nrows; ii += 8) { for (jj = 0; jj + 15 < nbyte_row; jj += 16) { a0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 0)*nbyte_row + jj]); b0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 1)*nbyte_row + jj]); c0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 2)*nbyte_row + jj]); d0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 3)*nbyte_row + jj]); e0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 4)*nbyte_row + jj]); f0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 5)*nbyte_row + jj]); g0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 6)*nbyte_row + jj]); h0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 7)*nbyte_row + jj]); a1 = _mm_unpacklo_epi8(a0, b0); b1 = _mm_unpacklo_epi8(c0, d0); c1 = _mm_unpacklo_epi8(e0, f0); d1 = _mm_unpacklo_epi8(g0, h0); e1 = _mm_unpackhi_epi8(a0, b0); f1 = _mm_unpackhi_epi8(c0, d0); g1 = _mm_unpackhi_epi8(e0, f0); h1 = _mm_unpackhi_epi8(g0, h0); a0 = _mm_unpacklo_epi16(a1, b1); b0 = _mm_unpacklo_epi16(c1, d1); c0 = _mm_unpackhi_epi16(a1, b1); d0 = _mm_unpackhi_epi16(c1, d1); e0 = _mm_unpacklo_epi16(e1, f1); f0 = _mm_unpacklo_epi16(g1, h1); g0 = _mm_unpackhi_epi16(e1, f1); h0 = _mm_unpackhi_epi16(g1, h1); a1 = _mm_unpacklo_epi32(a0, b0); b1 = _mm_unpackhi_epi32(a0, b0); c1 = _mm_unpacklo_epi32(c0, d0); d1 = _mm_unpackhi_epi32(c0, d0); e1 = _mm_unpacklo_epi32(e0, f0); f1 = _mm_unpackhi_epi32(e0, f0); g1 = _mm_unpacklo_epi32(g0, h0); h1 = _mm_unpackhi_epi32(g0, h0); // We don't have a storeh instruction for integers, so interpret // as a float. Have a storel (_mm_storel_epi64). as = (__m128 *) &a1; bs = (__m128 *) &b1; cs = (__m128 *) &c1; ds = (__m128 *) &d1; es = (__m128 *) &e1; fs = (__m128 *) &f1; gs = (__m128 *) &g1; hs = (__m128 *) &h1; _mm_storel_pi((__m64 *) &out_b[(jj + 0) * nrows + ii], *as); _mm_storel_pi((__m64 *) &out_b[(jj + 2) * nrows + ii], *bs); _mm_storel_pi((__m64 *) &out_b[(jj + 4) * nrows + ii], *cs); _mm_storel_pi((__m64 *) &out_b[(jj + 6) * nrows + ii], *ds); _mm_storel_pi((__m64 *) &out_b[(jj + 8) * nrows + ii], *es); _mm_storel_pi((__m64 *) &out_b[(jj + 10) * nrows + ii], *fs); _mm_storel_pi((__m64 *) &out_b[(jj + 12) * nrows + ii], *gs); _mm_storel_pi((__m64 *) &out_b[(jj + 14) * nrows + ii], *hs); _mm_storeh_pi((__m64 *) &out_b[(jj + 1) * nrows + ii], *as); _mm_storeh_pi((__m64 *) &out_b[(jj + 3) * nrows + ii], *bs); _mm_storeh_pi((__m64 *) &out_b[(jj + 5) * nrows + ii], *cs); _mm_storeh_pi((__m64 *) &out_b[(jj + 7) * nrows + ii], *ds); _mm_storeh_pi((__m64 *) &out_b[(jj + 9) * nrows + ii], *es); _mm_storeh_pi((__m64 *) &out_b[(jj + 11) * nrows + ii], *fs); _mm_storeh_pi((__m64 *) &out_b[(jj + 13) * nrows + ii], *gs); _mm_storeh_pi((__m64 *) &out_b[(jj + 15) * nrows + ii], *hs); } for (jj = nbyte_row - nbyte_row % 16; jj < nbyte_row; jj ++) { out_b[jj * nrows + ii + 0] = in_b[(ii + 0)*nbyte_row + jj]; out_b[jj * nrows + ii + 1] = in_b[(ii + 1)*nbyte_row + jj]; out_b[jj * nrows + ii + 2] = in_b[(ii + 2)*nbyte_row + jj]; out_b[jj * nrows + ii + 3] = in_b[(ii + 3)*nbyte_row + jj]; out_b[jj * nrows + ii + 4] = in_b[(ii + 4)*nbyte_row + jj]; out_b[jj * nrows + ii + 5] = in_b[(ii + 5)*nbyte_row + jj]; out_b[jj * nrows + ii + 6] = in_b[(ii + 6)*nbyte_row + jj]; out_b[jj * nrows + ii + 7] = in_b[(ii + 7)*nbyte_row + jj]; } } return size * elem_size; } /* Shuffle bits within the bytes of eight element blocks. */ int64_t bshuf_shuffle_bit_eightelem_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { CHECK_MULT_EIGHT(size); // With a bit of care, this could be written such that such that it is // in_buf = out_buf safe. const char* in_b = (const char*) in; uint16_t* out_ui16 = (uint16_t*) out; size_t ii, jj, kk; size_t nbyte = elem_size * size; __m128i xmm; int32_t bt; if (elem_size % 2) { bshuf_shuffle_bit_eightelem_scal(in, out, size, elem_size); } else { for (ii = 0; ii + 8 * elem_size - 1 < nbyte; ii += 8 * elem_size) { for (jj = 0; jj + 15 < 8 * elem_size; jj += 16) { xmm = _mm_loadu_si128((__m128i *) &in_b[ii + jj]); for (kk = 0; kk < 8; kk++) { bt = _mm_movemask_epi8(xmm); xmm = _mm_slli_epi16(xmm, 1); size_t ind = (ii + jj / 8 + (7 - kk) * elem_size); out_ui16[ind / 2] = bt; } } } } return size * elem_size; } /* Untranspose bits within elements. */ int64_t bshuf_untrans_bit_elem_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; CHECK_MULT_EIGHT(size); void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; count = bshuf_trans_byte_bitrow_SSE(in, tmp_buf, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_shuffle_bit_eightelem_SSE(tmp_buf, out, size, elem_size); free(tmp_buf); return count; } #else // #ifdef USESSE2 int64_t bshuf_untrans_bit_elem_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { return -11; } int64_t bshuf_trans_bit_elem_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { return -11; } int64_t bshuf_trans_byte_bitrow_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { return -11; } int64_t bshuf_trans_bit_byte_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { return -11; } int64_t bshuf_trans_byte_elem_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { return -11; } int64_t bshuf_trans_byte_elem_SSE_64(const void* in, void* out, const size_t size) { return -11; } int64_t bshuf_trans_byte_elem_SSE_32(const void* in, void* out, const size_t size) { return -11; } int64_t bshuf_trans_byte_elem_SSE_16(const void* in, void* out, const size_t size) { return -11; } int64_t bshuf_shuffle_bit_eightelem_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { return -11; } #endif // #ifdef USESSE2 /* ---- Code that requires AVX2. Intel Haswell (2013) and later. ---- */ /* ---- Worker code that uses AVX2 ---- * * The following code makes use of the AVX2 instruction set and specialized * 32 byte registers. The AVX2 instructions are present on newer x86 * processors. The first Intel processor microarchitecture supporting AVX2 was * Haswell (2013). * */ #ifdef USEAVX2 /* Transpose bits within bytes. */ int64_t bshuf_trans_bit_byte_AVX(const void* in, void* out, const size_t size, const size_t elem_size) { size_t ii, kk; const char* in_b = (const char*) in; char* out_b = (char*) out; int32_t* out_i32; size_t nbyte = elem_size * size; int64_t count; __m256i ymm; int32_t bt; for (ii = 0; ii + 31 < nbyte; ii += 32) { ymm = _mm256_loadu_si256((__m256i *) &in_b[ii]); for (kk = 0; kk < 8; kk++) { bt = _mm256_movemask_epi8(ymm); ymm = _mm256_slli_epi16(ymm, 1); out_i32 = (int32_t*) &out_b[((7 - kk) * nbyte + ii) / 8]; *out_i32 = bt; } } count = bshuf_trans_bit_byte_remainder(in, out, size, elem_size, nbyte - nbyte % 32); return count; } /* Transpose bits within elements. */ int64_t bshuf_trans_bit_elem_AVX(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; CHECK_MULT_EIGHT(size); void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; count = bshuf_trans_byte_elem_SSE(in, out, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_trans_bit_byte_AVX(out, tmp_buf, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_trans_bitrow_eight(tmp_buf, out, size, elem_size); free(tmp_buf); return count; } /* For data organized into a row for each bit (8 * elem_size rows), transpose * the bytes. */ int64_t bshuf_trans_byte_bitrow_AVX(const void* in, void* out, const size_t size, const size_t elem_size) { size_t hh, ii, jj, kk, mm; const char* in_b = (const char*) in; char* out_b = (char*) out; CHECK_MULT_EIGHT(size); size_t nrows = 8 * elem_size; size_t nbyte_row = size / 8; if (elem_size % 4) return bshuf_trans_byte_bitrow_SSE(in, out, size, elem_size); __m256i ymm_0[8]; __m256i ymm_1[8]; __m256i ymm_storeage[8][4]; for (jj = 0; jj + 31 < nbyte_row; jj += 32) { for (ii = 0; ii + 3 < elem_size; ii += 4) { for (hh = 0; hh < 4; hh ++) { for (kk = 0; kk < 8; kk ++){ ymm_0[kk] = _mm256_loadu_si256((__m256i *) &in_b[ (ii * 8 + hh * 8 + kk) * nbyte_row + jj]); } for (kk = 0; kk < 4; kk ++){ ymm_1[kk] = _mm256_unpacklo_epi8(ymm_0[kk * 2], ymm_0[kk * 2 + 1]); ymm_1[kk + 4] = _mm256_unpackhi_epi8(ymm_0[kk * 2], ymm_0[kk * 2 + 1]); } for (kk = 0; kk < 2; kk ++){ for (mm = 0; mm < 2; mm ++){ ymm_0[kk * 4 + mm] = _mm256_unpacklo_epi16( ymm_1[kk * 4 + mm * 2], ymm_1[kk * 4 + mm * 2 + 1]); ymm_0[kk * 4 + mm + 2] = _mm256_unpackhi_epi16( ymm_1[kk * 4 + mm * 2], ymm_1[kk * 4 + mm * 2 + 1]); } } for (kk = 0; kk < 4; kk ++){ ymm_1[kk * 2] = _mm256_unpacklo_epi32(ymm_0[kk * 2], ymm_0[kk * 2 + 1]); ymm_1[kk * 2 + 1] = _mm256_unpackhi_epi32(ymm_0[kk * 2], ymm_0[kk * 2 + 1]); } for (kk = 0; kk < 8; kk ++){ ymm_storeage[kk][hh] = ymm_1[kk]; } } for (mm = 0; mm < 8; mm ++) { for (kk = 0; kk < 4; kk ++){ ymm_0[kk] = ymm_storeage[mm][kk]; } ymm_1[0] = _mm256_unpacklo_epi64(ymm_0[0], ymm_0[1]); ymm_1[1] = _mm256_unpacklo_epi64(ymm_0[2], ymm_0[3]); ymm_1[2] = _mm256_unpackhi_epi64(ymm_0[0], ymm_0[1]); ymm_1[3] = _mm256_unpackhi_epi64(ymm_0[2], ymm_0[3]); ymm_0[0] = _mm256_permute2x128_si256(ymm_1[0], ymm_1[1], 32); ymm_0[1] = _mm256_permute2x128_si256(ymm_1[2], ymm_1[3], 32); ymm_0[2] = _mm256_permute2x128_si256(ymm_1[0], ymm_1[1], 49); ymm_0[3] = _mm256_permute2x128_si256(ymm_1[2], ymm_1[3], 49); _mm256_storeu_si256((__m256i *) &out_b[ (jj + mm * 2 + 0 * 16) * nrows + ii * 8], ymm_0[0]); _mm256_storeu_si256((__m256i *) &out_b[ (jj + mm * 2 + 0 * 16 + 1) * nrows + ii * 8], ymm_0[1]); _mm256_storeu_si256((__m256i *) &out_b[ (jj + mm * 2 + 1 * 16) * nrows + ii * 8], ymm_0[2]); _mm256_storeu_si256((__m256i *) &out_b[ (jj + mm * 2 + 1 * 16 + 1) * nrows + ii * 8], ymm_0[3]); } } } for (ii = 0; ii < nrows; ii ++ ) { for (jj = nbyte_row - nbyte_row % 32; jj < nbyte_row; jj ++) { out_b[jj * nrows + ii] = in_b[ii * nbyte_row + jj]; } } return size * elem_size; } /* Shuffle bits within the bytes of eight element blocks. */ int64_t bshuf_shuffle_bit_eightelem_AVX(const void* in, void* out, const size_t size, const size_t elem_size) { CHECK_MULT_EIGHT(size); // With a bit of care, this could be written such that such that it is // in_buf = out_buf safe. const char* in_b = (const char*) in; char* out_b = (char*) out; size_t ii, jj, kk; size_t nbyte = elem_size * size; __m256i ymm; int32_t bt; if (elem_size % 4) { return bshuf_shuffle_bit_eightelem_SSE(in, out, size, elem_size); } else { for (jj = 0; jj + 31 < 8 * elem_size; jj += 32) { for (ii = 0; ii + 8 * elem_size - 1 < nbyte; ii += 8 * elem_size) { ymm = _mm256_loadu_si256((__m256i *) &in_b[ii + jj]); for (kk = 0; kk < 8; kk++) { bt = _mm256_movemask_epi8(ymm); ymm = _mm256_slli_epi16(ymm, 1); size_t ind = (ii + jj / 8 + (7 - kk) * elem_size); * (int32_t *) &out_b[ind] = bt; } } } } return size * elem_size; } /* Untranspose bits within elements. */ int64_t bshuf_untrans_bit_elem_AVX(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; CHECK_MULT_EIGHT(size); void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; count = bshuf_trans_byte_bitrow_AVX(in, tmp_buf, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_shuffle_bit_eightelem_AVX(tmp_buf, out, size, elem_size); free(tmp_buf); return count; } #else // #ifdef USEAVX2 int64_t bshuf_trans_bit_byte_AVX(const void* in, void* out, const size_t size, const size_t elem_size) { return -12; } int64_t bshuf_trans_bit_elem_AVX(const void* in, void* out, const size_t size, const size_t elem_size) { return -12; } int64_t bshuf_trans_byte_bitrow_AVX(const void* in, void* out, const size_t size, const size_t elem_size) { return -12; } int64_t bshuf_shuffle_bit_eightelem_AVX(const void* in, void* out, const size_t size, const size_t elem_size) { return -12; } int64_t bshuf_untrans_bit_elem_AVX(const void* in, void* out, const size_t size, const size_t elem_size) { return -12; } #endif // #ifdef USEAVX2 /* ---- Drivers selecting best instruction set at compile time. ---- */ int64_t bshuf_trans_bit_elem(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; #ifdef USEAVX2 count = bshuf_trans_bit_elem_AVX(in, out, size, elem_size); #elif defined(USESSE2) count = bshuf_trans_bit_elem_SSE(in, out, size, elem_size); #elif defined(USEARMNEON) count = bshuf_trans_bit_elem_NEON(in, out, size, elem_size); #else count = bshuf_trans_bit_elem_scal(in, out, size, elem_size); #endif return count; } int64_t bshuf_untrans_bit_elem(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; #ifdef USEAVX2 count = bshuf_untrans_bit_elem_AVX(in, out, size, elem_size); #elif defined(USESSE2) count = bshuf_untrans_bit_elem_SSE(in, out, size, elem_size); #elif defined(USEARMNEON) count = bshuf_untrans_bit_elem_NEON(in, out, size, elem_size); #else count = bshuf_untrans_bit_elem_scal(in, out, size, elem_size); #endif return count; } /* ---- Wrappers for implementing blocking ---- */ /* Wrap a function for processing a single block to process an entire buffer in * parallel. */ int64_t bshuf_blocked_wrap_fun(bshufBlockFunDef fun, const void* in, void* out, \ const size_t size, const size_t elem_size, size_t block_size, const int option) { omp_size_t ii = 0; int64_t err = 0; int64_t count, cum_count=0; size_t last_block_size; size_t leftover_bytes; size_t this_iter; char *last_in; char *last_out; ioc_chain C; ioc_init(&C, in, out); if (block_size == 0) { block_size = bshuf_default_block_size(elem_size); } if (block_size % BSHUF_BLOCKED_MULT) return -81; #if defined(_OPENMP) #pragma omp parallel for schedule(dynamic, 1) \ private(count) reduction(+ : cum_count) #endif for (ii = 0; ii < (omp_size_t)( size / block_size ); ii ++) { count = fun(&C, block_size, elem_size, option); if (count < 0) err = count; cum_count += count; } last_block_size = size % block_size; last_block_size = last_block_size - last_block_size % BSHUF_BLOCKED_MULT; if (last_block_size) { count = fun(&C, last_block_size, elem_size, option); if (count < 0) err = count; cum_count += count; } if (err < 0) return err; leftover_bytes = size % BSHUF_BLOCKED_MULT * elem_size; //this_iter; last_in = (char *) ioc_get_in(&C, &this_iter); ioc_set_next_in(&C, &this_iter, (void *) (last_in + leftover_bytes)); last_out = (char *) ioc_get_out(&C, &this_iter); ioc_set_next_out(&C, &this_iter, (void *) (last_out + leftover_bytes)); memcpy(last_out, last_in, leftover_bytes); ioc_destroy(&C); return cum_count + leftover_bytes; } /* Bitshuffle a single block. */ int64_t bshuf_bitshuffle_block(ioc_chain *C_ptr, \ const size_t size, const size_t elem_size, const int option) { size_t this_iter; const void *in; void *out; int64_t count; in = ioc_get_in(C_ptr, &this_iter); ioc_set_next_in(C_ptr, &this_iter, (void*) ((char*) in + size * elem_size)); out = ioc_get_out(C_ptr, &this_iter); ioc_set_next_out(C_ptr, &this_iter, (void *) ((char *) out + size * elem_size)); count = bshuf_trans_bit_elem(in, out, size, elem_size); return count; } /* Bitunshuffle a single block. */ int64_t bshuf_bitunshuffle_block(ioc_chain* C_ptr, \ const size_t size, const size_t elem_size, const int option) { size_t this_iter; const void *in; void *out; int64_t count; in = ioc_get_in(C_ptr, &this_iter); ioc_set_next_in(C_ptr, &this_iter, (void*) ((char*) in + size * elem_size)); out = ioc_get_out(C_ptr, &this_iter); ioc_set_next_out(C_ptr, &this_iter, (void *) ((char *) out + size * elem_size)); count = bshuf_untrans_bit_elem(in, out, size, elem_size); return count; } /* Write a 64 bit unsigned integer to a buffer in big endian order. */ void bshuf_write_uint64_BE(void* buf, uint64_t num) { int ii; uint8_t* b = (uint8_t*) buf; uint64_t pow28 = 1 << 8; for (ii = 7; ii >= 0; ii--) { b[ii] = num % pow28; num = num / pow28; } } /* Read a 64 bit unsigned integer from a buffer big endian order. */ uint64_t bshuf_read_uint64_BE(void* buf) { int ii; uint8_t* b = (uint8_t*) buf; uint64_t num = 0, pow28 = 1 << 8, cp = 1; for (ii = 7; ii >= 0; ii--) { num += b[ii] * cp; cp *= pow28; } return num; } /* Write a 32 bit unsigned integer to a buffer in big endian order. */ void bshuf_write_uint32_BE(void* buf, uint32_t num) { int ii; uint8_t* b = (uint8_t*) buf; uint32_t pow28 = 1 << 8; for (ii = 3; ii >= 0; ii--) { b[ii] = num % pow28; num = num / pow28; } } /* Read a 32 bit unsigned integer from a buffer big endian order. */ uint32_t bshuf_read_uint32_BE(const void* buf) { int ii; uint8_t* b = (uint8_t*) buf; uint32_t num = 0, pow28 = 1 << 8, cp = 1; for (ii = 3; ii >= 0; ii--) { num += b[ii] * cp; cp *= pow28; } return num; } /* ---- Public functions ---- * * See header file for description and usage. * */ size_t bshuf_default_block_size(const size_t elem_size) { // This function needs to be absolutely stable between versions. // Otherwise encoded data will not be decodable. size_t block_size = BSHUF_TARGET_BLOCK_SIZE_B / elem_size; // Ensure it is a required multiple. block_size = (block_size / BSHUF_BLOCKED_MULT) * BSHUF_BLOCKED_MULT; return MAX(block_size, BSHUF_MIN_RECOMMEND_BLOCK); } int64_t bshuf_bitshuffle(const void* in, void* out, const size_t size, const size_t elem_size, size_t block_size) { return bshuf_blocked_wrap_fun(&bshuf_bitshuffle_block, in, out, size, elem_size, block_size, 0/*option*/); } int64_t bshuf_bitunshuffle(const void* in, void* out, const size_t size, const size_t elem_size, size_t block_size) { return bshuf_blocked_wrap_fun(&bshuf_bitunshuffle_block, in, out, size, elem_size, block_size, 0/*option*/); } #undef TRANS_BIT_8X8 #undef TRANS_ELEM_TYPE #undef MAX #undef CHECK_MULT_EIGHT #undef CHECK_ERR_FREE #undef USESSE2 #undef USEAVX2
v3-conduct.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <omp.h> #include <mpi.h> /** * 2) * Parallelization via MPI should be favoured when huge data sets * are processes on big cluster with different nodes. Additionally * OpenMP can be used to further parallelize the work on each node. * This way it's possible to divide the workload over more cores * than those that would be available on a single node. * * 3) a) * Partitioning the grid into rows is the easiest to implement and * very likely also the fastest version, due to minimal amount of * communications (compared to partitioning into squares) and efficient * cache usage. Partittioning into rows however, results in more data * being sent compared to squares which could result in a lower perfomance * with big grid sizes. **/ #define DEFAULT_GRIDSIZE 128 // Save/ Print only every nth step: #define PRINTSTEP 1 // Run for that many time steps #define DEFAULT_TIMESTEPS 1000 void init_cells(double* grid, int gridsize); void print(double* grid, int padded_grid_size, int time); void save(FILE *f, double* grid, int padded_grid_size, int time); int find_option( int argc, char **argv, const char *option ); int read_int( int argc, char **argv, const char *option, int default_value ); char *read_string( int argc, char **argv, const char *option, char *default_value ); int main(int argc, char** argv) { int numtasks, rank; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &numtasks); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Status status; if( find_option( argc, argv, "-h" ) >= 0 ) { printf( "Options:\n" ); printf( "-h to see this help\n" ); printf( "-n <int> to set the grid size\n" ); printf( "-t <int> to set the number of time steps\n" ); printf( "-o <filename> to specify the output file name\n" ); return 0; } int GRIDSIZE = read_int( argc, argv, "-n", DEFAULT_GRIDSIZE ); // Check gridsize for some basic assumptions if(GRIDSIZE%2) { printf("Only even Gridsize allowed!\n"); return 1; } int TIMESTEPS = read_int( argc, argv, "-t", DEFAULT_TIMESTEPS ); char *savename = read_string( argc, argv, "-o", "sample_conduct.txt" ); FILE *f = savename ? fopen( savename, "w" ) : NULL; if( f == NULL ) { printf( "failed to open %s\n", savename ); return 1; } double *T, *T_block, *Tn_block; // Allocate Grid with a padding on every side for convenience int padded_grid_size = GRIDSIZE+2; int blocksize = GRIDSIZE / numtasks; if(rank == 0) { T=(double *) malloc((padded_grid_size)*(padded_grid_size)*sizeof(double)); // temp grid to hold the calculated data for the next time step init_cells(T,padded_grid_size); } T_block = (double *) malloc(padded_grid_size * (blocksize+2) * sizeof(double)); Tn_block = (double *) malloc(padded_grid_size * (blocksize+2) * sizeof(double)); MPI_Scatter(&T[padded_grid_size], padded_grid_size * blocksize, MPI_DOUBLE, &T_block[padded_grid_size], padded_grid_size * blocksize, MPI_DOUBLE, 0, MPI_COMM_WORLD); // remember -- our grid has a border around it! int last_row = padded_grid_size * (blocksize + 1); int next_to_last_row = last_row - padded_grid_size; for(int t=0;t<TIMESTEPS;t++) { // Loop for the time steps if(rank > 0 && rank < numtasks-1) { MPI_Sendrecv(&T_block[padded_grid_size], padded_grid_size, MPI_DOUBLE, rank-1, 42, T_block, padded_grid_size, MPI_DOUBLE, rank-1, 42, MPI_COMM_WORLD, NULL); MPI_Sendrecv(&T_block[next_to_last_row], padded_grid_size, MPI_DOUBLE, rank+1, 42, &T_block[last_row], padded_grid_size, MPI_DOUBLE, rank+1, 42, MPI_COMM_WORLD, NULL); } else if(rank == 0) { MPI_Sendrecv(&T_block[next_to_last_row], padded_grid_size, MPI_DOUBLE, 1, 42, &T_block[last_row], padded_grid_size, MPI_DOUBLE, 1, 42, MPI_COMM_WORLD, &status); } else if(rank == numtasks-1) { MPI_Sendrecv(&T_block[padded_grid_size], padded_grid_size, MPI_DOUBLE, rank-1, 42, T_block, padded_grid_size, MPI_DOUBLE, rank-1, 42, MPI_COMM_WORLD, &status); } // Calculate grid cells for next timestep #pragma omp parallel for default(none) shared(blocksize, padded_grid_size, Tn_block, T_block) for(int i=1; i<blocksize+1; i++) { for(int j=1; j<padded_grid_size-1; j++) { Tn_block[i*padded_grid_size + j] = (T_block[(i-1)*padded_grid_size+j] + T_block[i*padded_grid_size + (j-1)] \ + T_block[i*padded_grid_size+(j+1)] + T_block[(i+1)*padded_grid_size+j]) / 4.0; } } // copy new grid into old one #pragma omp parallel for default(none) shared(blocksize, padded_grid_size, Tn_block, T_block) for(int i=1; i<blocksize+1; i++) { for(int j=1; j<padded_grid_size-1; j++) { T_block[i*padded_grid_size+j] = Tn_block[i*padded_grid_size+j]; } } MPI_Barrier(MPI_COMM_WORLD); /** * This is a quick and dirty fix to implement the save functionionality. A better way would be to have each thread * save it's part of the grid every PRINTSTEP timestep into it's own file and then merge those individual files, each representing * a part of the grid over time, into one output file at the end of the simulation. This way we can get rid of the Gather * and the non rank 0 threads are not idle during the save process. **/ if(!(t % PRINTSTEP)) { MPI_Gather(&T_block[padded_grid_size], blocksize*padded_grid_size, MPI_DOUBLE, &T[padded_grid_size], blocksize*padded_grid_size, MPI_DOUBLE, 0, MPI_COMM_WORLD); if(rank == 0) save(f,T,padded_grid_size,TIMESTEPS); } } fclose(f); MPI_Finalize(); return 0; } void init_cells(double* grid, int gridsize) { // set everything to zero, even the border #pragma omp parallel for default(none) shared(grid, gridsize) for(int i=0;i<gridsize;i++) { for(int j=0;j<gridsize;j++) { grid[i*gridsize + j]=0; } } // but the most inner 4 cells for(int i=gridsize/2-1;i<=gridsize/2;i++) { for(int j=gridsize/2-1;j<=gridsize/2;j++) { grid[i*gridsize + j]=1; } } } void print(double* grid, int padded_grid_size, int time) { printf("\n\n\n"); int i,j; // we don't want to print the border! for(i=1;i<padded_grid_size-1;i++) { for(j=1;j<padded_grid_size-1;j++) { printf("%.2f ",grid[i*padded_grid_size + j]); } printf("\n"); } } void save( FILE *f, double* grid, int padded_grid_size,int TIMESTEPS) { int i,j; static int first = 1; if( first ) { fprintf( f, "# %d %d\n", TIMESTEPS, padded_grid_size-2 ); first = 0; } for(i = 1; i < padded_grid_size-1; i++ ) { for(j=1; j < padded_grid_size-1; j++) { fprintf( f, "%.g ", grid[i* padded_grid_size + j] ); } fprintf(f,"\n"); } } // // command line option processing // int find_option( int argc, char **argv, const char *option ) { int i; for( i = 1; i < argc; i++ ) if( strcmp( argv[i], option ) == 0 ) return i; return -1; } int read_int( int argc, char **argv, const char *option, int default_value ) { int iplace = find_option( argc, argv, option ); if( iplace >= 0 && iplace < argc-1 ) return atoi( argv[iplace+1] ); return default_value; } char *read_string( int argc, char **argv, const char *option, char *default_value ) { int iplace = find_option( argc, argv, option ); if( iplace >= 0 && iplace < argc-1 ) return argv[iplace+1]; return default_value; }
GB_unop__minv_int8_int8.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__minv_int8_int8 // op(A') function: GB_unop_tran__minv_int8_int8 // C type: int8_t // A type: int8_t // cast: int8_t cij = aij // unaryop: cij = GB_IMINV_SIGNED (aij, 8) #define GB_ATYPE \ int8_t #define GB_CTYPE \ int8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_IMINV_SIGNED (x, 8) ; // casting #define GB_CAST(z, aij) \ int8_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int8_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int8_t z = aij ; \ Cx [pC] = GB_IMINV_SIGNED (z, 8) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_INT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__minv_int8_int8 ( int8_t *Cx, // Cx and Ax may be aliased const int8_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int8_t aij = Ax [p] ; int8_t z = aij ; Cx [p] = GB_IMINV_SIGNED (z, 8) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__minv_int8_int8 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif